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 }})
" 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. 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. Copyright (C) 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 . 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: Copyright (C) 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 . 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 . ================================================ FILE: README.md ================================================
Logo [![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]

Lux

A light desktop proxy app.
lux-docs »

Download for macOS(require macOS 13+) · Windows

Report Bug · Request Feature

- [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

(back to top)

## 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).

(back to top)

## Built With * [![React][React.js]][React-url] * [![Flutter][Flutter]][Flutter-url] * [![Go][Go.dev]][Golang-url]

(back to top)

## 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.

(back to top)

## License Distributed under the GPL License. See `LICENSE.txt` for more information.

(back to top)

## Contact Project Link: [https://github.com/igoogolx/lux](https://github.com/igoogolx/lux)

(back to top)

## Sponsors JetBrains logo. Thanks to Jetbrains provided license!

(back to top)

[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 createState() => _App(); } class _App extends State { 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( 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 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 = []; 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> readConfig() async { try { var homeDir = await getHomeDir(); var configPath = path.join(homeDir, 'config.json'); return await readJsonFile(configPath); } catch (e) { return {}; } } Future> readSetting() async { try { final config = await readConfig(); if (config.containsKey('setting') && config['setting'] is Map) { return config['setting'] as Map; } 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 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 readClientMode() async { var setting = await readSetting(); if (setting.containsKey('lightClientMode') && setting['lightClientMode'] is bool) { if (setting['lightClientMode']) { return ClientMode.light; } } return ClientMode.webview; } Future readAutoLaunch() async { var setting = await readSetting(); if (setting.containsKey('autoLaunch') && setting['autoLaunch'] is bool) { return setting['autoLaunch'] as bool; } return false; } Future readAutoConnect() async { var setting = await readSetting(); if (setting.containsKey('autoConnect') && setting['autoConnect'] is bool) { return setting['autoConnect'] as bool; } return false; } Future 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 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 sortProxyList( List groups, List subscriptions) { final sortedIds = [localServersGroupKey]; for (var i = subscriptions.length - 1; i >= 0; i--) { sortedIds.add(subscriptions[i].id); } final newGroups = []; 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 convertProxyListToGroup( List items, List subscriptions) { Map> 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 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 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 toJson() => { 'id': id, 'name': name, }; } class ProxyList { final List proxies; final String id; ProxyList(this.proxies, this.id); ProxyList.fromJson(Map json) : proxies = json['proxies'] != null ? (json['proxies'] as List) .map((asset) => ProxyItem.fromJson(asset as Map)) .toList() : [], id = (json['selectedId'] as String); Map 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 json) : id = (json['id'] as String), url = (json['url'] as String), name = (json['name'] as String), remark = (json['remark'] as String); Map toJson() => { 'id': id, 'name': name, 'url': url, 'remark': remark, }; } class SubscriptionList { late List value; SubscriptionList(this.value); SubscriptionList.fromJson(Map json) { value = json['subscriptions'] != null ? (json['subscriptions'] as List) .map((asset) => SubscriptionItem.fromJson(asset as Map)) .toList() : []; } Map toJson() => {'value': value}; } class ProxyListGroup { final List allProxies; final List subscriptions; late String selectedId; late List groups; ProxyListGroup( {required this.allProxies, required this.subscriptions, required this.selectedId}) : groups = convertProxyListToGroup(allProxies, subscriptions); } class RuleList { final List rules; String selectedId; RuleList(this.rules, this.selectedId); RuleList.fromJson(Map json) : rules = json['rules'] != null ? (json['rules'] as List).map((asset) => asset as String).toList() : [], selectedId = (json['selectedId'] as String); Map 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 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 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 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 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 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 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 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 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 _parseAndDecode(String response) { return jsonDecode(response) as Map; } Future> 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 result) async { // Received changes in available connectivity types! if (result.contains(ConnectivityResult.none)) { await Future.delayed(const Duration(seconds: 2)); final List 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 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 ping() async { try { await makeRequestUntilSuccess('$baseHttpUrl/ping'); } catch (e) { throw CoreRunError("fail to ping core: ${e.toString()}"); } } Future stop() async { await dio.post('$baseHttpUrl/manager/stop', options: Options( sendTimeout: const Duration(seconds: 10), receiveTimeout: const Duration(seconds: 10), )); } Future start() async { await dio.post('$baseHttpUrl/manager/start', options: Options( sendTimeout: const Duration(seconds: 10), receiveTimeout: const Duration(seconds: 10), )); } Future 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 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 getProxyList() async { final proxiesRes = await dio.get('$baseHttpUrl/proxies'); return ProxyList.fromJson(proxiesRes.data); } Future getRuleList() async { final rulesRes = await dio.get('$baseHttpUrl/rules'); return RuleList.fromJson(rulesRes.data); } Future selectProxy(String id) async { await dio.post('$baseHttpUrl/selected/proxy', data: {'id': id}); } Future selectRule(String id) async { await dio.post('$baseHttpUrl/selected/rule', data: {'id': id}); } Future 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 safeExit() async { try { await dio.post('$baseHttpUrl/manager/exit'); coreProcess?.exit(); } catch (e) { debugPrint(e.toString()); } } Future restart() async { coreProcess?.exit(); await coreProcess?.run(); } Future run() async { await coreProcess?.run(); await ping(); onReady(); } Future getTrafficChannel() async { _trafficChannel ??= WebSocketChannel.connect(Uri.parse('$baseWsUrl/traffic?token=$token')); return _trafficChannel; } Future getRuntimeStatusChannel() async { _runtimeStatusChannel ??= WebSocketChannel.connect( Uri.parse('$baseWsUrl/heartbeat/runtime-status?token=$token')); return _runtimeStatusChannel; } Future getEventChannel() async { _eventChannel ??= WebSocketChannel.connect(Uri.parse('$baseWsUrl/event?token=$token')); return _eventChannel; } Future getSetting() async { final res = await dio.get('$baseHttpUrl/setting'); if (!(res.data.containsKey('setting') && res.data['setting'] is Map)) { throw Exception('invalid setting data'); } return Setting.fromJson(res.data["setting"]); } Future deleteProxies(List ids) async { await dio.delete('$baseHttpUrl/proxies', data: {'ids': ids}); } Future 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 createState() => _DashboardState(); } class _DashboardState extends State 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 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 createState() => _HomeState(); } Future initClient(CoreManager? coreManager) async { await setAutoConnect(coreManager); await setAutoLaunch(coreManager); } class _HomeState extends State with TrayListener, WindowListener, PowerMonitorListener { String baseUrl = ""; String urlStr = ""; String homeDir = ""; CoreManager? coreManager; ValueNotifier isCoreReady = ValueNotifier(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) { 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(context, listen: false)); } Future _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 = 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(context, AppLocalizations); } static const LocalizationsDelegate 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> localizationsDelegates = >[ delegate, GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate, GlobalWidgetsLocalizations.delegate, ]; /// A list of this localizations delegate's supported locales. static const List supportedLocales = [ 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 { const _AppLocalizationsDelegate(); @override Future load(Locale locale) { return SynchronousFuture(lookupAppLocalizations(locale)); } @override bool isSupported(Locale locale) => ['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 args) async { WidgetsFlutterBinding.ensureInitialized(); await notifier.ensureInitialized(); PlatformDispatcher.instance.onError = (error, stack) { if (error is DioException) { if (error.response?.data is Map) { 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 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 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 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 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 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 args; final bool needElevate; ProcessManager(this.path, this.args, this.needElevate); Future run() async { if (Platform.isWindows) { await verifyCoreBinary(path); List 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 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> readJsonFile(String filePath) async { var input = await File(filePath).readAsString(); var map = jsonDecode(input); if (map is Map) { return map; } return {}; } void exitApp() async { exit(0); } Future 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 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 getLocale() async { var curLanguage = await readLanguage(); return convertLocale(curLanguage); } typedef InitI10nLabel = ({ String macOSElevateServiceInfo, String macOSNotElevatedMsg }); Future 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 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 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 createState() => _AppBodyState(); } class _AppBodyState extends State with WindowListener { ProxyListGroup proxyListGroup = ProxyListGroup( allProxies: [], selectedId: "", subscriptions: []); List subscriptionList = []; bool isLoadingProxyList = false; bool isLoadingProxyRadio = false; var isCollapsedMap = {}; Future 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(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 refreshData() async { if (!isLoadingProxyRadio) { refreshProxyList(); } } Future handleSelectProxy(String? id) async { if (id == null) { return; } try { setState(() { isLoadingProxyRadio = true; }); await widget.coreManager.selectProxy(id); setState(() { proxyListGroup.selectedId = id; Provider.of(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( 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 createState() => _AppBottomBarState(); } class _AppBottomBarState extends State with WindowListener { ProxyMode proxyMode = ProxyMode.tun; TrafficState? trafficData; WebSocketChannel? trafficChannel; bool isWindowHidden = false; Future 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 createState() => _State(); } class _State extends State with WindowListener { bool isStarted = false; RuleList ruleList = RuleList([], ""); bool isLoadingSwitch = false; bool isLoadingRuleList = false; bool isLoadingRuleDropdown = false; WebSocketChannel? runtimeStatusChannel; void openWebDashboard() { launchUrl(Uri.parse(widget.urlStr)); } Future refreshData() async { if (!isLoadingSwitch) { refreshIsStarted(); } refreshCurProxyInfo(); if (!isLoadingRuleDropdown) { refreshRuleList(); } } Future refreshIsStarted() async { final value = await widget.coreManager.getIsStarted(); setState(() { isStarted = value; }); } Future refreshCurProxyInfo() async { final value = await widget.coreManager.getCurProxyInfo(); setState(() { widget.onCurProxyInfoChange(value); }); } Future 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 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(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> menuEntries = UnmodifiableListView>( ruleList.rules.map>((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( 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 createState() => _CoreRunErrorHandlerState(); } class _CoreRunErrorHandlerState extends State { 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 createState() => _AppProgressIndicatorState(); } class _AppProgressIndicatorState extends State 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 createState() => _ProxyItemActionMenuState(); } class _ProxyItemActionMenuState extends State { FocusNode buttonFocusNode = FocusNode(debugLabel: 'Menu Button'); @override void dispose() { super.dispose(); buttonFocusNode.dispose(); } @override Widget build(BuildContext context) { return Consumer(builder: (context, appState, child) { final isDeleteDisabled = appState.isStarted && appState.selectedProxyId == widget.id; final actionItems = [ 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 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 createState() => _ProxyListCardState(); } class _ProxyListCardState extends State { 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( (Set states) { return Colors.transparent; }, ), overlayColor: WidgetStateProperty.resolveWith( (Set 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 createState() => _ProxyListItemState(); } class _ProxyListItemState extends State { 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( 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 ================================================ ================================================ 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 ================================================ com.apple.security.app-sandbox com.apple.security.cs.allow-jit com.apple.security.network.server ================================================ FILE: macos/Runner/Info.plist ================================================ CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIconFile CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType APPL CFBundleShortVersionString $(FLUTTER_BUILD_NAME) CFBundleVersion $(FLUTTER_BUILD_NUMBER) LSMinimumSystemVersion $(MACOSX_DEPLOYMENT_TARGET) NSHumanReadableCopyright $(PRODUCT_COPYRIGHT) NSMainNibFile MainMenu NSPrincipalClass NSApplication ================================================ 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 ================================================ com.apple.security.app-sandbox ================================================ 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 = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; 3BF077F1B774008AFACDB990 /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 69F1635BCA26D70464CB9EBB /* Pods_Runner.framework */; }; 58D3022204686DE8EF2AEB82 /* Pods_RunnerTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 726D8EF5DAB8D40467DE7A56 /* Pods_RunnerTests.framework */; }; 8C2B2B4C2D805CA500DCA9F0 /* LaunchAtLogin in Frameworks */ = {isa = PBXBuildFile; productRef = 8C2B2B4B2D805CA500DCA9F0 /* LaunchAtLogin */; }; 8CF04FA52D7DA43300447BC9 /* LaunchAtLogin in Frameworks */ = {isa = PBXBuildFile; productRef = 8CF04FA42D7DA43300447BC9 /* LaunchAtLogin */; }; 8CF04FA72D7DA82E00447BC9 /* LaunchAtLogin in Frameworks */ = {isa = PBXBuildFile; productRef = 8CF04FA62D7DA82E00447BC9 /* LaunchAtLogin */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 33CC10E52044A3C60003C045 /* Project object */; proxyType = 1; remoteGlobalIDString = 33CC10EC2044A3C60003C045; remoteInfo = Runner; }; 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 33CC10E52044A3C60003C045 /* Project object */; proxyType = 1; remoteGlobalIDString = 33CC111A2044C6BA0003C045; remoteInfo = FLX; }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ 33CC110E2044A8840003C045 /* Bundle Framework */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = ""; dstSubfolderSpec = 10; files = ( ); name = "Bundle Framework"; runOnlyForDeploymentPostprocessing = 0; }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ 22AE9E0B8C04BA5A1611F3E7 /* Pods-RunnerTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.debug.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.debug.xcconfig"; sourceTree = ""; }; 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; 33CC10ED2044A3C60003C045 /* Lux.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Lux.app; sourceTree = BUILT_PRODUCTS_DIR; }; 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; 69F1635BCA26D70464CB9EBB /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 726D8EF5DAB8D40467DE7A56 /* Pods_RunnerTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_RunnerTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; 926F498169295E992EF57EFE /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; 9D50E06012B9B906DA2B1C37 /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; DF961A4D9286464E14272F7C /* Pods-RunnerTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.release.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.release.xcconfig"; sourceTree = ""; }; E0949EAC71C55E4ADDB10FAE /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; FD1ED7C4BCE08FBAFA3A828C /* Pods-RunnerTests.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-RunnerTests.profile.xcconfig"; path = "Target Support Files/Pods-RunnerTests/Pods-RunnerTests.profile.xcconfig"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 331C80D2294CF70F00263BE5 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 58D3022204686DE8EF2AEB82 /* Pods_RunnerTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; 33CC10EA2044A3C60003C045 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 8CF04FA72D7DA82E00447BC9 /* LaunchAtLogin in Frameworks */, 8CF04FA52D7DA43300447BC9 /* LaunchAtLogin in Frameworks */, 8C2B2B4C2D805CA500DCA9F0 /* LaunchAtLogin in Frameworks */, 3BF077F1B774008AFACDB990 /* Pods_Runner.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 331C80D6294CF71000263BE5 /* RunnerTests */ = { isa = PBXGroup; children = ( 331C80D7294CF71000263BE5 /* RunnerTests.swift */, ); path = RunnerTests; sourceTree = ""; }; 33BA886A226E78AF003329D5 /* Configs */ = { isa = PBXGroup; children = ( 33E5194F232828860026EE4D /* AppInfo.xcconfig */, 9740EEB21CF90195004384FC /* Debug.xcconfig */, 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, ); path = Configs; sourceTree = ""; }; 33CC10E42044A3C60003C045 = { isa = PBXGroup; children = ( 33FAB671232836740065AC1E /* Runner */, 33CEB47122A05771004F2AC0 /* Flutter */, 331C80D6294CF71000263BE5 /* RunnerTests */, 33CC10EE2044A3C60003C045 /* Products */, D73912EC22F37F3D000D13A0 /* Frameworks */, F562A9F194E753677402540D /* Pods */, ); sourceTree = ""; }; 33CC10EE2044A3C60003C045 /* Products */ = { isa = PBXGroup; children = ( 33CC10ED2044A3C60003C045 /* Lux.app */, 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, ); name = Products; sourceTree = ""; }; 33CC11242044D66E0003C045 /* Resources */ = { isa = PBXGroup; children = ( 33CC10F22044A3C60003C045 /* Assets.xcassets */, 33CC10F42044A3C60003C045 /* MainMenu.xib */, 33CC10F72044A3C60003C045 /* Info.plist */, ); name = Resources; path = ..; sourceTree = ""; }; 33CEB47122A05771004F2AC0 /* Flutter */ = { isa = PBXGroup; children = ( 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, ); path = Flutter; sourceTree = ""; }; 33FAB671232836740065AC1E /* Runner */ = { isa = PBXGroup; children = ( 33CC10F02044A3C60003C045 /* AppDelegate.swift */, 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, 33E51913231747F40026EE4D /* DebugProfile.entitlements */, 33E51914231749380026EE4D /* Release.entitlements */, 33CC11242044D66E0003C045 /* Resources */, 33BA886A226E78AF003329D5 /* Configs */, ); path = Runner; sourceTree = ""; }; D73912EC22F37F3D000D13A0 /* Frameworks */ = { isa = PBXGroup; children = ( 69F1635BCA26D70464CB9EBB /* Pods_Runner.framework */, 726D8EF5DAB8D40467DE7A56 /* Pods_RunnerTests.framework */, ); name = Frameworks; sourceTree = ""; }; F562A9F194E753677402540D /* Pods */ = { isa = PBXGroup; children = ( 9D50E06012B9B906DA2B1C37 /* Pods-Runner.debug.xcconfig */, 926F498169295E992EF57EFE /* Pods-Runner.release.xcconfig */, E0949EAC71C55E4ADDB10FAE /* Pods-Runner.profile.xcconfig */, 22AE9E0B8C04BA5A1611F3E7 /* Pods-RunnerTests.debug.xcconfig */, DF961A4D9286464E14272F7C /* Pods-RunnerTests.release.xcconfig */, FD1ED7C4BCE08FBAFA3A828C /* Pods-RunnerTests.profile.xcconfig */, ); path = Pods; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 331C80D4294CF70F00263BE5 /* RunnerTests */ = { isa = PBXNativeTarget; buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; buildPhases = ( E433C8B9A4D6A552D04CD3AC /* [CP] Check Pods Manifest.lock */, 331C80D1294CF70F00263BE5 /* Sources */, 331C80D2294CF70F00263BE5 /* Frameworks */, 331C80D3294CF70F00263BE5 /* Resources */, ); buildRules = ( ); dependencies = ( 331C80DA294CF71000263BE5 /* PBXTargetDependency */, ); name = RunnerTests; productName = RunnerTests; productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; productType = "com.apple.product-type.bundle.unit-test"; }; 33CC10EC2044A3C60003C045 /* Runner */ = { isa = PBXNativeTarget; buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; buildPhases = ( 86901BD31A06D52A8F559DFA /* [CP] Check Pods Manifest.lock */, 33CC10E92044A3C60003C045 /* Sources */, 33CC10EA2044A3C60003C045 /* Frameworks */, 33CC10EB2044A3C60003C045 /* Resources */, 33CC110E2044A8840003C045 /* Bundle Framework */, 3399D490228B24CF009A79C7 /* ShellScript */, B6A6D6F8B3933A21B9BB6822 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); dependencies = ( 33CC11202044C79F0003C045 /* PBXTargetDependency */, ); name = Runner; packageProductDependencies = ( 8C2B2B4B2D805CA500DCA9F0 /* LaunchAtLogin */, ); productName = Runner; productReference = 33CC10ED2044A3C60003C045 /* Lux.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 33CC10E52044A3C60003C045 /* Project object */ = { isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0920; LastUpgradeCheck = 1510; ORGANIZATIONNAME = ""; TargetAttributes = { 331C80D4294CF70F00263BE5 = { CreatedOnToolsVersion = 14.0; TestTargetID = 33CC10EC2044A3C60003C045; }; 33CC10EC2044A3C60003C045 = { CreatedOnToolsVersion = 9.2; LastSwiftMigration = 1100; ProvisioningStyle = Automatic; SystemCapabilities = { com.apple.Sandbox = { enabled = 1; }; }; }; 33CC111A2044C6BA0003C045 = { CreatedOnToolsVersion = 9.2; ProvisioningStyle = Manual; }; }; }; buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; compatibilityVersion = "Xcode 9.3"; developmentRegion = en; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = 33CC10E42044A3C60003C045; packageReferences = ( 8C2B2B4A2D805CA500DCA9F0 /* XCRemoteSwiftPackageReference "LaunchAtLogin-Modern" */, ); productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 33CC10EC2044A3C60003C045 /* Runner */, 331C80D4294CF70F00263BE5 /* RunnerTests */, 33CC111A2044C6BA0003C045 /* Flutter Assemble */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 331C80D3294CF70F00263BE5 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; 33CC10EB2044A3C60003C045 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ 3399D490228B24CF009A79C7 /* ShellScript */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( ); inputPaths = ( ); outputFileListPaths = ( ); outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; }; 33CC111E2044C6BF0003C045 /* ShellScript */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( Flutter/ephemeral/FlutterInputs.xcfilelist, ); inputPaths = ( Flutter/ephemeral/tripwire, ); outputFileListPaths = ( Flutter/ephemeral/FlutterOutputs.xcfilelist, ); outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; }; 86901BD31A06D52A8F559DFA /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( ); inputPaths = ( "${PODS_PODFILE_DIR_PATH}/Podfile.lock", "${PODS_ROOT}/Manifest.lock", ); name = "[CP] Check Pods Manifest.lock"; outputFileListPaths = ( ); outputPaths = ( "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; B6A6D6F8B3933A21B9BB6822 /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", ); inputPaths = ( ); name = "[CP] Embed Pods Frameworks"; outputFileListPaths = ( "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", ); outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; E433C8B9A4D6A552D04CD3AC /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputFileListPaths = ( ); inputPaths = ( "${PODS_PODFILE_DIR_PATH}/Podfile.lock", "${PODS_ROOT}/Manifest.lock", ); name = "[CP] Check Pods Manifest.lock"; outputFileListPaths = ( ); outputPaths = ( "$(DERIVED_FILE_DIR)/Pods-RunnerTests-checkManifestLockResult.txt", ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; showEnvVarsInLog = 0; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 331C80D1294CF70F00263BE5 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 33CC10E92044A3C60003C045 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 33CC10EC2044A3C60003C045 /* Runner */; targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; }; 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ /* Begin PBXVariantGroup section */ 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { isa = PBXVariantGroup; children = ( 33CC10F52044A3C60003C045 /* Base */, ); name = MainMenu.xib; path = Runner; sourceTree = ""; }; /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ 331C80DB294CF71000263BE5 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 22AE9E0B8C04BA5A1611F3E7 /* Pods-RunnerTests.debug.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = com.github.igoogolx.lux.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/lux.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/lux"; }; name = Debug; }; 331C80DC294CF71000263BE5 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = DF961A4D9286464E14272F7C /* Pods-RunnerTests.release.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = com.github.igoogolx.lux.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/lux.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/lux"; }; name = Release; }; 331C80DD294CF71000263BE5 /* Profile */ = { isa = XCBuildConfiguration; baseConfigurationReference = FD1ED7C4BCE08FBAFA3A828C /* Pods-RunnerTests.profile.xcconfig */; buildSettings = { BUNDLE_LOADER = "$(TEST_HOST)"; CURRENT_PROJECT_VERSION = 1; GENERATE_INFOPLIST_FILE = YES; MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = com.github.igoogolx.lux.RunnerTests; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/lux.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/lux"; }; name = Profile; }; 338D0CE9231458BD00FA5F75 /* Profile */ = { isa = XCBuildConfiguration; baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CODE_SIGN_IDENTITY = "-"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MACOSX_DEPLOYMENT_TARGET = 13.5; MTL_ENABLE_DEBUG_INFO = NO; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-O"; }; name = Profile; }; 338D0CEA231458BD00FA5F75 /* Profile */ = { isa = XCBuildConfiguration; baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/../Frameworks", ); PROVISIONING_PROFILE_SPECIFIER = ""; SWIFT_VERSION = 5.0; }; name = Profile; }; 338D0CEB231458BD00FA5F75 /* Profile */ = { isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_STYLE = Manual; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Profile; }; 33CC10F92044A3C60003C045 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CODE_SIGN_IDENTITY = "-"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MACOSX_DEPLOYMENT_TARGET = 13.5; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; }; name = Debug; }; 33CC10FA2044A3C60003C045 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CODE_SIGN_IDENTITY = "-"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; EXCLUDED_ARCHS = x86_64; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MACOSX_DEPLOYMENT_TARGET = 13.5; MTL_ENABLE_DEBUG_INFO = NO; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-O"; }; name = Release; }; 33CC10FC2044A3C60003C045 /* Debug */ = { isa = XCBuildConfiguration; baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/../Frameworks", ); PROVISIONING_PROFILE_SPECIFIER = ""; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 5.0; }; name = Debug; }; 33CC10FD2044A3C60003C045 /* Release */ = { isa = XCBuildConfiguration; baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; INFOPLIST_FILE = Runner/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/../Frameworks", ); PROVISIONING_PROFILE_SPECIFIER = ""; SWIFT_VERSION = 5.0; }; name = Release; }; 33CC111C2044C6BA0003C045 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_STYLE = Manual; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Debug; }; 33CC111D2044C6BA0003C045 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_STYLE = Automatic; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { isa = XCConfigurationList; buildConfigurations = ( 331C80DB294CF71000263BE5 /* Debug */, 331C80DC294CF71000263BE5 /* Release */, 331C80DD294CF71000263BE5 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { isa = XCConfigurationList; buildConfigurations = ( 33CC10F92044A3C60003C045 /* Debug */, 33CC10FA2044A3C60003C045 /* Release */, 338D0CE9231458BD00FA5F75 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { isa = XCConfigurationList; buildConfigurations = ( 33CC10FC2044A3C60003C045 /* Debug */, 33CC10FD2044A3C60003C045 /* Release */, 338D0CEA231458BD00FA5F75 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { isa = XCConfigurationList; buildConfigurations = ( 33CC111C2044C6BA0003C045 /* Debug */, 33CC111D2044C6BA0003C045 /* Release */, 338D0CEB231458BD00FA5F75 /* Profile */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ /* Begin XCRemoteSwiftPackageReference section */ 8C2B2B4A2D805CA500DCA9F0 /* XCRemoteSwiftPackageReference "LaunchAtLogin-Modern" */ = { isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/sindresorhus/LaunchAtLogin-Modern"; requirement = { branch = main; kind = branch; }; }; 8CF04FA32D7DA43300447BC9 /* XCRemoteSwiftPackageReference "LaunchAtLogin-Modern" */ = { isa = XCRemoteSwiftPackageReference; repositoryURL = "https://github.com/sindresorhus/LaunchAtLogin-Modern"; requirement = { branch = main; kind = branch; }; }; /* End XCRemoteSwiftPackageReference section */ /* Begin XCSwiftPackageProductDependency section */ 8C2B2B4B2D805CA500DCA9F0 /* LaunchAtLogin */ = { isa = XCSwiftPackageProductDependency; package = 8C2B2B4A2D805CA500DCA9F0 /* XCRemoteSwiftPackageReference "LaunchAtLogin-Modern" */; productName = LaunchAtLogin; }; 8CF04FA42D7DA43300447BC9 /* LaunchAtLogin */ = { isa = XCSwiftPackageProductDependency; package = 8CF04FA32D7DA43300447BC9 /* XCRemoteSwiftPackageReference "LaunchAtLogin-Modern" */; productName = LaunchAtLogin; }; 8CF04FA62D7DA82E00447BC9 /* LaunchAtLogin */ = { isa = XCSwiftPackageProductDependency; package = 8CF04FA32D7DA43300447BC9 /* XCRemoteSwiftPackageReference "LaunchAtLogin-Modern" */; productName = LaunchAtLogin; }; /* End XCSwiftPackageProductDependency section */ }; rootObject = 33CC10E52044A3C60003C045 /* Project object */; } ================================================ FILE: macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist ================================================ IDEDidComputeMac32BitWarning ================================================ FILE: macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme ================================================ ================================================ FILE: macos/Runner.xcworkspace/contents.xcworkspacedata ================================================ ================================================ FILE: macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist ================================================ IDEDidComputeMac32BitWarning ================================================ FILE: macos/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved ================================================ { "pins" : [ { "identity" : "launchatlogin-modern", "kind" : "remoteSourceControl", "location" : "https://github.com/sindresorhus/LaunchAtLogin-Modern", "state" : { "branch" : "main", "revision" : "a04ec1c363be3627734f6dad757d82f5d4fa8fcc" } } ], "version" : 2 } ================================================ FILE: macos/RunnerTests/RunnerTests.swift ================================================ import FlutterMacOS import Cocoa import XCTest class RunnerTests: XCTestCase { func testExample() { // If you add code to the Runner application, consider adding tests here. // See https://developer.apple.com/documentation/xctest for more information about using XCTest. } } ================================================ FILE: macos/packaging/dmg/make_config.yaml ================================================ title: Lux contents: - x: 448 y: 344 type: link path: "/Applications" - x: 192 y: 344 type: file path: Lux.app ================================================ FILE: pubspec.yaml ================================================ name: lux description: A light desktop proxy app. # The following line prevents the package from being accidentally published to # pub.dev using `flutter pub publish`. This is preferred for private packages. publish_to: 'none' # Remove this line if you wish to publish to pub.dev # The following defines the version and build number for your application. # A version number is three numbers separated by dots, like 1.2.43 # followed by an optional build number separated by a +. # Both the version and the builder number may be overridden in flutter # build by specifying --build-name and --build-number, respectively. # In Android, build-name is used as versionName while build-number used as versionCode. # Read more about Android versioning at https://developer.android.com/studio/publish/versioning # In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. # Read more about iOS versioning at # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. version: 1.40.2 environment: sdk: '>=3.0.6 <4.0.0' # Dependencies specify other packages that your package needs in order to work. # To automatically upgrade your package dependencies to the latest versions # consider running `flutter pub upgrade --major-versions`. Alternatively, # dependencies can be manually updated by changing the version numbers below to # the latest version available on pub.dev. To see which dependencies have newer # versions available, run `flutter pub outdated`. dependencies: flutter: sdk: flutter # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.2 url_launcher: ^6.1.12 path: ^1.8.3 dio: ^5.3.0 path_provider: ^2.0.15 window_manager: ^0.5.0 package_info_plus: ^9.0.0 args: ^2.4.2 power_monitor: git: url: https://github.com/igoogolx/power_monitor.git ref: v0.0.3 version: ^3.0.2 uuid: ^4.5.1 connectivity_plus: ^7.0.0 launch_at_startup: ^0.5.1 tray_manager: ^0.5.0 flutter_local_notifications: ^21.0.0 flutter_localizations: sdk: flutter intl: any provider: ^6.1.4 crypto: ^3.0.6 flex_color_scheme: ^8.2.0 web_socket_channel: ^3.0.3 yaml: ^3.1.3 win32_registry: ^2.1.0 dev_dependencies: flutter_test: sdk: flutter # The "flutter_lints" package below contains a set of recommended lints to # encourage good coding practices. The lint set provided by the package is # activated in the `analysis_options.yaml` file located at the root of your # package. See that file for information about deactivating specific lint # rules and activating additional ones. flutter_lints: ^6.0.0 flutter_launcher_icons: ^0.14.2 archive: ^4.0.2 # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec # The following section is specific to Flutter packages. flutter: generate: true # The following line ensures that the Material Icons font is # included with your application, so that you can use the icons in # the material Icons class. uses-material-design: true # To add assets to your application, add an assets section, like this: # assets: # - images/a_dot_burr.jpeg # - images/a_dot_ham.jpeg assets: - assets/app_icon.ico - assets/tray.png - assets/tray.icns - assets/bin/ - pubspec.yaml # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.dev/assets-and-images/#resolution-aware # For details regarding adding assets from package dependencies, see # https://flutter.dev/assets-and-images/#from-packages # To add custom fonts to your application, add a fonts section here, # in this "flutter" section. Each entry in this list should have a # "family" key with the font family name, and a "fonts" key with a # list giving the asset and other descriptors for the font. For # example: # fonts: # - family: Schyler # fonts: # - asset: fonts/Schyler-Regular.ttf # - asset: fonts/Schyler-Italic.ttf # style: italic # - family: Trajan Pro # fonts: # - asset: fonts/TrajanPro.ttf # - asset: fonts/TrajanPro_Bold.ttf # weight: 700 # # For details regarding fonts from package dependencies, # see https://flutter.dev/custom-fonts/#from-packages flutter_launcher_icons: image_path: "assets/logo.png" windows: generate: true icon_size: 48 macos: generate: true ================================================ FILE: scripts/constant.dart ================================================ const rawCoreVersion = '1.33.1'; ================================================ FILE: scripts/init.dart ================================================ // ignore_for_file: avoid_print import 'dart:io'; import 'package:args/args.dart'; import 'package:dio/dio.dart'; import 'package:lux/const/const.dart'; import 'package:lux/core/checksum.dart'; import 'package:path/path.dart' as path; import 'constant.dart'; // https://github.com/dart-lang/sdk/issues/31610 final assetsPath = path.normalize(path.join(Platform.script.toFilePath(), '../../assets')); final binDir = Directory(path.join(assetsPath, 'bin')); const rawCoreName = 'itun2socks'; Future downloadFileWith(String url, String savePath) async { final dio = Dio(); try { await dio.download( url, savePath, ); print('✅ File downloaded to: $savePath'); } catch (e) { print('❌ Download failed: $e'); } } void downloadInnoSetupChineseItransFile() async { final url = 'https://raw.githubusercontent.com/jrsoftware/issrc/main/Files/Languages/Unofficial/ChineseSimplified.isl'; final folderPath = path.normalize(path.join( Platform.script.toFilePath(), '..', "..", "windows", "packaging", "exe")); final fileName = 'ChineseSimplified.isl'; final savePath = '$folderPath/$fileName'; await downloadFileWith(url, savePath); } Future downloadLatestCore(String arch, String token) async { final dio = Dio(); dio.options.headers = {HttpHeaders.authorizationHeader: 'Bear $token'}; var releaseArch = LuxCoreName.arch; if (arch.isNotEmpty) { releaseArch = arch; } final String luxCoreName = '${rawCoreName}_${rawCoreVersion}_${LuxCoreName.platform}_$releaseArch'; print(luxCoreName); final info = await dio.get( 'https://api.github.com/repos/igoogolx/itun2socks/releases/tags/v$rawCoreVersion'); final Map latest = (info.data['assets'] as List) .firstWhere((it) => (it['name'] as String).contains(luxCoreName)); final String name = latest['name']; final tempFile = File(path.join(binDir.path, LuxCoreName.name)); print('Downloading $name'); await dio.download(latest['browser_download_url'], tempFile.path); print('Download $name Success'); await verifyCoreBinary(tempFile.path); if (Platform.isMacOS) { await Process.run('chmod', ['+x', tempFile.path]); } } const targetArch = 'target-arch'; const secret = 'secret'; void main(List arguments) async { try { final parser = ArgParser() ..addOption(targetArch, defaultsTo: '', abbr: 'a') ..addOption(secret, defaultsTo: '', abbr: 's'); ArgResults argResults = parser.parse(arguments); if ((await binDir.exists())) { await binDir.delete(recursive: true); } await binDir.create(); if (Platform.isWindows) { downloadInnoSetupChineseItransFile(); } await downloadLatestCore( argResults[targetArch] as String, argResults[secret]); } catch (e) { print(e); exit(1); } } ================================================ FILE: scripts/update_core_sha256.dart ================================================ import 'dart:io'; import 'package:dio/dio.dart'; import 'package:path/path.dart' as p; import 'constant.dart'; class ReleaseAsset { final String digest; final String name; ReleaseAsset(this.digest, this.name); ReleaseAsset.fromJson(Map json) : digest = (json['digest'] as String).replaceFirst("sha256:", ""), name = (json['name'] as String); Map toJson() => { 'digest': digest, 'name': name, }; } class Release { final List assets; Release(this.assets); Release.fromJson(Map json) : assets = json['assets'] != null ? (json['assets'] as List) .map((asset) => ReleaseAsset.fromJson(asset as Map)) .toList() : []; Map toJson() => {'assets': assets.map((asset) => asset.toJson()).toList()}; } Future replaceChecksumSectionInFile( String filePath, String newContent) async { String content = await File(filePath).readAsString(); final regex = RegExp( r'(// checksum-start)([\s\S]*?)(// checksum-end)', multiLine: true, ); String replaced = content.replaceAllMapped(regex, (match) { return '${match[1]}\n$newContent\n${match[3]}'; }); await File(filePath).writeAsString(replaced); } Future getSha256() async { final dio = Dio(); var checksumCode = ""; try { var response = await dio.get( "https://api.github.com/repos/igoogolx/itun2socks/releases/tags/v$rawCoreVersion", ); var release = Release.fromJson(response.data); for (var asset in release.assets) { switch (asset.name) { case "itun2socks_${rawCoreVersion}_darwin_arm64": checksumCode = "$checksumCode const darwinArm64Checksum = \"${asset.digest}\";\n"; case "itun2socks_${rawCoreVersion}_darwin_amd64": checksumCode = "$checksumCode const darwinAmd64Checksum = \"${asset.digest}\";\n"; case "itun2socks_${rawCoreVersion}_windows_amd64.exe": checksumCode = "$checksumCode const windowsAmd64Checksum = \"${asset.digest}\";"; } } return checksumCode; } catch (e) { return ""; } } Future main() async { final newCode = await getSha256(); await replaceChecksumSectionInFile( p.join("lib", "core", "checksum.dart"), newCode); print(newCode); exit(1); } ================================================ FILE: test/widget_test.dart ================================================ ================================================ FILE: windows/.gitignore ================================================ flutter/ephemeral/ # Visual Studio user-specific files. *.suo *.user *.userosscache *.sln.docstates # Visual Studio build-related files. x64/ x86/ # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !*.[Cc]ache/ ================================================ FILE: windows/CMakeLists.txt ================================================ # Project-level configuration. cmake_minimum_required(VERSION 3.14) project(lux LANGUAGES CXX) # The name of the executable created for the application. Change this to change # the on-disk name of your application. set(BINARY_NAME "lux") # Explicitly opt in to modern CMake behaviors to avoid warnings with recent # versions of CMake. cmake_policy(SET CMP0063 NEW) # Define build configuration option. get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) if(IS_MULTICONFIG) set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" CACHE STRING "" FORCE) else() if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Flutter build mode" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Profile" "Release") endif() endif() # Define settings for the Profile build mode. set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") # Use Unicode for all projects. add_definitions(-DUNICODE -D_UNICODE) # Compilation settings that should be applied to most targets. # # Be cautious about adding new options here, as plugins use this function by # default. In most cases, you should add new options to specific targets instead # of modifying this function. function(APPLY_STANDARD_SETTINGS TARGET) target_compile_features(${TARGET} PUBLIC cxx_std_17) target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") target_compile_options(${TARGET} PRIVATE /EHsc) target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") endfunction() # Flutter library and tool build rules. set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") add_subdirectory(${FLUTTER_MANAGED_DIR}) # Application build; see runner/CMakeLists.txt. add_subdirectory("runner") # Generated plugin build rules, which manage building the plugins and adding # them to the application. include(flutter/generated_plugins.cmake) # === Installation === # Support files are copied into place next to the executable, so that it can # run in place. This is done instead of making a separate bundle (as on Linux) # so that building and running from within Visual Studio will work. set(BUILD_BUNDLE_DIR "$") # Make the "install" step default, as it's required to run. set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() # Fully re-copy the assets directory on each build to avoid having stale files # from a previous install. set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) # Install the AOT library on non-Debug builds only. install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ================================================ FILE: windows/flutter/CMakeLists.txt ================================================ # This file controls Flutter-level build steps. It should not be edited. cmake_minimum_required(VERSION 3.14) set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") # Configuration provided via flutter tool. include(${EPHEMERAL_DIR}/generated_config.cmake) # TODO: Move the rest of this into files in ephemeral. See # https://github.com/flutter/flutter/issues/57146. set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") # Set fallback configurations for older versions of the flutter tool. if (NOT DEFINED FLUTTER_TARGET_PLATFORM) set(FLUTTER_TARGET_PLATFORM "windows-x64") endif() # === Flutter Library === set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) list(APPEND FLUTTER_LIBRARY_HEADERS "flutter_export.h" "flutter_windows.h" "flutter_messenger.h" "flutter_plugin_registrar.h" "flutter_texture_registrar.h" ) list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}" ) target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") add_dependencies(flutter flutter_assemble) # === Wrapper === list(APPEND CPP_WRAPPER_SOURCES_CORE "core_implementations.cc" "standard_codec.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") list(APPEND CPP_WRAPPER_SOURCES_PLUGIN "plugin_registrar.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") list(APPEND CPP_WRAPPER_SOURCES_APP "flutter_engine.cc" "flutter_view_controller.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") # Wrapper sources needed for a plugin. add_library(flutter_wrapper_plugin STATIC ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ) apply_standard_settings(flutter_wrapper_plugin) set_target_properties(flutter_wrapper_plugin PROPERTIES POSITION_INDEPENDENT_CODE ON) set_target_properties(flutter_wrapper_plugin PROPERTIES CXX_VISIBILITY_PRESET hidden) target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) target_include_directories(flutter_wrapper_plugin PUBLIC "${WRAPPER_ROOT}/include" ) add_dependencies(flutter_wrapper_plugin flutter_assemble) # Wrapper sources needed for the runner. add_library(flutter_wrapper_app STATIC ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_APP} ) apply_standard_settings(flutter_wrapper_app) target_link_libraries(flutter_wrapper_app PUBLIC flutter) target_include_directories(flutter_wrapper_app PUBLIC "${WRAPPER_ROOT}/include" ) add_dependencies(flutter_wrapper_app flutter_assemble) # === Flutter tool backend === # _phony_ is a non-existent file to force this command to run every time, # since currently there's no way to get a full input/output list from the # flutter tool. set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ${PHONY_OUTPUT} COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" ${FLUTTER_TARGET_PLATFORM} $ VERBATIM ) add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ) ================================================ FILE: windows/flutter/generated_plugin_registrant.cc ================================================ // // Generated file. Do not edit. // // clang-format off #include "generated_plugin_registrant.h" #include #include #include #include #include #include void RegisterPlugins(flutter::PluginRegistry* registry) { ConnectivityPlusWindowsPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("ConnectivityPlusWindowsPlugin")); PowerMonitorPluginCApiRegisterWithRegistrar( registry->GetRegistrarForPlugin("PowerMonitorPluginCApi")); ScreenRetrieverWindowsPluginCApiRegisterWithRegistrar( registry->GetRegistrarForPlugin("ScreenRetrieverWindowsPluginCApi")); TrayManagerPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("TrayManagerPlugin")); UrlLauncherWindowsRegisterWithRegistrar( registry->GetRegistrarForPlugin("UrlLauncherWindows")); WindowManagerPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("WindowManagerPlugin")); } ================================================ FILE: windows/flutter/generated_plugin_registrant.h ================================================ // // Generated file. Do not edit. // // clang-format off #ifndef GENERATED_PLUGIN_REGISTRANT_ #define GENERATED_PLUGIN_REGISTRANT_ #include // Registers Flutter plugins. void RegisterPlugins(flutter::PluginRegistry* registry); #endif // GENERATED_PLUGIN_REGISTRANT_ ================================================ FILE: windows/flutter/generated_plugins.cmake ================================================ # # Generated file, do not edit. # list(APPEND FLUTTER_PLUGIN_LIST connectivity_plus power_monitor screen_retriever_windows tray_manager url_launcher_windows window_manager ) list(APPEND FLUTTER_FFI_PLUGIN_LIST flutter_local_notifications_windows ) set(PLUGIN_BUNDLED_LIBRARIES) foreach(plugin ${FLUTTER_PLUGIN_LIST}) add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) list(APPEND PLUGIN_BUNDLED_LIBRARIES $) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) endforeach(plugin) foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) endforeach(ffi_plugin) ================================================ FILE: windows/packaging/exe/make_config.yaml ================================================ # The value of AppId uniquely identifies this application. # Do not use the same AppId value in installers for other applications. # TODO: update app_id: 80DF132E-434A-4DAB-9BC8-48A79C8383B9 publisher: igoogolx publisher_url: https://github.com/leanflutter/flutter_distributor display_name: Lux create_desktop_icon: true install_dir_name: '{autopf}\lux' script_template: setup.iss setup_icon_file: assets\app_icon.ico locales: - en - zh ================================================ FILE: windows/packaging/exe/setup.iss ================================================ [Setup] AppId={{APP_ID}} AppVersion={{APP_VERSION}} AppName={{DISPLAY_NAME}} AppPublisher={{PUBLISHER_NAME}} AppPublisherURL={{PUBLISHER_URL}} AppSupportURL={{PUBLISHER_URL}} AppUpdatesURL={{PUBLISHER_URL}} DefaultDirName={{INSTALL_DIR_NAME}} DisableProgramGroupPage=yes OutputDir=. OutputBaseFilename={{OUTPUT_BASE_FILENAME}} Compression=lzma SolidCompression=yes SetupIconFile={{SETUP_ICON_FILE}} WizardStyle=modern PrivilegesRequired=lowest ArchitecturesAllowed=x64compatible ArchitecturesInstallIn64BitMode=x64compatible DisableFinishedPage=yes AppMutex=lux.app.mutex,Global\lux.app.mutex [Languages] {% for locale in LOCALES %} {% if locale == 'en' %}Name: "english"; MessagesFile: "compiler:Default.isl"{% endif %} {% if locale == 'hy' %}Name: "armenian"; MessagesFile: "compiler:Languages\\Armenian.isl"{% endif %} {% if locale == 'bg' %}Name: "bulgarian"; MessagesFile: "compiler:Languages\\Bulgarian.isl"{% endif %} {% if locale == 'ca' %}Name: "catalan"; MessagesFile: "compiler:Languages\\Catalan.isl"{% endif %} {% if locale == 'zh' %}Name: "chinesesimplified"; MessagesFile: "..\\..\\windows\\packaging\\exe\\ChineseSimplified.isl"{% endif %} {% if locale == 'co' %}Name: "corsican"; MessagesFile: "compiler:Languages\\Corsican.isl"{% endif %} {% if locale == 'cs' %}Name: "czech"; MessagesFile: "compiler:Languages\\Czech.isl"{% endif %} {% if locale == 'da' %}Name: "danish"; MessagesFile: "compiler:Languages\\Danish.isl"{% endif %} {% if locale == 'nl' %}Name: "dutch"; MessagesFile: "compiler:Languages\\Dutch.isl"{% endif %} {% if locale == 'fi' %}Name: "finnish"; MessagesFile: "compiler:Languages\\Finnish.isl"{% endif %} {% if locale == 'fr' %}Name: "french"; MessagesFile: "compiler:Languages\\French.isl"{% endif %} {% if locale == 'de' %}Name: "german"; MessagesFile: "compiler:Languages\\German.isl"{% endif %} {% if locale == 'he' %}Name: "hebrew"; MessagesFile: "compiler:Languages\\Hebrew.isl"{% endif %} {% if locale == 'is' %}Name: "icelandic"; MessagesFile: "compiler:Languages\\Icelandic.isl"{% endif %} {% if locale == 'it' %}Name: "italian"; MessagesFile: "compiler:Languages\\Italian.isl"{% endif %} {% if locale == 'ja' %}Name: "japanese"; MessagesFile: "compiler:Languages\\Japanese.isl"{% endif %} {% if locale == 'no' %}Name: "norwegian"; MessagesFile: "compiler:Languages\\Norwegian.isl"{% endif %} {% if locale == 'pl' %}Name: "polish"; MessagesFile: "compiler:Languages\\Polish.isl"{% endif %} {% if locale == 'pt' %}Name: "portuguese"; MessagesFile: "compiler:Languages\\Portuguese.isl"{% endif %} {% if locale == 'ru' %}Name: "russian"; MessagesFile: "compiler:Languages\\Russian.isl"{% endif %} {% if locale == 'sk' %}Name: "slovak"; MessagesFile: "compiler:Languages\\Slovak.isl"{% endif %} {% if locale == 'sl' %}Name: "slovenian"; MessagesFile: "compiler:Languages\\Slovenian.isl"{% endif %} {% if locale == 'es' %}Name: "spanish"; MessagesFile: "compiler:Languages\\Spanish.isl"{% endif %} {% if locale == 'tr' %}Name: "turkish"; MessagesFile: "compiler:Languages\\Turkish.isl"{% endif %} {% if locale == 'uk' %}Name: "ukrainian"; MessagesFile: "compiler:Languages\\Ukrainian.isl"{% endif %} {% endfor %} [Files] Source: "C:\temp\dll\*"; DestDir: "{app}"; Flags: ignoreversion skipifsourcedoesntexist [Tasks] Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: {% if CREATE_DESKTOP_ICON != true %}unchecked{% else %}checkedonce{% endif %} [Files] Source: "{{SOURCE_DIR}}\\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs ; NOTE: Don't use "Flags: ignoreversion" on any shared system files [Icons] Name: "{autoprograms}\\{{DISPLAY_NAME}}"; Filename: "{app}\\{{EXECUTABLE_NAME}}" Name: "{autodesktop}\\{{DISPLAY_NAME}}"; Filename: "{app}\\{{EXECUTABLE_NAME}}"; Tasks: desktopicon [UninstallDelete] Type: filesandordirs; Name: "{localappdata}\..\Roaming\com.github.igoogolx\lux" ; NOTE: delete any file cautiously ================================================ FILE: windows/runner/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.14) project(runner LANGUAGES CXX) # Define the application target. To change its name, change BINARY_NAME in the # top-level CMakeLists.txt, not the value here, or `flutter run` will no longer # work. # # Any new source files that you add to the application should be added here. add_executable(${BINARY_NAME} WIN32 "flutter_window.cpp" "main.cpp" "utils.cpp" "win32_window.cpp" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" "Runner.rc" "runner.exe.manifest" ) # Apply the standard set of build settings. This can be removed for applications # that need different build settings. apply_standard_settings(${BINARY_NAME}) # Add preprocessor definitions for the build version. target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") # Disable Windows macros that collide with C++ standard library functions. target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") # Add dependency libraries and include directories. Add any application-specific # dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") # Run the Flutter tool portions of the build. This must not be removed. add_dependencies(${BINARY_NAME} flutter_assemble) ================================================ FILE: windows/runner/Runner.rc ================================================ // Microsoft Visual C++ generated resource script. // #pragma code_page(65001) #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // #include "winres.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // English (United States) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE BEGIN "resource.h\0" END 2 TEXTINCLUDE BEGIN "#include ""winres.h""\r\n" "\0" END 3 TEXTINCLUDE BEGIN "\r\n" "\0" END #endif // APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Icon // // Icon with lowest ID value placed first to ensure application icon // remains consistent on all systems. // IDI_APP_ICON ICON "resources\\app_icon.ico" IDI_APP_ICON ICON "../../assets/app_icon.ico" ///////////////////////////////////////////////////////////////////////////// // // Version // #if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) #define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD #else #define VERSION_AS_NUMBER 1,0,0,0 #endif #if defined(FLUTTER_VERSION) #define VERSION_AS_STRING FLUTTER_VERSION #else #define VERSION_AS_STRING "1.0.0" #endif VS_VERSION_INFO VERSIONINFO FILEVERSION VERSION_AS_NUMBER PRODUCTVERSION VERSION_AS_NUMBER FILEFLAGSMASK VS_FFI_FILEFLAGSMASK #ifdef _DEBUG FILEFLAGS VS_FF_DEBUG #else FILEFLAGS 0x0L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_APP FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904e4" BEGIN VALUE "CompanyName", "com.github.igoogolx" "\0" VALUE "FileDescription", "lux" "\0" VALUE "FileVersion", VERSION_AS_STRING "\0" VALUE "InternalName", "lux" "\0" VALUE "LegalCopyright", "Copyright (C) 2023 com.github.igoogolx. All rights reserved." "\0" VALUE "OriginalFilename", "lux.exe" "\0" VALUE "ProductName", "lux" "\0" VALUE "ProductVersion", VERSION_AS_STRING "\0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1252 END END #endif // English (United States) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED ================================================ FILE: windows/runner/flutter_window.cpp ================================================ #include "flutter_window.h" #include #include "flutter/generated_plugin_registrant.h" FlutterWindow::FlutterWindow(const flutter::DartProject& project) : project_(project) {} FlutterWindow::~FlutterWindow() {} bool FlutterWindow::OnCreate() { if (!Win32Window::OnCreate()) { return false; } RECT frame = GetClientArea(); // The size here must match the window dimensions to avoid unnecessary surface // creation / destruction in the startup path. flutter_controller_ = std::make_unique( frame.right - frame.left, frame.bottom - frame.top, project_); // Ensure that basic setup of the controller was successful. if (!flutter_controller_->engine() || !flutter_controller_->view()) { return false; } RegisterPlugins(flutter_controller_->engine()); SetChildContent(flutter_controller_->view()->GetNativeWindow()); flutter_controller_->engine()->SetNextFrameCallback([&]() { //delete this->Show() }); return true; } void FlutterWindow::OnDestroy() { if (flutter_controller_) { flutter_controller_ = nullptr; } Win32Window::OnDestroy(); } LRESULT FlutterWindow::MessageHandler(HWND hwnd, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { // Give Flutter, including plugins, an opportunity to handle window messages. if (flutter_controller_) { std::optional result = flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, lparam); if (result) { return *result; } } switch (message) { case WM_FONTCHANGE: flutter_controller_->engine()->ReloadSystemFonts(); break; } return Win32Window::MessageHandler(hwnd, message, wparam, lparam); } ================================================ FILE: windows/runner/flutter_window.h ================================================ #ifndef RUNNER_FLUTTER_WINDOW_H_ #define RUNNER_FLUTTER_WINDOW_H_ #include #include #include #include "win32_window.h" // A window that does nothing but host a Flutter view. class FlutterWindow : public Win32Window { public: // Creates a new FlutterWindow hosting a Flutter view running |project|. explicit FlutterWindow(const flutter::DartProject& project); virtual ~FlutterWindow(); protected: // Win32Window: bool OnCreate() override; void OnDestroy() override; LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept override; private: // The project to run. flutter::DartProject project_; // The Flutter instance hosted by this window. std::unique_ptr flutter_controller_; }; #endif // RUNNER_FLUTTER_WINDOW_H_ ================================================ FILE: windows/runner/main.cpp ================================================ #include #include #include #include "flutter_window.h" #include "utils.h" int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, _In_ wchar_t *command_line, _In_ int show_command) { HWND hwnd = ::FindWindow(L"FLUTTER_RUNNER_WIN32_WINDOW", L"Lux"); if (hwnd != NULL) { ::ShowWindow(hwnd, SW_NORMAL); ::SetForegroundWindow(hwnd); return EXIT_FAILURE; } // Attach to console when present (e.g., 'flutter run') or create a // new console when running with a debugger. if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { CreateAndAttachConsole(); } // Initialize COM, so that it is available for use in the library and/or // plugins. ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); flutter::DartProject project(L"data"); std::vector command_line_arguments = GetCommandLineArguments(); project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); FlutterWindow window(project); Win32Window::Point origin(10, 10); Win32Window::Size size(1280, 720); if (!window.Create(L"Lux", origin, size)) { return EXIT_FAILURE; } window.SetQuitOnClose(true); ::MSG msg; while (::GetMessage(&msg, nullptr, 0, 0)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } ::CoUninitialize(); return EXIT_SUCCESS; } ================================================ FILE: windows/runner/resource.h ================================================ //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by Runner.rc // #define IDI_APP_ICON 101 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 102 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif ================================================ FILE: windows/runner/runner.exe.manifest ================================================ PerMonitorV2 ================================================ FILE: windows/runner/utils.cpp ================================================ #include "utils.h" #include #include #include #include #include void CreateAndAttachConsole() { if (::AllocConsole()) { FILE *unused; if (freopen_s(&unused, "CONOUT$", "w", stdout)) { _dup2(_fileno(stdout), 1); } if (freopen_s(&unused, "CONOUT$", "w", stderr)) { _dup2(_fileno(stdout), 2); } std::ios::sync_with_stdio(); FlutterDesktopResyncOutputStreams(); } } std::vector GetCommandLineArguments() { // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. int argc; wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); if (argv == nullptr) { return std::vector(); } std::vector command_line_arguments; // Skip the first argument as it's the binary name. for (int i = 1; i < argc; i++) { command_line_arguments.push_back(Utf8FromUtf16(argv[i])); } ::LocalFree(argv); return command_line_arguments; } std::string Utf8FromUtf16(const wchar_t* utf16_string) { if (utf16_string == nullptr) { return std::string(); } int target_length = ::WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, -1, nullptr, 0, nullptr, nullptr) -1; // remove the trailing null character int input_length = (int)wcslen(utf16_string); std::string utf8_string; if (target_length <= 0 || target_length > utf8_string.max_size()) { return utf8_string; } utf8_string.resize(target_length); int converted_length = ::WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, input_length, utf8_string.data(), target_length, nullptr, nullptr); if (converted_length == 0) { return std::string(); } return utf8_string; } ================================================ FILE: windows/runner/utils.h ================================================ #ifndef RUNNER_UTILS_H_ #define RUNNER_UTILS_H_ #include #include // Creates a console for the process, and redirects stdout and stderr to // it for both the runner and the Flutter library. void CreateAndAttachConsole(); // Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string // encoded in UTF-8. Returns an empty std::string on failure. std::string Utf8FromUtf16(const wchar_t* utf16_string); // Gets the command line arguments passed in as a std::vector, // encoded in UTF-8. Returns an empty std::vector on failure. std::vector GetCommandLineArguments(); #endif // RUNNER_UTILS_H_ ================================================ FILE: windows/runner/win32_window.cpp ================================================ #include "win32_window.h" #include #include #include "resource.h" namespace { /// Window attribute that enables dark mode window decorations. /// /// Redefined in case the developer's machine has a Windows SDK older than /// version 10.0.22000.0. /// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute #ifndef DWMWA_USE_IMMERSIVE_DARK_MODE #define DWMWA_USE_IMMERSIVE_DARK_MODE 20 #endif HANDLE hMutexHandle=CreateMutex(NULL, TRUE, L"lux.app.mutex"); constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; /// Registry key for app theme preference. /// /// A value of 0 indicates apps should use dark mode. A non-zero or missing /// value indicates apps should use light mode. constexpr const wchar_t kGetPreferredBrightnessRegKey[] = L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; // The number of Win32Window objects that currently exist. static int g_active_window_count = 0; using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); // Scale helper to convert logical scaler values to physical using passed in // scale factor int Scale(int source, double scale_factor) { return static_cast(source * scale_factor); } // Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. // This API is only needed for PerMonitor V1 awareness mode. void EnableFullDpiSupportIfAvailable(HWND hwnd) { HMODULE user32_module = LoadLibraryA("User32.dll"); if (!user32_module) { return; } auto enable_non_client_dpi_scaling = reinterpret_cast( GetProcAddress(user32_module, "EnableNonClientDpiScaling")); if (enable_non_client_dpi_scaling != nullptr) { enable_non_client_dpi_scaling(hwnd); } FreeLibrary(user32_module); } } // namespace // Manages the Win32Window's window class registration. class WindowClassRegistrar { public: ~WindowClassRegistrar() = default; // Returns the singleton registrar instance. static WindowClassRegistrar* GetInstance() { if (!instance_) { instance_ = new WindowClassRegistrar(); } return instance_; } // Returns the name of the window class, registering the class if it hasn't // previously been registered. const wchar_t* GetWindowClass(); // Unregisters the window class. Should only be called if there are no // instances of the window. void UnregisterWindowClass(); private: WindowClassRegistrar() = default; static WindowClassRegistrar* instance_; bool class_registered_ = false; }; WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; const wchar_t* WindowClassRegistrar::GetWindowClass() { if (!class_registered_) { WNDCLASS window_class{}; window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); window_class.lpszClassName = kWindowClassName; window_class.style = CS_HREDRAW | CS_VREDRAW; window_class.cbClsExtra = 0; window_class.cbWndExtra = 0; window_class.hInstance = GetModuleHandle(nullptr); window_class.hIcon = LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); window_class.hbrBackground = 0; window_class.lpszMenuName = nullptr; window_class.lpfnWndProc = Win32Window::WndProc; RegisterClass(&window_class); class_registered_ = true; } return kWindowClassName; } void WindowClassRegistrar::UnregisterWindowClass() { UnregisterClass(kWindowClassName, nullptr); class_registered_ = false; } Win32Window::Win32Window() { ++g_active_window_count; } Win32Window::~Win32Window() { --g_active_window_count; Destroy(); } bool Win32Window::Create(const std::wstring& title, const Point& origin, const Size& size) { Destroy(); const wchar_t* window_class = WindowClassRegistrar::GetInstance()->GetWindowClass(); const POINT target_point = {static_cast(origin.x), static_cast(origin.y)}; HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); double scale_factor = dpi / 96.0; HWND window = CreateWindow( window_class, title.c_str(), WS_OVERLAPPEDWINDOW, Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), Scale(size.width, scale_factor), Scale(size.height, scale_factor), nullptr, nullptr, GetModuleHandle(nullptr), this); if (!window) { return false; } UpdateTheme(window); return OnCreate(); } bool Win32Window::Show() { return ShowWindow(window_handle_, SW_SHOWNORMAL); } // static LRESULT CALLBACK Win32Window::WndProc(HWND const window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { if (message == WM_NCCREATE) { auto window_struct = reinterpret_cast(lparam); SetWindowLongPtr(window, GWLP_USERDATA, reinterpret_cast(window_struct->lpCreateParams)); auto that = static_cast(window_struct->lpCreateParams); EnableFullDpiSupportIfAvailable(window); that->window_handle_ = window; } else if (Win32Window* that = GetThisFromHandle(window)) { return that->MessageHandler(window, message, wparam, lparam); } return DefWindowProc(window, message, wparam, lparam); } LRESULT Win32Window::MessageHandler(HWND hwnd, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { switch (message) { case WM_DESTROY: window_handle_ = nullptr; Destroy(); if (quit_on_close_) { PostQuitMessage(0); } return 0; case WM_DPICHANGED: { auto newRectSize = reinterpret_cast(lparam); LONG newWidth = newRectSize->right - newRectSize->left; LONG newHeight = newRectSize->bottom - newRectSize->top; SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, newHeight, SWP_NOZORDER | SWP_NOACTIVATE); return 0; } case WM_SIZE: { RECT rect = GetClientArea(); if (child_content_ != nullptr) { // Size and position the child window. MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE); } return 0; } case WM_ACTIVATE: if (child_content_ != nullptr) { SetFocus(child_content_); } return 0; case WM_DWMCOLORIZATIONCOLORCHANGED: UpdateTheme(hwnd); return 0; } return DefWindowProc(window_handle_, message, wparam, lparam); } void Win32Window::Destroy() { OnDestroy(); if (window_handle_) { DestroyWindow(window_handle_); window_handle_ = nullptr; } if (g_active_window_count == 0) { WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); } } Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { return reinterpret_cast( GetWindowLongPtr(window, GWLP_USERDATA)); } void Win32Window::SetChildContent(HWND content) { child_content_ = content; SetParent(content, window_handle_); RECT frame = GetClientArea(); MoveWindow(content, frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, true); SetFocus(child_content_); } RECT Win32Window::GetClientArea() { RECT frame; GetClientRect(window_handle_, &frame); return frame; } HWND Win32Window::GetHandle() { return window_handle_; } void Win32Window::SetQuitOnClose(bool quit_on_close) { quit_on_close_ = quit_on_close; } bool Win32Window::OnCreate() { // No-op; provided for subclasses. return true; } void Win32Window::OnDestroy() { // No-op; provided for subclasses. ReleaseMutex(hMutexHandle); } void Win32Window::UpdateTheme(HWND const window) { DWORD light_mode; DWORD light_mode_size = sizeof(light_mode); LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, kGetPreferredBrightnessRegValue, RRF_RT_REG_DWORD, nullptr, &light_mode, &light_mode_size); if (result == ERROR_SUCCESS) { BOOL enable_dark_mode = light_mode == 0; DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, &enable_dark_mode, sizeof(enable_dark_mode)); } } ================================================ FILE: windows/runner/win32_window.h ================================================ #ifndef RUNNER_WIN32_WINDOW_H_ #define RUNNER_WIN32_WINDOW_H_ #include #include #include #include // A class abstraction for a high DPI-aware Win32 Window. Intended to be // inherited from by classes that wish to specialize with custom // rendering and input handling class Win32Window { public: struct Point { unsigned int x; unsigned int y; Point(unsigned int x, unsigned int y) : x(x), y(y) {} }; struct Size { unsigned int width; unsigned int height; Size(unsigned int width, unsigned int height) : width(width), height(height) {} }; Win32Window(); virtual ~Win32Window(); // Creates a win32 window with |title| that is positioned and sized using // |origin| and |size|. New windows are created on the default monitor. Window // sizes are specified to the OS in physical pixels, hence to ensure a // consistent size this function will scale the inputted width and height as // as appropriate for the default monitor. The window is invisible until // |Show| is called. Returns true if the window was created successfully. bool Create(const std::wstring& title, const Point& origin, const Size& size); // Show the current window. Returns true if the window was successfully shown. bool Show(); // Release OS resources associated with window. void Destroy(); // Inserts |content| into the window tree. void SetChildContent(HWND content); // Returns the backing Window handle to enable clients to set icon and other // window properties. Returns nullptr if the window has been destroyed. HWND GetHandle(); // If true, closing this window will quit the application. void SetQuitOnClose(bool quit_on_close); // Return a RECT representing the bounds of the current client area. RECT GetClientArea(); protected: // Processes and route salient window messages for mouse handling, // size change and DPI. Delegates handling of these to member overloads that // inheriting classes can handle. virtual LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept; // Called when CreateAndShow is called, allowing subclass window-related // setup. Subclasses should return false if setup fails. virtual bool OnCreate(); // Called when Destroy is called. virtual void OnDestroy(); private: friend class WindowClassRegistrar; // OS callback called by message pump. Handles the WM_NCCREATE message which // is passed when the non-client area is being created and enables automatic // non-client DPI scaling so that the non-client area automatically // responds to changes in DPI. All other messages are handled by // MessageHandler. static LRESULT CALLBACK WndProc(HWND const window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept; // Retrieves a class instance pointer for |window| static Win32Window* GetThisFromHandle(HWND const window) noexcept; // Update the window frame's theme to match the system theme. static void UpdateTheme(HWND const window); bool quit_on_close_ = false; // window handle for top level window. HWND window_handle_ = nullptr; // window handle for hosted content. HWND child_content_ = nullptr; }; #endif // RUNNER_WIN32_WINDOW_H_