commit 463e69bc4b7a724ed5bcb6d2430f2e5ea257a3da Author: LZX <1820455493@qq.com> Date: Mon Oct 19 22:16:26 2026 +0800 feat: Initial commit of OpenLoc diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..70a4214 --- /dev/null +++ b/.gitignore @@ -0,0 +1,68 @@ +# Built application files +*.apk +*.aar +*.ap_ +*.aab + +# Files for the ART/Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ +build/ +app/build/ +.cxx/ +.externalNativeBuild/ + +# Gradle files +.gradle/ +build/ + +# Local configuration file (sdk path, etc) +local.properties +/local.properties + +# Proguard folder generated by Eclipse +proguard/ + +# Log Files +*.log + +# Android Studio Navigation editor temp files +.navigation/ + +# Android Studio captures folder +captures/ +/captures + +# IntelliJ IDEA / Android Studio +*.iml +.idea/ +.idea/libraries +.idea/modules.xml +.idea/workspace.xml +.idea/caches/ +.idea/navEditor.xml +.idea/assetWizardSettings.xml + +# Keystore & Signing Secrets (NEVER COMMIT) +*.jks +*.keystore +keystore.properties + +# OS-specific files +.DS_Store +Thumbs.db + +# Temporary test & debug dumps +*.tmp +/dump* +/screen* +/current_screen.txt +/.screenshot_* + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..1faa02f --- /dev/null +++ b/LICENSE @@ -0,0 +1,621 @@ + 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 severe 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 who make or run 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 diff --git a/README.md b/README.md new file mode 100644 index 0000000..6aca60b --- /dev/null +++ b/README.md @@ -0,0 +1,30 @@ +# OpenLoc + +OpenLoc 是一款专为 Android 平台设计的现代地理位置模拟与隐私辅助工具。 + +--- + +## 软件用途 + +OpenLoc 旨在为开发者、测试人员以及关注个人数字隐私的用户提供安全、可控且纯净的位置环境模拟服务,主要用于以下场景: + +- **位置环境模拟** + 支持在地图上自由选定目标位置或精确检索地理坐标,为应用提供自定义的虚拟定位环境,便于进行基于位置的应用功能开发与场景联调。 + +- **应用作用域管控** + 支持全局模式、黑名单模式与白名单模式,用户可灵活指定哪些应用接收模拟位置、哪些应用使用真实网络环境,避免影响日常无关应用的正常使用。 + +- **常用地点快捷收藏** + 提供便捷的地点收藏与管理功能,支持常用测试点位或兴趣位置的自定义命名、快速切换与拖拽排序。 + +- **多维环境拟真与隐私防护** + 在提供虚拟坐标的同时,协同拟真设备在日常手持、运动状态下的环境表现,避免单一静态坐标导致的数据异常,有效防止个人真实物理行踪的过度获取与隐私泄露。 + +- **纯粹无干扰的交互体验** + 基于 Material 3 现代设计语言构建,界面简洁直观,无后台冗余常驻,注重工具属性的克制与易用性。 + +--- + +## 免责声明 + +本软件仅供合法的软件开发调试、学术研究、定位功能测试及个人隐私保护使用,请勿用于任何违反法律法规或破坏第三方服务协议的用途。 diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..4f2d1c6 --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,84 @@ +import java.util.Properties + +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.compose) +} + + +android { + namespace = "com.lzxnone.openloc" + compileSdk { + version = release(36) { + minorApiLevel = 1 + } + } + + defaultConfig { + applicationId = "com.lzxnone.openloc" + minSdk = 28 + targetSdk = 36 + versionCode = 1 + versionName = "1.0.0" + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + + } + + signingConfigs { + create("release") { + val keystorePropsFile = rootProject.file("keystore.properties") + if (keystorePropsFile.exists()) { + val props = Properties() + keystorePropsFile.inputStream().use { stream -> + props.load(stream) + } + storeFile = file(props.getProperty("storeFile", "openloc.jks")) + storePassword = props.getProperty("storePassword") + keyAlias = props.getProperty("keyAlias") + keyPassword = props.getProperty("keyPassword") + } + } + } + + + buildTypes { + release { + isMinifyEnabled = false + signingConfig = signingConfigs.getByName("release") + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + buildFeatures { + compose = true + } +} + +dependencies { + implementation(platform(libs.androidx.compose.bom)) + implementation(libs.androidx.activity.compose) + implementation(libs.androidx.compose.material3) + implementation(libs.androidx.compose.material.icons.extended) + implementation(libs.androidx.compose.ui) + implementation(libs.androidx.compose.ui.graphics) + implementation(libs.androidx.compose.ui.tooling.preview) + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.lifecycle.runtime.ktx) + implementation(libs.osmdroid.android) + compileOnly(libs.xposed.api) + testImplementation(libs.junit) + androidTestImplementation(platform(libs.androidx.compose.bom)) + androidTestImplementation(libs.androidx.compose.ui.test.junit4) + androidTestImplementation(libs.androidx.espresso.core) + androidTestImplementation(libs.androidx.junit) + debugImplementation(libs.androidx.compose.ui.test.manifest) + debugImplementation(libs.androidx.compose.ui.tooling) +} \ No newline at end of file diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/app/src/androidTest/java/com/lzxnone/openloc/ExampleInstrumentedTest.kt b/app/src/androidTest/java/com/lzxnone/openloc/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..b8fb242 --- /dev/null +++ b/app/src/androidTest/java/com/lzxnone/openloc/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package com.lzxnone.openloc + +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("com.lzxnone.openloc", appContext.packageName) + } +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..43662a7 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/assets/xposed_init b/app/src/main/assets/xposed_init new file mode 100644 index 0000000..7a24f7b --- /dev/null +++ b/app/src/main/assets/xposed_init @@ -0,0 +1 @@ +com.lzxnone.openloc.hook.HookEntry diff --git a/app/src/main/java/com/lzxnone/openloc/MainActivity.kt b/app/src/main/java/com/lzxnone/openloc/MainActivity.kt new file mode 100644 index 0000000..9432d0d --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/MainActivity.kt @@ -0,0 +1,127 @@ +package com.lzxnone.openloc + +import android.app.Activity +import android.content.Context +import android.content.res.Configuration +import android.content.res.Resources +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.remember +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.tooling.preview.Preview +import com.lzxnone.openloc.data.preference.AppLanguage +import com.lzxnone.openloc.data.preference.AppPreferences +import com.lzxnone.openloc.ui.screens.MainScreen +import com.lzxnone.openloc.ui.theme.OpenLocTheme +import java.util.Locale + +class MainActivity : ComponentActivity() { + + override fun attachBaseContext(newBase: Context) { + AppPreferences.init(newBase) + val appLanguage = AppPreferences.appLanguage + val localizedContext = createLocalizedContext(newBase, appLanguage) + super.attachBaseContext(localizedContext) + } + + override fun applyOverrideConfiguration(overrideConfiguration: Configuration?) { + if (overrideConfiguration != null) { + val appLanguage = AppPreferences.appLanguage + val locale = getLocaleForLanguage(appLanguage) + overrideConfiguration.setLocale(locale) + } + super.applyOverrideConfiguration(overrideConfiguration) + } + + override fun onCreate(savedInstanceState: Bundle?) { + AppPreferences.init(applicationContext) + updateActivityLocale(this, AppPreferences.appLanguage) + super.onCreate(savedInstanceState) + + enableEdgeToEdge() + setContent { + val currentLanguage = AppPreferences.appLanguage + val baseContext = LocalContext.current + + val localizedContext = remember(currentLanguage, baseContext) { + createLocalizedContext(baseContext, currentLanguage) + } + + CompositionLocalProvider( + LocalContext provides localizedContext, + LocalConfiguration provides localizedContext.resources.configuration, + androidx.activity.compose.LocalActivityResultRegistryOwner provides this + ) { + OpenLocTheme { + MainScreen() + } + } + } + } +} + +fun getLocaleForLanguage(language: AppLanguage): Locale { + return when (language) { + AppLanguage.SYSTEM -> { + val systemLocales = Resources.getSystem().configuration.locales + if (!systemLocales.isEmpty) systemLocales[0] else Locale.getDefault() + } + AppLanguage.ZH -> Locale.SIMPLIFIED_CHINESE + AppLanguage.EN -> Locale.ENGLISH + } +} + +fun updateActivityLocale(activity: Activity, language: AppLanguage) { + val locale = getLocaleForLanguage(language) + Locale.setDefault(locale) + val resources = activity.resources + val config = Configuration(resources.configuration) + config.setLocale(locale) + config.setLayoutDirection(locale) + @Suppress("DEPRECATION") + resources.updateConfiguration(config, resources.displayMetrics) + @Suppress("DEPRECATION") + activity.applicationContext.resources.updateConfiguration(config, activity.applicationContext.resources.displayMetrics) +} + +/** + * 根据用户选择的语言构建 Localized Context + */ +fun createLocalizedContext(context: Context, language: AppLanguage): Context { + val locale = getLocaleForLanguage(language) + Locale.setDefault(locale) + val config = Configuration(context.resources.configuration) + config.setLocale(locale) + config.setLayoutDirection(locale) + return context.createConfigurationContext(config) +} + +/** + * 为 Dialog / BottomSheet 提供强制局部语言环境的 Composable 容器 + */ +@Composable +fun LocalizedDialogContent(context: Context = LocalContext.current, content: @Composable () -> Unit) { + val appLanguage = AppPreferences.appLanguage + val localized = remember(appLanguage, context) { + createLocalizedContext(context, appLanguage) + } + CompositionLocalProvider( + LocalContext provides localized, + LocalConfiguration provides localized.resources.configuration + ) { + content() + } +} + +@Preview(showBackground = true, name = "Light Theme") +@Composable +fun MainScreenPreviewLight() { + OpenLocTheme { + MainScreen() + } +} \ No newline at end of file diff --git a/app/src/main/java/com/lzxnone/openloc/core/provider/ConfigContract.kt b/app/src/main/java/com/lzxnone/openloc/core/provider/ConfigContract.kt new file mode 100644 index 0000000..a22416d --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/core/provider/ConfigContract.kt @@ -0,0 +1,25 @@ +package com.lzxnone.openloc.core.provider + +/** + * 跨进程数据共享契约常量 + */ +object ConfigContract { + const val AUTHORITY = "com.lzxnone.openloc.provider" + val CONTENT_URI = "content://$AUTHORITY" + + const val METHOD_GET_CONFIG = "get_mock_config" + + const val KEY_ENABLED = "key_is_enabled" + const val KEY_LATITUDE = "key_latitude" + const val KEY_LONGITUDE = "key_longitude" + const val KEY_LOCATION_NAME = "key_location_name" + const val KEY_APP_MOCK_MODE = "key_app_mock_mode" + const val KEY_WHITELIST_APPS = "key_whitelist_apps" + const val KEY_BLACKLIST_APPS = "key_blacklist_apps" + const val KEY_ENABLE_JITTER = "key_enable_jitter" + const val KEY_ENABLE_GNSS_SIMULATION = "key_enable_gnss_simulation" + const val KEY_ENABLE_NETWORK_CAMOUFLAGE = "key_enable_network_camouflage" + const val KEY_ENABLE_SENSOR_SIMULATION = "key_enable_sensor_simulation" + const val KEY_ENABLE_STEALTH = "key_enable_stealth" + const val KEY_ENABLE_DEV_CAMOUFLAGE = "key_enable_dev_camouflage" +} diff --git a/app/src/main/java/com/lzxnone/openloc/core/provider/LocationConfigProvider.kt b/app/src/main/java/com/lzxnone/openloc/core/provider/LocationConfigProvider.kt new file mode 100644 index 0000000..0f8852b --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/core/provider/LocationConfigProvider.kt @@ -0,0 +1,82 @@ +package com.lzxnone.openloc.core.provider + +import android.content.ContentProvider +import android.content.ContentValues +import android.content.Context +import android.database.Cursor +import android.net.Uri +import android.os.Bundle +import com.lzxnone.openloc.data.preference.AppPreferences + +/** + * 跨进程配置共享服务提供者 + * + * 目标 App 进程内的 Hook 代码通过调用此 Provider 的 call 方法, + * 实时拉取 OpenLoc 中用户配置的最新总开关与虚拟坐标。 + */ +class LocationConfigProvider : ContentProvider() { + + override fun onCreate(): Boolean { + context?.let { ctx -> + AppPreferences.init(ctx.applicationContext) + } + return true + } + + override fun call(method: String, arg: String?, extras: Bundle?): Bundle? { + if (method == ConfigContract.METHOD_GET_CONFIG) { + val ctx = context ?: return null + // 确保读取到最新存储 + val prefs = ctx.getSharedPreferences("openloc_prefs", Context.MODE_PRIVATE) + + val isEnabled = prefs.getBoolean("mock_service_enabled", false) + val lat = prefs.getString("mock_latitude", "39.908722")?.toDoubleOrNull() ?: 39.908722 + val lng = prefs.getString("mock_longitude", "116.397496")?.toDoubleOrNull() ?: 116.397496 + val name = prefs.getString("mock_location_name", "") ?: "" + val mode = prefs.getString("app_mock_mode", "GLOBAL") ?: "GLOBAL" + val whitelistJson = prefs.getString("whitelist_apps", "[]") ?: "[]" + val blacklistJson = prefs.getString("blacklist_apps", "[]") ?: "[]" + val isJitter = prefs.getBoolean("enable_jitter", true) + val isGnss = prefs.getBoolean("enable_gnss_simulation", true) + val isNetwork = prefs.getBoolean("enable_network_camouflage", true) + val isSensor = prefs.getBoolean("enable_sensor_simulation", true) + val isStealth = prefs.getBoolean("enable_stealth", true) + val isDevCamouflage = prefs.getBoolean("enable_dev_camouflage", true) + + return Bundle().apply { + putBoolean(ConfigContract.KEY_ENABLED, isEnabled) + putDouble(ConfigContract.KEY_LATITUDE, lat) + putDouble(ConfigContract.KEY_LONGITUDE, lng) + putString(ConfigContract.KEY_LOCATION_NAME, name) + putString(ConfigContract.KEY_APP_MOCK_MODE, mode) + putString(ConfigContract.KEY_WHITELIST_APPS, whitelistJson) + putString(ConfigContract.KEY_BLACKLIST_APPS, blacklistJson) + putBoolean(ConfigContract.KEY_ENABLE_JITTER, isJitter) + putBoolean(ConfigContract.KEY_ENABLE_GNSS_SIMULATION, isGnss) + putBoolean(ConfigContract.KEY_ENABLE_NETWORK_CAMOUFLAGE, isNetwork) + putBoolean(ConfigContract.KEY_ENABLE_SENSOR_SIMULATION, isSensor) + putBoolean(ConfigContract.KEY_ENABLE_STEALTH, isStealth) + putBoolean(ConfigContract.KEY_ENABLE_DEV_CAMOUFLAGE, isDevCamouflage) + } + } + return super.call(method, arg, extras) + } + + override fun query( + uri: Uri, + projection: Array?, + selection: String?, + selectionArgs: Array?, + sortOrder: String? + ): Cursor? = null + + override fun getType(uri: Uri): String? = null + override fun insert(uri: Uri, values: ContentValues?): Uri? = null + override fun delete(uri: Uri, selection: String?, selectionArgs: Array?): Int = 0 + override fun update( + uri: Uri, + values: ContentValues?, + selection: String?, + selectionArgs: Array? + ): Int = 0 +} diff --git a/app/src/main/java/com/lzxnone/openloc/core/util/CoordinateConverter.kt b/app/src/main/java/com/lzxnone/openloc/core/util/CoordinateConverter.kt new file mode 100644 index 0000000..71bf7f4 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/core/util/CoordinateConverter.kt @@ -0,0 +1,127 @@ +package com.lzxnone.openloc.core.util + +import kotlin.math.abs +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.sin +import kotlin.math.sqrt + +/** + * 中国标准坐标系转换工具 + * WGS-84: GPS原始地球坐标系(国际标准,Android系统硬件与系统底层LocationManager输出标准) + * GCJ-02: 火星坐标系(中国国测局标准,高德地图、腾讯地图、谷歌中国采用) + * BD-09: 百度坐标系(百度地图在GCJ-02基础上进一步加偏采用) + */ +object CoordinateConverter { + + private const val X_PI = 3.14159265358979324 * 3000.0 / 180.0 + private const val PI = 3.1415926535897932384626 + private const val A = 6378245.0 // 长半轴 + private const val EE = 0.00669342162296594323 // 扁率平方 + + /** + * 判断坐标是否在中国境外(境外不进行火星加偏) + */ + fun outOfChina(lat: Double, lng: Double): Boolean { + if (lng < 72.004 || lng > 137.8347) return true + if (lat < 0.8293 || lat > 55.8271) return true + return false + } + + /** + * WGS-84 转 GCJ-02 (高德/腾讯/国测局) + * 用于将真实设备 GPS 坐标转换后精准打在 OpenLoc 的高德瓦片底图上 + */ + fun wgs84ToGcj02(lat: Double, lng: Double): DoubleArray { + if (outOfChina(lat, lng)) { + return doubleArrayOf(lat, lng) + } + var dLat = transformLat(lng - 105.0, lat - 35.0) + var dLng = transformLng(lng - 105.0, lat - 35.0) + val radLat = lat / 180.0 * PI + var magic = sin(radLat) + magic = 1 - EE * magic * magic + val sqrtMagic = sqrt(magic) + dLat = (dLat * 180.0) / ((A * (1 - EE)) / (magic * sqrtMagic) * PI) + dLng = (dLng * 180.0) / (A / sqrtMagic * cos(radLat) * PI) + return doubleArrayOf(lat + dLat, lng + dLng) + } + + /** + * GCJ-02 转 WGS-84 + * 用于将用户在 OpenLoc 高德瓦片上点击的火星坐标还原为国际 WGS-84 标准坐标, + * 传递给目标应用(如百度地图、高德地图、微信等),防止目标应用二次加偏造成几百米严重偏差。 + */ + fun gcj02ToWgs84(lat: Double, lng: Double): DoubleArray { + if (outOfChina(lat, lng)) { + return doubleArrayOf(lat, lng) + } + var dLat = transformLat(lng - 105.0, lat - 35.0) + var dLng = transformLng(lng - 105.0, lat - 35.0) + val radLat = lat / 180.0 * PI + var magic = sin(radLat) + magic = 1 - EE * magic * magic + val sqrtMagic = sqrt(magic) + dLat = (dLat * 180.0) / ((A * (1 - EE)) / (magic * sqrtMagic) * PI) + dLng = (dLng * 180.0) / (A / sqrtMagic * cos(radLat) * PI) + val mgLat = lat + dLat + val mgLng = lng + dLng + return doubleArrayOf(lat * 2 - mgLat, lng * 2 - mgLng) + } + + /** + * WGS-84 直接转 BD-09 (百度坐标系) + */ + fun wgs84ToBd09(lat: Double, lng: Double): DoubleArray { + val gcj = wgs84ToGcj02(lat, lng) + return gcj02ToBd09(gcj[0], gcj[1]) + } + + /** + * GCJ-02 转 BD-09 (百度坐标系) + */ + fun gcj02ToBd09(lat: Double, lng: Double): DoubleArray { + val z = sqrt(lng * lng + lat * lat) + 0.00002 * sin(lat * X_PI) + val theta = atan2(lat, lng) + 0.000003 * cos(lng * X_PI) + val bdLng = z * cos(theta) + 0.0065 + val bdLat = z * sin(theta) + 0.006 + return doubleArrayOf(bdLat, bdLng) + } + + /** + * BD-09 转 GCJ-02 + */ + fun bd09ToGcj02(lat: Double, lng: Double): DoubleArray { + val x = lng - 0.0065 + val y = lat - 0.006 + val z = sqrt(x * x + y * y) - 0.00002 * sin(y * X_PI) + val theta = atan2(y, x) - 0.000003 * cos(x * X_PI) + val gcjLng = z * cos(theta) + val gcjLat = z * sin(theta) + return doubleArrayOf(gcjLat, gcjLng) + } + + /** + * BD-09 转 WGS-84 + */ + fun bd09ToWgs84(lat: Double, lng: Double): DoubleArray { + val gcj = bd09ToGcj02(lat, lng) + return gcj02ToWgs84(gcj[0], gcj[1]) + } + + private fun transformLat(x: Double, y: Double): Double { + var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * sqrt(abs(x)) + ret += (20.0 * sin(6.0 * x * PI) + 20.0 * sin(2.0 * x * PI)) * 2.0 / 3.0 + ret += (20.0 * sin(y * PI) + 40.0 * sin(y / 3.0 * PI)) * 2.0 / 3.0 + ret += (160.0 * sin(y / 12.0 * PI) + 320 * sin(y * PI / 30.0)) * 2.0 / 3.0 + return ret + } + + private fun transformLng(x: Double, y: Double): Double { + var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * sqrt(abs(x)) + ret += (20.0 * sin(6.0 * x * PI) + 20.0 * sin(2.0 * x * PI)) * 2.0 / 3.0 + ret += (20.0 * sin(x * PI) + 40.0 * sin(x / 3.0 * PI)) * 2.0 / 3.0 + ret += (150.0 * sin(x / 12.0 * PI) + 300.0 * sin(x / 30.0 * PI)) * 2.0 / 3.0 + return ret + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/core/util/HookStatus.kt b/app/src/main/java/com/lzxnone/openloc/core/util/HookStatus.kt new file mode 100644 index 0000000..89b42e8 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/core/util/HookStatus.kt @@ -0,0 +1,15 @@ +package com.lzxnone.openloc.core.util + +/** + * 模块激活状态判定桩 + * + * 在 Xposed / LSPosed 架构中,应用本体与 Hook 模块共享此方法: + * - 默认情况下,该方法返回 false(表示未激活或当前未被框架注入)。 + * - 当 Xposed / LSPosed 加载本模块并注入本应用进程时,会 Hook 此方法令其恒返回 true。 + */ +object HookStatus { + @JvmStatic + fun isModuleActive(): Boolean { + return false + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/core/util/LocationResolver.kt b/app/src/main/java/com/lzxnone/openloc/core/util/LocationResolver.kt new file mode 100644 index 0000000..9f7921a --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/core/util/LocationResolver.kt @@ -0,0 +1,611 @@ +package com.lzxnone.openloc.core.util + +import android.content.Context +import android.location.Address +import android.location.Geocoder +import android.os.Build +import com.lzxnone.openloc.data.preference.AppPreferences +import com.lzxnone.openloc.data.preference.SearchProvider +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withContext +import org.json.JSONObject +import java.net.HttpURLConnection +import java.net.URL +import java.net.URLEncoder +import java.util.Locale +import kotlin.coroutines.resume + +/** + * 搜索结果数据结构 (经纬度统一存储为国际标准 WGS-84) + */ +data class SearchResult( + val name: String, + val address: String, + val latitude: Double, + val longitude: Double +) + +/** + * 搜索响应封装,包含结果列表与错误状态 + */ +data class SearchResponse( + val results: List, + val errorMessage: String? = null // null 正常,"NO_API_KEY", "KEY_INVALID: ...", "NETWORK_ERROR: ..." +) + +/** + * 地理编码、逆地理编码与多源搜索服务工具类 + * 支持商用源(高德 Web 服务、百度地图 Web 服务)及免 Key 免费源(Photon、Nominatim) + */ +object LocationResolver { + + /** + * 测试指定提供商的 API Key / AK 是否有效 + * @return Pair(isSuccess, errorMessage) + */ + suspend fun testApiKey(provider: SearchProvider, key: String): Pair = withContext(Dispatchers.IO) { + val trimmedKey = key.trim() + if (trimmedKey.isEmpty()) { + return@withContext Pair(false, "KEY_EMPTY") + } + + try { + when (provider) { + SearchProvider.AMAP -> { + val encoded = URLEncoder.encode("Beijing", "UTF-8") + val urlStr = "https://restapi.amap.com/v3/place/text?keywords=$encoded&key=$trimmedKey&offset=1&page=1" + val conn = (URL(urlStr).openConnection() as HttpURLConnection).apply { + requestMethod = "GET" + connectTimeout = 4000 + readTimeout = 4000 + } + if (conn.responseCode == HttpURLConnection.HTTP_OK) { + val body = conn.inputStream.bufferedReader().use { it.readText() } + val json = JSONObject(body) + val status = json.optString("status") + if (status == "1") { + Pair(true, null) + } else { + val info = json.optString("info") + val infocode = json.optString("infocode") + Pair(false, "$info ($infocode)") + } + } else { + Pair(false, "HTTP ${conn.responseCode}") + } + } + SearchProvider.BAIDU -> { + val encoded = URLEncoder.encode("Beijing", "UTF-8") + val urlStr = "https://api.map.baidu.com/place/v2/suggestion?query=$encoded®ion=%E5%85%A8%E5%9B%BD&output=json&ak=$trimmedKey" + val conn = (URL(urlStr).openConnection() as HttpURLConnection).apply { + requestMethod = "GET" + connectTimeout = 4000 + readTimeout = 4000 + } + if (conn.responseCode == HttpURLConnection.HTTP_OK) { + val body = conn.inputStream.bufferedReader().use { it.readText() } + val json = JSONObject(body) + val status = json.optInt("status", -1) + if (status == 0) { + Pair(true, null) + } else { + val msg = json.optString("message") + Pair(false, "$msg ($status)") + } + } else { + Pair(false, "HTTP ${conn.responseCode}") + } + } + else -> Pair(true, null) + } + } catch (e: Exception) { + Pair(false, e.localizedMessage ?: "NETWORK_ERROR") + } + } + + /** + * 逆地理编码:将坐标反查为人类可读地名 + */ + suspend fun resolveLocationName( + context: Context, + wgsLat: Double, + wgsLng: Double + ): String = withContext(Dispatchers.IO) { + val provider = AppPreferences.searchProvider + + // 通道 1: 高德地图逆地理服务 (当选定高德且配置了 Key 时) + if (provider == SearchProvider.AMAP && AppPreferences.amapApiKey.isNotBlank()) { + try { + val gcj = CoordinateConverter.wgs84ToGcj02(wgsLat, wgsLng) + val urlString = "https://restapi.amap.com/v3/geocode/regeo?location=${gcj[1]},${gcj[0]}&key=${AppPreferences.amapApiKey}&extensions=all" + val connection = (URL(urlString).openConnection() as HttpURLConnection).apply { + requestMethod = "GET" + connectTimeout = 3000 + readTimeout = 3000 + } + + if (connection.responseCode == HttpURLConnection.HTTP_OK) { + val responseBody = connection.inputStream.bufferedReader().use { it.readText() } + val json = JSONObject(responseBody) + if (json.optString("status") == "1") { + val regeocode = json.optJSONObject("regeocode") + if (regeocode != null) { + val pois = regeocode.optJSONArray("pois") + if (pois != null && pois.length() > 0) { + val firstPoi = pois.getJSONObject(0) + val poiName = firstPoi.optString("name") + if (poiName.isNotBlank()) return@withContext poiName + } + val formattedAddress = regeocode.optString("formatted_address") + if (formattedAddress.isNotBlank()) return@withContext formattedAddress + } + } + } + } catch (_: Throwable) {} + } + + // 通道 2: 百度地图逆地理服务 (当选定百度且配置了 AK 时) + if (provider == SearchProvider.BAIDU && AppPreferences.baiduApiKey.isNotBlank()) { + try { + val urlString = "https://api.map.baidu.com/reverse_geocoding/v3/?ak=${AppPreferences.baiduApiKey}&output=json&coordtype=wgs84ll&location=$wgsLat,$wgsLng" + val connection = (URL(urlString).openConnection() as HttpURLConnection).apply { + requestMethod = "GET" + connectTimeout = 3000 + readTimeout = 3000 + } + + if (connection.responseCode == HttpURLConnection.HTTP_OK) { + val responseBody = connection.inputStream.bufferedReader().use { it.readText() } + val json = JSONObject(responseBody) + if (json.optInt("status", -1) == 0) { + val result = json.optJSONObject("result") + if (result != null) { + val pois = result.optJSONArray("pois") + if (pois != null && pois.length() > 0) { + val firstPoi = pois.getJSONObject(0) + val poiName = firstPoi.optString("name") + if (poiName.isNotBlank()) return@withContext poiName + } + val formattedAddress = result.optString("formatted_address") + if (formattedAddress.isNotBlank()) return@withContext formattedAddress + } + } + } + } catch (_: Throwable) {} + } + + // 通道 3: 原生 Android Geocoder + try { + if (Geocoder.isPresent()) { + val geocoder = Geocoder(context, Locale.getDefault()) + val addresses: List
= if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + suspendCancellableCoroutine { continuation -> + try { + geocoder.getFromLocation(wgsLat, wgsLng, 1, object : Geocoder.GeocodeListener { + override fun onGeocode(results: MutableList
) { + continuation.resume(results) + } + + override fun onError(errorMessage: String?) { + continuation.resume(emptyList()) + } + }) + } catch (_: Exception) { + continuation.resume(emptyList()) + } + } + } else { + @Suppress("DEPRECATION") + try { + geocoder.getFromLocation(wgsLat, wgsLng, 1) ?: emptyList() + } catch (_: Exception) { + emptyList() + } + } + + if (addresses.isNotEmpty()) { + val address = addresses[0] + val feature = address.featureName + val thoroughfare = address.thoroughfare + val subLocality = address.subLocality + val locality = address.locality + + val name = when { + !feature.isNullOrBlank() && feature != thoroughfare && feature != subLocality -> feature + !thoroughfare.isNullOrBlank() -> thoroughfare + !subLocality.isNullOrBlank() -> "${locality ?: ""} $subLocality".trim() + !locality.isNullOrBlank() -> locality + else -> address.getAddressLine(0) ?: "" + } + if (name.isNotBlank()) { + return@withContext name + } + } + } + } catch (_: Throwable) {} + + // 最终兜底:格式化经纬度显示 + String.format(Locale.getDefault(), "%.5f, %.5f", wgsLat, wgsLng) + } + + /** + * 统一地点与坐标搜索入口 + */ + suspend fun searchPlaces(context: Context, query: String): SearchResponse = withContext(Dispatchers.IO) { + val trimmed = query.trim() + if (trimmed.isEmpty()) return@withContext SearchResponse(emptyList(), null) + + // 1. 纯经纬度坐标输入格式检查(如 "30.54, 114.32") + val parts = trimmed.split(",", ",", " ", "、").filter { it.isNotBlank() } + if (parts.size >= 2) { + val lat = parts[0].toDoubleOrNull() + val lng = parts[1].toDoubleOrNull() + if (lat != null && lng != null && lat in -90.0..90.0 && lng in -180.0..180.0) { + return@withContext SearchResponse( + results = listOf( + SearchResult( + name = String.format(Locale.getDefault(), "%.6f, %.6f", lat, lng), + address = context.getString(com.lzxnone.openloc.R.string.location_search_coord_format, lng, lat), + latitude = lat, + longitude = lng + ) + ), + errorMessage = null + ) + } + } + + // 2. 根据当前选定的搜索引擎提供商分流 + val provider = AppPreferences.searchProvider + when (provider) { + SearchProvider.AMAP -> searchAmap(trimmed) + SearchProvider.BAIDU -> searchBaidu(trimmed) + SearchProvider.PHOTON -> searchPhoton(trimmed) + SearchProvider.NOMINATIM -> searchNominatim(trimmed) + } + } + + /** + * 高德地图 (AMap) 搜索实现 + */ + private fun searchAmap(query: String): SearchResponse { + val apiKey = AppPreferences.amapApiKey + if (apiKey.isBlank()) { + return SearchResponse(emptyList(), "NO_API_KEY") + } + + try { + val encodedQuery = URLEncoder.encode(query, "UTF-8") + val tipUrl = "https://restapi.amap.com/v3/assistant/inputtips?keywords=$encodedQuery&key=$apiKey" + val connection = (URL(tipUrl).openConnection() as HttpURLConnection).apply { + requestMethod = "GET" + connectTimeout = 4000 + readTimeout = 4000 + } + + if (connection.responseCode == HttpURLConnection.HTTP_OK) { + val responseBody = connection.inputStream.bufferedReader().use { it.readText() } + val json = JSONObject(responseBody) + val status = json.optString("status") + val info = json.optString("info") + val infocode = json.optString("infocode") + + if (status != "1") { + return SearchResponse(emptyList(), "KEY_INVALID: $info ($infocode)") + } + + val tips = json.optJSONArray("tips") + val results = mutableListOf() + if (tips != null) { + for (i in 0 until tips.length()) { + val tip = tips.getJSONObject(i) + val name = tip.optString("name") + val district = tip.optString("district") + val address = tip.optString("address") + val locStr = tip.optString("location") + + if (locStr.isNotBlank() && locStr.contains(",")) { + val locParts = locStr.split(",") + val gcjLng = locParts[0].toDoubleOrNull() + val gcjLat = locParts.getOrNull(1)?.toDoubleOrNull() + if (gcjLat != null && gcjLng != null) { + val wgs = CoordinateConverter.gcj02ToWgs84(gcjLat, gcjLng) + val fullAddr = listOf(district, address) + .filter { it.isNotBlank() && it != "[]" } + .joinToString(" ") + + results.add( + SearchResult( + name = name, + address = fullAddr.ifBlank { name }, + latitude = wgs[0], + longitude = wgs[1] + ) + ) + } + } + } + } + + if (results.isEmpty()) { + val searchUrl = "https://restapi.amap.com/v3/place/text?keywords=$encodedQuery&key=$apiKey&offset=15&page=1" + val searchConn = (URL(searchUrl).openConnection() as HttpURLConnection).apply { + requestMethod = "GET" + connectTimeout = 4000 + readTimeout = 4000 + } + if (searchConn.responseCode == HttpURLConnection.HTTP_OK) { + val sBody = searchConn.inputStream.bufferedReader().use { it.readText() } + val sJson = JSONObject(sBody) + if (sJson.optString("status") == "1") { + val pois = sJson.optJSONArray("pois") + if (pois != null) { + for (i in 0 until pois.length()) { + val poi = pois.getJSONObject(i) + val name = poi.optString("name") + val pname = poi.optString("pname") + val cityname = poi.optString("cityname") + val adname = poi.optString("adname") + val address = poi.optString("address") + val locStr = poi.optString("location") + + if (locStr.isNotBlank() && locStr.contains(",")) { + val locParts = locStr.split(",") + val gcjLng = locParts[0].toDoubleOrNull() + val gcjLat = locParts.getOrNull(1)?.toDoubleOrNull() + if (gcjLat != null && gcjLng != null) { + val wgs = CoordinateConverter.gcj02ToWgs84(gcjLat, gcjLng) + val fullAddr = listOf(pname, cityname, adname, address) + .filter { it.isNotBlank() && it != "[]" } + .joinToString(" ") + + results.add( + SearchResult( + name = name, + address = fullAddr.ifBlank { name }, + latitude = wgs[0], + longitude = wgs[1] + ) + ) + } + } + } + } + } + } + } + + return SearchResponse(results, null) + } else { + return SearchResponse(emptyList(), "HTTP_ERROR: ${connection.responseCode}") + } + } catch (e: Exception) { + return SearchResponse(emptyList(), "NETWORK_ERROR: ${e.message}") + } + } + + /** + * 百度地图 (Baidu) 搜索实现 + */ + private fun searchBaidu(query: String): SearchResponse { + val apiKey = AppPreferences.baiduApiKey + if (apiKey.isBlank()) { + return SearchResponse(emptyList(), "NO_API_KEY") + } + + try { + val encodedQuery = URLEncoder.encode(query, "UTF-8") + val urlString = "https://api.map.baidu.com/place/v2/suggestion?query=$encodedQuery®ion=%E5%85%A8%E5%9B%BD&output=json&ak=$apiKey" + val connection = (URL(urlString).openConnection() as HttpURLConnection).apply { + requestMethod = "GET" + connectTimeout = 4000 + readTimeout = 4000 + } + + if (connection.responseCode == HttpURLConnection.HTTP_OK) { + val responseBody = connection.inputStream.bufferedReader().use { it.readText() } + val json = JSONObject(responseBody) + val status = json.optInt("status", -1) + val message = json.optString("message") + + if (status != 0) { + return SearchResponse(emptyList(), "KEY_INVALID: $message ($status)") + } + + val results = mutableListOf() + val resultList = json.optJSONArray("result") + if (resultList != null) { + for (i in 0 until resultList.length()) { + val item = resultList.getJSONObject(i) + val name = item.optString("name") + val province = item.optString("province") + val city = item.optString("city") + val district = item.optString("district") + val address = item.optString("address") + val loc = item.optJSONObject("location") + + if (loc != null) { + val bdLat = loc.optDouble("lat", Double.NaN) + val bdLng = loc.optDouble("lng", Double.NaN) + if (!bdLat.isNaN() && !bdLng.isNaN()) { + // 百度坐标系 (BD-09) 转换为标准 WGS-84 + val wgs = CoordinateConverter.bd09ToWgs84(bdLat, bdLng) + val fullAddr = listOf(province, city, district, address) + .filter { it.isNotBlank() } + .distinct() + .joinToString(" ") + + results.add( + SearchResult( + name = name, + address = fullAddr.ifBlank { name }, + latitude = wgs[0], + longitude = wgs[1] + ) + ) + } + } + } + } + + if (results.isEmpty()) { + // 降级使用 place/v2/search 检索 + val searchUrl = "https://api.map.baidu.com/place/v2/search?query=$encodedQuery®ion=%E5%85%A8%E5%9B%BD&output=json&ak=$apiKey&page_size=15&page_num=0" + val searchConn = (URL(searchUrl).openConnection() as HttpURLConnection).apply { + requestMethod = "GET" + connectTimeout = 4000 + readTimeout = 4000 + } + if (searchConn.responseCode == HttpURLConnection.HTTP_OK) { + val sBody = searchConn.inputStream.bufferedReader().use { it.readText() } + val sJson = JSONObject(sBody) + val sResults = sJson.optJSONArray("results") + if (sResults != null) { + for (i in 0 until sResults.length()) { + val item = sResults.getJSONObject(i) + val name = item.optString("name") + val address = item.optString("address") + val loc = item.optJSONObject("location") + if (loc != null) { + val bdLat = loc.optDouble("lat", Double.NaN) + val bdLng = loc.optDouble("lng", Double.NaN) + if (!bdLat.isNaN() && !bdLng.isNaN()) { + val wgs = CoordinateConverter.bd09ToWgs84(bdLat, bdLng) + results.add( + SearchResult( + name = name, + address = address.ifBlank { name }, + latitude = wgs[0], + longitude = wgs[1] + ) + ) + } + } + } + } + } + } + + return SearchResponse(results, null) + } else { + return SearchResponse(emptyList(), "HTTP_ERROR: ${connection.responseCode}") + } + } catch (e: Exception) { + return SearchResponse(emptyList(), "NETWORK_ERROR: ${e.message}") + } + } + + /** + * Photon (基于 OpenStreetMap) 免 Key 极速搜索实现 + */ + private fun searchPhoton(query: String): SearchResponse { + try { + val encodedQuery = URLEncoder.encode(query, "UTF-8") + val urlString = "https://photon.komoot.io/api/?q=$encodedQuery&limit=20&lang=zh" + val connection = (URL(urlString).openConnection() as HttpURLConnection).apply { + requestMethod = "GET" + connectTimeout = 5000 + readTimeout = 5000 + setRequestProperty("User-Agent", "OpenLoc/1.0 (Android)") + } + + if (connection.responseCode == HttpURLConnection.HTTP_OK) { + val body = connection.inputStream.bufferedReader().use { it.readText() } + val json = JSONObject(body) + val features = json.optJSONArray("features") + val results = mutableListOf() + + if (features != null) { + for (i in 0 until features.length()) { + val feat = features.getJSONObject(i) + val props = feat.optJSONObject("properties") ?: continue + val geom = feat.optJSONObject("geometry") ?: continue + val coords = geom.optJSONArray("coordinates") ?: continue + + if (coords.length() >= 2) { + val lng = coords.getDouble(0) // Photon 返回 [lon, lat] (WGS-84) + val lat = coords.getDouble(1) + + val name = props.optString("name") + val street = props.optString("street") + val district = props.optString("district") + val city = props.optString("city") + val state = props.optString("state") + val country = props.optString("country") + + val fullAddress = listOf(country, state, city, district, street) + .filter { it.isNotBlank() } + .distinct() + .joinToString(" ") + + if (name.isNotBlank()) { + results.add( + SearchResult( + name = name, + address = fullAddress.ifBlank { name }, + latitude = lat, + longitude = lng + ) + ) + } + } + } + } + + return SearchResponse(results, null) + } else { + return SearchResponse(emptyList(), "HTTP_ERROR: ${connection.responseCode}") + } + } catch (e: Exception) { + return SearchResponse(emptyList(), "NETWORK_ERROR: ${e.message}") + } + } + + /** + * Nominatim (OpenStreetMap 官方) 免 Key 搜索实现 + */ + private fun searchNominatim(query: String): SearchResponse { + try { + val encodedQuery = URLEncoder.encode(query, "UTF-8") + val urlString = "https://nominatim.openstreetmap.org/search?q=$encodedQuery&format=json&addressdetails=1&limit=20&accept-language=zh" + val connection = (URL(urlString).openConnection() as HttpURLConnection).apply { + requestMethod = "GET" + connectTimeout = 6000 + readTimeout = 6000 + setRequestProperty("User-Agent", "OpenLoc/1.0 (Android)") + } + + if (connection.responseCode == HttpURLConnection.HTTP_OK) { + val body = connection.inputStream.bufferedReader().use { it.readText() } + val array = org.json.JSONArray(body) + val results = mutableListOf() + + for (i in 0 until array.length()) { + val item = array.getJSONObject(i) + val displayName = item.optString("display_name") + val name = item.optString("name").ifBlank { displayName.split(",").firstOrNull() ?: displayName } + val lat = item.optString("lat").toDoubleOrNull() + val lng = item.optString("lon").toDoubleOrNull() + + if (lat != null && lng != null) { + results.add( + SearchResult( + name = name, + address = displayName, + latitude = lat, + longitude = lng + ) + ) + } + } + + return SearchResponse(results, null) + } else { + return SearchResponse(emptyList(), "HTTP_ERROR: ${connection.responseCode}") + } + } catch (e: Exception) { + return SearchResponse(emptyList(), "NETWORK_ERROR: ${e.message}") + } + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/data/model/FavoriteItem.kt b/app/src/main/java/com/lzxnone/openloc/data/model/FavoriteItem.kt new file mode 100644 index 0000000..4978827 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/data/model/FavoriteItem.kt @@ -0,0 +1,16 @@ +package com.lzxnone.openloc.data.model + +import java.util.UUID + +/** + * 收藏夹地点条目数据结构 + * 经纬度统一存储为国际标准 WGS-84 + */ +data class FavoriteItem( + val id: String = UUID.randomUUID().toString(), + val name: String, + val address: String, + val latitude: Double, + val longitude: Double, + val timestamp: Long = System.currentTimeMillis() +) diff --git a/app/src/main/java/com/lzxnone/openloc/data/preference/AppPreferences.kt b/app/src/main/java/com/lzxnone/openloc/data/preference/AppPreferences.kt new file mode 100644 index 0000000..396a553 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/data/preference/AppPreferences.kt @@ -0,0 +1,501 @@ +package com.lzxnone.openloc.data.preference + +import android.content.Context +import android.content.SharedPreferences +import androidx.annotation.StringRes +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableLongStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb +import com.lzxnone.openloc.R +import com.lzxnone.openloc.core.util.SearchResult +import com.lzxnone.openloc.data.model.FavoriteItem + +enum class ThemeMode(@param:StringRes val titleRes: Int) { + SYSTEM(R.string.settings_theme_mode_system), + LIGHT(R.string.settings_theme_mode_light), + DARK(R.string.settings_theme_mode_dark) +} + +enum class SearchProvider( + val id: String, + @param:StringRes val titleRes: Int, + val requiresKey: Boolean +) { + AMAP("amap", R.string.search_provider_amap, requiresKey = true), + BAIDU("baidu", R.string.search_provider_baidu, requiresKey = true), + PHOTON("photon", R.string.search_provider_photon, requiresKey = false), + NOMINATIM("nominatim", R.string.search_provider_nominatim, requiresKey = false); + + companion object { + fun fromId(id: String): SearchProvider { + return entries.firstOrNull { it.id.equals(id, ignoreCase = true) } ?: AMAP + } + } +} + +enum class AppLanguage(val tag: String, @param:StringRes val titleRes: Int) { + SYSTEM("", R.string.settings_language_system), + ZH("zh-CN", R.string.settings_language_zh), + EN("en", R.string.settings_language_en); + + companion object { + fun fromTag(tag: String): AppLanguage { + return entries.firstOrNull { it.tag.equals(tag, ignoreCase = true) } ?: SYSTEM + } + } +} + +/** + * 预设质感主题色列表 + */ +val PresetThemeColors = listOf( + Color(0xFF0061A4), // 科技蓝(默认) + Color(0xFF006D44), // 薄荷森绿 + Color(0xFF6750A4), // 优雅紫 + Color(0xFFA04100), // 活力橙 + Color(0xFF006874), // 深邃青 + Color(0xFFB3261E), // 热情红 + Color(0xFF984061), // 玫瑰粉 + Color(0xFF5A5F67) // 沉稳灰 +) + +/** + * 应用虚拟定位生效模式 + */ +enum class AppMockMode { + GLOBAL, // 全局模式:整机所有应用生效 + BLACKLIST, // 黑名单模式:黑名单内应用保持真实定位,其余生效虚拟 + WHITELIST; // 白名单模式:仅白名单内应用生效虚拟,其余保持真实定位 + + companion object { + fun fromId(id: String): AppMockMode { + return entries.firstOrNull { it.name.equals(id, ignoreCase = true) } ?: GLOBAL + } + } +} + +object AppPreferences { + private const val PREF_NAME = "openloc_prefs" + private const val KEY_THEME_MODE = "theme_mode" + private const val KEY_THEME_COLOR = "theme_color" + private const val KEY_DYNAMIC_COLOR = "dynamic_color" + private const val KEY_LANGUAGE = "language" + private const val KEY_SERVICE_ENABLED = "mock_service_enabled" + + private lateinit var prefs: SharedPreferences + + var themeMode by mutableStateOf(ThemeMode.SYSTEM) + private set + + var themeColor by mutableLongStateOf(0xFF0061A4) + private set + + var isDynamicColor by mutableStateOf(false) + private set + + private const val KEY_MOCK_LATITUDE = "mock_latitude" + private const val KEY_MOCK_LONGITUDE = "mock_longitude" + private const val KEY_MOCK_LOCATION_NAME = "mock_location_name" + private const val KEY_HAS_USER_SET_LOCATION = "has_user_set_location" + private const val KEY_SEARCH_HISTORY = "search_history" + private const val KEY_SEARCH_PROVIDER = "search_provider" + private const val KEY_AMAP_API_KEY = "amap_api_key" + private const val KEY_BAIDU_API_KEY = "baidu_api_key" + private const val KEY_FAVORITES = "favorites" + private const val KEY_APP_MOCK_MODE = "app_mock_mode" + private const val KEY_WHITELIST_APPS = "whitelist_apps" + private const val KEY_BLACKLIST_APPS = "blacklist_apps" + private const val KEY_ENABLE_JITTER = "enable_jitter" + private const val KEY_ENABLE_GNSS_SIMULATION = "enable_gnss_simulation" + private const val KEY_ENABLE_NETWORK_CAMOUFLAGE = "enable_network_camouflage" + private const val KEY_ENABLE_SENSOR_SIMULATION = "enable_sensor_simulation" + private const val KEY_ENABLE_STEALTH = "enable_stealth" + private const val KEY_ENABLE_DEV_CAMOUFLAGE = "enable_dev_camouflage" + + var appLanguage by mutableStateOf(AppLanguage.SYSTEM) + private set + + var searchProvider by mutableStateOf(SearchProvider.AMAP) + private set + + var appMockMode by mutableStateOf(AppMockMode.GLOBAL) + private set + + var whitelistApps by mutableStateOf>(emptySet()) + private set + + var blacklistApps by mutableStateOf>(emptySet()) + private set + + var isJitterEnabled by mutableStateOf(true) + private set + + var isGnssSimulationEnabled by mutableStateOf(true) + private set + + var isNetworkCamouflageEnabled by mutableStateOf(true) + private set + + var isSensorSimulationEnabled by mutableStateOf(true) + private set + + var isStealthEnabled by mutableStateOf(true) + private set + + var isDevCamouflageEnabled by mutableStateOf(true) + private set + + var mockLatitude by androidx.compose.runtime.mutableDoubleStateOf(39.908722) + private set + + var mockLongitude by androidx.compose.runtime.mutableDoubleStateOf(116.397496) + private set + + var mockLocationName by mutableStateOf("") + private set + + var hasUserSetLocation by mutableStateOf(false) + private set + + var isServiceEnabled by mutableStateOf(false) + private set + + var searchHistory by mutableStateOf>(emptyList()) + private set + + var favorites by mutableStateOf>(emptyList()) + private set + + var amapApiKey by mutableStateOf("") + private set + + var baiduApiKey by mutableStateOf("") + private set + + fun init(context: Context) { + prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) + + val modeOrdinal = prefs.getInt(KEY_THEME_MODE, ThemeMode.SYSTEM.ordinal) + themeMode = ThemeMode.entries.getOrElse(modeOrdinal) { ThemeMode.SYSTEM } + + themeColor = prefs.getLong(KEY_THEME_COLOR, 0xFF0061A4) + isDynamicColor = prefs.getBoolean(KEY_DYNAMIC_COLOR, false) + + val langTag = prefs.getString(KEY_LANGUAGE, "") ?: "" + appLanguage = AppLanguage.fromTag(langTag) + + val providerId = prefs.getString(KEY_SEARCH_PROVIDER, SearchProvider.AMAP.id) ?: SearchProvider.AMAP.id + searchProvider = SearchProvider.fromId(providerId) + + hasUserSetLocation = prefs.getBoolean(KEY_HAS_USER_SET_LOCATION, false) + mockLatitude = prefs.getString(KEY_MOCK_LATITUDE, "39.908722")?.toDoubleOrNull() ?: 39.908722 + mockLongitude = prefs.getString(KEY_MOCK_LONGITUDE, "116.397496")?.toDoubleOrNull() ?: 116.397496 + mockLocationName = prefs.getString(KEY_MOCK_LOCATION_NAME, "") ?: "" + + isServiceEnabled = prefs.getBoolean(KEY_SERVICE_ENABLED, false) + + val historyJson = prefs.getString(KEY_SEARCH_HISTORY, "[]") ?: "[]" + searchHistory = parseSearchHistory(historyJson) + + val favoritesJson = prefs.getString(KEY_FAVORITES, "[]") ?: "[]" + favorites = parseFavorites(favoritesJson) + + amapApiKey = prefs.getString(KEY_AMAP_API_KEY, "") ?: "" + baiduApiKey = prefs.getString(KEY_BAIDU_API_KEY, "") ?: "" + + val modeStr = prefs.getString(KEY_APP_MOCK_MODE, AppMockMode.GLOBAL.name) ?: AppMockMode.GLOBAL.name + appMockMode = AppMockMode.fromId(modeStr) + + val whitelistJson = prefs.getString(KEY_WHITELIST_APPS, "[]") ?: "[]" + whitelistApps = parsePackageSet(whitelistJson) + + val blacklistJson = prefs.getString(KEY_BLACKLIST_APPS, "[]") ?: "[]" + blacklistApps = parsePackageSet(blacklistJson) + + isJitterEnabled = prefs.getBoolean(KEY_ENABLE_JITTER, true) + isGnssSimulationEnabled = prefs.getBoolean(KEY_ENABLE_GNSS_SIMULATION, true) + isNetworkCamouflageEnabled = prefs.getBoolean(KEY_ENABLE_NETWORK_CAMOUFLAGE, true) + isSensorSimulationEnabled = prefs.getBoolean(KEY_ENABLE_SENSOR_SIMULATION, true) + isStealthEnabled = prefs.getBoolean(KEY_ENABLE_STEALTH, true) + isDevCamouflageEnabled = prefs.getBoolean(KEY_ENABLE_DEV_CAMOUFLAGE, true) + } + + fun updateMockLocation(latitude: Double, longitude: Double, name: String = "", isUserManual: Boolean = true) { + mockLatitude = latitude + mockLongitude = longitude + if (name.isNotEmpty()) { + mockLocationName = name + } + if (isUserManual) { + hasUserSetLocation = true + } + prefs.edit() + .putBoolean(KEY_HAS_USER_SET_LOCATION, hasUserSetLocation) + .putString(KEY_MOCK_LATITUDE, latitude.toString()) + .putString(KEY_MOCK_LONGITUDE, longitude.toString()) + .putString(KEY_MOCK_LOCATION_NAME, mockLocationName) + .apply() + } + + fun updateThemeMode(mode: ThemeMode) { + themeMode = mode + prefs.edit().putInt(KEY_THEME_MODE, mode.ordinal).apply() + } + + fun updateThemeColor(color: Color) { + val colorLong = (color.toArgb().toLong() and 0xFFFFFFFFL) + themeColor = colorLong + prefs.edit().putLong(KEY_THEME_COLOR, colorLong).apply() + } + + fun updateDynamicColor(enabled: Boolean) { + isDynamicColor = enabled + prefs.edit().putBoolean(KEY_DYNAMIC_COLOR, enabled).apply() + } + + fun updateAppLanguage(language: AppLanguage) { + appLanguage = language + prefs.edit().putString(KEY_LANGUAGE, language.tag).apply() + } + + fun updateServiceEnabled(enabled: Boolean) { + isServiceEnabled = enabled + prefs.edit().putBoolean(KEY_SERVICE_ENABLED, enabled).apply() + } + + fun addSearchHistory(item: SearchResult) { + val updated = (listOf(item) + searchHistory.filterNot { it.name == item.name && it.latitude == item.latitude }).take(10) + searchHistory = updated + saveSearchHistory(updated) + } + + fun removeSearchHistory(item: SearchResult) { + val updated = searchHistory.filterNot { it.name == item.name && it.latitude == item.latitude } + searchHistory = updated + saveSearchHistory(updated) + } + + fun clearSearchHistory() { + searchHistory = emptyList() + saveSearchHistory(emptyList()) + } + + private fun saveSearchHistory(list: List) { + val array = org.json.JSONArray() + for (item in list) { + val obj = org.json.JSONObject().apply { + put("name", item.name) + put("address", item.address) + put("lat", item.latitude) + put("lng", item.longitude) + } + array.put(obj) + } + prefs.edit().putString(KEY_SEARCH_HISTORY, array.toString()).apply() + } + + private fun parseSearchHistory(jsonStr: String): List { + return try { + val array = org.json.JSONArray(jsonStr) + val list = mutableListOf() + for (i in 0 until array.length()) { + val obj = array.getJSONObject(i) + list.add( + SearchResult( + name = obj.getString("name"), + address = obj.optString("address"), + latitude = obj.getDouble("lat"), + longitude = obj.getDouble("lng") + ) + ) + } + list + } catch (_: Exception) { + emptyList() + } + } + + fun addFavorite(item: FavoriteItem) { + val updated = listOf(item) + favorites.filterNot { it.id == item.id } + favorites = updated + saveFavorites(updated) + } + + fun removeFavorite(id: String) { + val updated = favorites.filterNot { it.id == id } + favorites = updated + saveFavorites(updated) + } + + fun updateFavorite(item: FavoriteItem) { + val updated = favorites.map { if (it.id == item.id) item else it } + favorites = updated + saveFavorites(updated) + } + + fun moveFavorite(fromIndex: Int, toIndex: Int) { + if (fromIndex == toIndex || fromIndex !in favorites.indices || toIndex !in favorites.indices) return + val list = favorites.toMutableList() + val item = list.removeAt(fromIndex) + list.add(toIndex, item) + favorites = list + saveFavorites(list) + } + + private fun saveFavorites(list: List) { + val array = org.json.JSONArray() + for (item in list) { + val obj = org.json.JSONObject().apply { + put("id", item.id) + put("name", item.name) + put("address", item.address) + put("lat", item.latitude) + put("lng", item.longitude) + put("timestamp", item.timestamp) + } + array.put(obj) + } + prefs.edit().putString(KEY_FAVORITES, array.toString()).apply() + } + + private fun parseFavorites(jsonStr: String): List { + return try { + val array = org.json.JSONArray(jsonStr) + val list = mutableListOf() + for (i in 0 until array.length()) { + val obj = array.getJSONObject(i) + list.add( + FavoriteItem( + id = obj.optString("id", java.util.UUID.randomUUID().toString()), + name = obj.getString("name"), + address = obj.optString("address", ""), + latitude = obj.getDouble("lat"), + longitude = obj.getDouble("lng"), + timestamp = obj.optLong("timestamp", System.currentTimeMillis()) + ) + ) + } + list + } catch (_: Exception) { + emptyList() + } + } + + fun updateSearchProvider(provider: SearchProvider) { + searchProvider = provider + prefs.edit().putString(KEY_SEARCH_PROVIDER, provider.id).apply() + } + + fun updateAmapApiKey(key: String) { + amapApiKey = key.trim() + prefs.edit().putString(KEY_AMAP_API_KEY, amapApiKey).apply() + } + + fun updateBaiduApiKey(key: String) { + baiduApiKey = key.trim() + prefs.edit().putString(KEY_BAIDU_API_KEY, baiduApiKey).apply() + } + + fun getCurrentProviderKey(): String { + return when (searchProvider) { + SearchProvider.AMAP -> amapApiKey + SearchProvider.BAIDU -> baiduApiKey + else -> "" + } + } + + fun updateCurrentProviderKey(key: String) { + when (searchProvider) { + SearchProvider.AMAP -> updateAmapApiKey(key) + SearchProvider.BAIDU -> updateBaiduApiKey(key) + else -> Unit + } + } + + fun updateAppMockMode(mode: AppMockMode) { + appMockMode = mode + prefs.edit().putString(KEY_APP_MOCK_MODE, mode.name).apply() + } + + fun updateWhitelistApps(packages: Set) { + whitelistApps = packages + savePackageSet(KEY_WHITELIST_APPS, packages) + } + + fun toggleWhitelistApp(packageName: String) { + val updated = if (whitelistApps.contains(packageName)) { + whitelistApps - packageName + } else { + whitelistApps + packageName + } + updateWhitelistApps(updated) + } + + fun updateBlacklistApps(packages: Set) { + blacklistApps = packages + savePackageSet(KEY_BLACKLIST_APPS, packages) + } + + fun toggleBlacklistApp(packageName: String) { + val updated = if (blacklistApps.contains(packageName)) { + blacklistApps - packageName + } else { + blacklistApps + packageName + } + updateBlacklistApps(updated) + } + + private fun savePackageSet(key: String, packages: Set) { + val array = org.json.JSONArray() + for (pkg in packages) { + array.put(pkg) + } + prefs.edit().putString(key, array.toString()).apply() + } + + private fun parsePackageSet(jsonStr: String): Set { + return try { + val array = org.json.JSONArray(jsonStr) + val set = mutableSetOf() + for (i in 0 until array.length()) { + set.add(array.getString(i)) + } + set + } catch (_: Exception) { + emptySet() + } + } + + fun updateJitterEnabled(enabled: Boolean) { + isJitterEnabled = enabled + prefs.edit().putBoolean(KEY_ENABLE_JITTER, enabled).apply() + } + + fun updateGnssSimulationEnabled(enabled: Boolean) { + isGnssSimulationEnabled = enabled + prefs.edit().putBoolean(KEY_ENABLE_GNSS_SIMULATION, enabled).apply() + } + + fun updateNetworkCamouflageEnabled(enabled: Boolean) { + isNetworkCamouflageEnabled = enabled + prefs.edit().putBoolean(KEY_ENABLE_NETWORK_CAMOUFLAGE, enabled).apply() + } + + fun updateSensorSimulationEnabled(enabled: Boolean) { + isSensorSimulationEnabled = enabled + prefs.edit().putBoolean(KEY_ENABLE_SENSOR_SIMULATION, enabled).apply() + } + + fun updateStealthEnabled(enabled: Boolean) { + isStealthEnabled = enabled + prefs.edit().putBoolean(KEY_ENABLE_STEALTH, enabled).apply() + } + + fun updateDevCamouflageEnabled(enabled: Boolean) { + isDevCamouflageEnabled = enabled + prefs.edit().putBoolean(KEY_ENABLE_DEV_CAMOUFLAGE, enabled).apply() + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/hook/HookEntry.kt b/app/src/main/java/com/lzxnone/openloc/hook/HookEntry.kt new file mode 100644 index 0000000..5feac65 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/hook/HookEntry.kt @@ -0,0 +1,107 @@ +package com.lzxnone.openloc.hook + +import android.app.Application +import android.content.Context +import com.lzxnone.openloc.hook.interceptor.AntiDetectionHook +import com.lzxnone.openloc.hook.interceptor.GnssHook +import com.lzxnone.openloc.hook.interceptor.LocationHook +import com.lzxnone.openloc.hook.interceptor.NetworkLocationHook +import com.lzxnone.openloc.hook.interceptor.SensorHook +import com.lzxnone.openloc.hook.system.SystemServerHook +import de.robv.android.xposed.IXposedHookLoadPackage +import de.robv.android.xposed.XC_MethodHook +import de.robv.android.xposed.XC_MethodReplacement +import de.robv.android.xposed.XposedBridge +import de.robv.android.xposed.XposedHelpers +import de.robv.android.xposed.callbacks.XC_LoadPackage + +/** + * Xposed / LSPosed 统一 Hook 分发主入口 + */ +class HookEntry : IXposedHookLoadPackage { + + @Volatile + private var appContext: Context? = null + + override fun handleLoadPackage(lpparam: XC_LoadPackage.LoadPackageParam) { + // 1. 系统级全局拦截:如果是 Android 系统框架 (system_server) + // 只要在 LSPosed 中勾选了【Android 系统 (android)】,整机所有应用全部享受全局定位拦截! + if (lpparam.packageName == "android") { + SystemServerHook.hook(lpparam.classLoader) + return + } + + // 过滤系统 UI 进程 + if (lpparam.packageName == "com.android.systemui") { + return + } + + // 2. 如果加载的是本应用自身,Hook 激活判定桩使其恒返回 true + if (lpparam.packageName == MODULE_PACKAGE_NAME) { + hookSelfActiveStatus(lpparam.classLoader) + return + } + + // 3. 注入目标应用进程(客户端双重兜底):挂载 Context 并启动深度拦截链路(WiFi/基站/NMEA) + initTargetHooks(lpparam) + } + + /** + * Hook 本身应用的 HookStatus.isModuleActive(),令其返回 true + */ + private fun hookSelfActiveStatus(classLoader: ClassLoader) { + try { + XposedHelpers.findAndHookMethod( + "com.lzxnone.openloc.core.util.HookStatus", + classLoader, + "isModuleActive", + object : XC_MethodReplacement() { + override fun replaceHookedMethod(param: MethodHookParam?): Any { + return true + } + } + ) + XposedBridge.log("[OpenLoc] Hooked isModuleActive -> true successfully") + } catch (t: Throwable) { + XposedBridge.log("[OpenLoc] Failed to hook isModuleActive: ${t.message}") + } + } + + /** + * 目标应用进程初始化与全链路 Hook 挂载 + */ + private fun initTargetHooks(lpparam: XC_LoadPackage.LoadPackageParam) { + try { + val contextProvider = { appContext } + + // 监听 Application 启动以安全捕获应用级 Context + XposedHelpers.findAndHookMethod( + Application::class.java, + "attach", + Context::class.java, + object : XC_MethodHook() { + override fun afterHookedMethod(param: MethodHookParam) { + if (appContext == null) { + appContext = param.args[0] as? Context + } + } + } + ) + + // 挂载定位与防检测核心拦截线 + LocationHook.hook(lpparam.classLoader, contextProvider) + NetworkLocationHook.hook(lpparam.classLoader, contextProvider) + GnssHook.hook(lpparam.classLoader, contextProvider) + SensorHook.hook(lpparam.classLoader, contextProvider) + AntiDetectionHook.hook(lpparam.classLoader, contextProvider) + + XposedBridge.log("[OpenLoc] Injected target hooks for: ${lpparam.packageName}") + } catch (t: Throwable) { + XposedBridge.log("[OpenLoc] Error initializing target hooks for ${lpparam.packageName}: ${t.message}") + } + } + + companion object { + const val MODULE_PACKAGE_NAME = "com.lzxnone.openloc" + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/hook/interceptor/AntiDetectionHook.kt b/app/src/main/java/com/lzxnone/openloc/hook/interceptor/AntiDetectionHook.kt new file mode 100644 index 0000000..47ea55d --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/hook/interceptor/AntiDetectionHook.kt @@ -0,0 +1,280 @@ +package com.lzxnone.openloc.hook.interceptor + +import android.content.ContentResolver +import android.content.Context +import android.content.pm.ApplicationInfo +import android.content.pm.PackageInfo +import android.content.pm.PackageManager +import com.lzxnone.openloc.hook.ipc.ConfigFetcher +import de.robv.android.xposed.XC_MethodHook +import de.robv.android.xposed.XposedBridge +import de.robv.android.xposed.XposedHelpers + +/** + * 防检测与隐匿拦截器 + * 1. 堆栈清洗:过滤 Xposed / LSPosed / OpenLoc 相关调用栈帧 + * 2. 模块包名自隐匿:隐藏 com.lzxnone.openloc,防止被目标应用通过 PackageManager 探测 + * 3. 开发者选项与模拟位置状态伪装:伪装开发者模式、USB调试、模拟位置为未开启 + */ +object AntiDetectionHook { + + private val isSanitizingStack = ThreadLocal.withInitial { false } + + private val CAMOUFLAGE_SETTINGS_KEYS = setOf( + "development_settings_enabled", + "adb_enabled", + "mock_location", + "ALLOW_MOCK_LOCATION" + ) + + private const val MODULE_PACKAGE_NAME = "com.lzxnone.openloc" + + fun hook(classLoader: ClassLoader, contextProvider: () -> Context?) { + hookStackTrace(contextProvider) + hookPackageManager(classLoader, contextProvider) + hookSettingsCamouflage(classLoader, contextProvider) + } + + /** + * 1. 调用栈隐匿:对 Throwable 与 Thread 的 getStackTrace 进行清洗 + */ + private fun hookStackTrace(contextProvider: () -> Context?) { + try { + // Hook Throwable.getStackTrace() + XposedHelpers.findAndHookMethod( + Throwable::class.java, + "getStackTrace", + object : XC_MethodHook() { + override fun afterHookedMethod(param: MethodHookParam) { + if (isSanitizingStack.get() == true) return + try { + isSanitizingStack.set(true) + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (!config.shouldMock(ctx.packageName) || !config.isStealthEnabled) return + + @Suppress("UNCHECKED_CAST") + val originalElements = param.result as? Array ?: return + var hasForbidden = false + for (elem in originalElements) { + if (isForbiddenClassName(elem.className)) { + hasForbidden = true + break + } + } + if (hasForbidden) { + param.result = originalElements.filter { !isForbiddenClassName(it.className) }.toTypedArray() + } + } finally { + isSanitizingStack.set(false) + } + } + } + ) + + // Hook Thread.getStackTrace() + XposedHelpers.findAndHookMethod( + Thread::class.java, + "getStackTrace", + object : XC_MethodHook() { + override fun afterHookedMethod(param: MethodHookParam) { + if (isSanitizingStack.get() == true) return + try { + isSanitizingStack.set(true) + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (!config.shouldMock(ctx.packageName) || !config.isStealthEnabled) return + + @Suppress("UNCHECKED_CAST") + val originalElements = param.result as? Array ?: return + var hasForbidden = false + for (elem in originalElements) { + if (isForbiddenClassName(elem.className)) { + hasForbidden = true + break + } + } + if (hasForbidden) { + param.result = originalElements.filter { !isForbiddenClassName(it.className) }.toTypedArray() + } + } finally { + isSanitizingStack.set(false) + } + } + } + ) + } catch (t: Throwable) { + XposedBridge.log("[OpenLoc] hookStackTrace error: ${t.message}") + } + } + + private fun isForbiddenClassName(className: String): Boolean { + val lower = className.lowercase() + return lower.contains("openloc") || + lower.contains("xposed") || + lower.contains("lsposed") || + lower.contains("sandhook") || + lower.contains("edxposed") + } + + /** + * 2. PackageManager 模块自隐匿 + */ + private fun hookPackageManager(classLoader: ClassLoader, contextProvider: () -> Context?) { + val pmClasses = listOf( + "android.app.ApplicationPackageManager", + "android.content.pm.PackageManager" + ) + + for (pmClassName in pmClasses) { + val pmClass = try { + XposedHelpers.findClass(pmClassName, classLoader) + } catch (_: Throwable) { + null + } ?: continue + + for (method in pmClass.declaredMethods) { + when (method.name) { + "getPackageInfo" -> { + try { + XposedBridge.hookMethod(method, object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val pkgName = param.args.firstOrNull { it is String } as? String ?: return + if (pkgName == MODULE_PACKAGE_NAME) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (config.shouldMock(ctx.packageName) && config.isStealthEnabled) { + param.throwable = PackageManager.NameNotFoundException(pkgName) + } + } + } + }) + } catch (_: Throwable) {} + } + "getApplicationInfo" -> { + try { + XposedBridge.hookMethod(method, object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val pkgName = param.args.firstOrNull { it is String } as? String ?: return + if (pkgName == MODULE_PACKAGE_NAME) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (config.shouldMock(ctx.packageName) && config.isStealthEnabled) { + param.throwable = PackageManager.NameNotFoundException(pkgName) + } + } + } + }) + } catch (_: Throwable) {} + } + "getInstalledPackages" -> { + try { + XposedBridge.hookMethod(method, object : XC_MethodHook() { + override fun afterHookedMethod(param: MethodHookParam) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (!config.shouldMock(ctx.packageName) || !config.isStealthEnabled) return + + val list = param.result as? List<*> ?: return + val filtered = list.filter { + (it as? PackageInfo)?.packageName != MODULE_PACKAGE_NAME + } + param.result = filtered + } + }) + } catch (_: Throwable) {} + } + "getInstalledApplications" -> { + try { + XposedBridge.hookMethod(method, object : XC_MethodHook() { + override fun afterHookedMethod(param: MethodHookParam) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (!config.shouldMock(ctx.packageName) || !config.isStealthEnabled) return + + val list = param.result as? List<*> ?: return + val filtered = list.filter { + (it as? ApplicationInfo)?.packageName != MODULE_PACKAGE_NAME + } + param.result = filtered + } + }) + } catch (_: Throwable) {} + } + } + } + } + } + + /** + * 3. 开发者选项与系统模拟位置状态伪装 (Settings.Secure & Settings.Global) + */ + private fun hookSettingsCamouflage(classLoader: ClassLoader, contextProvider: () -> Context?) { + val settingsClasses = listOf( + "android.provider.Settings\$Secure", + "android.provider.Settings\$Global" + ) + + for (className in settingsClasses) { + val settingsClass = try { + XposedHelpers.findClass(className, classLoader) + } catch (_: Throwable) { + null + } ?: continue + + for (method in settingsClass.declaredMethods) { + val methodName = method.name + when (methodName) { + "getString" -> { + try { + XposedBridge.hookMethod(method, object : XC_MethodHook() { + override fun afterHookedMethod(param: MethodHookParam) { + val key = param.args.firstOrNull { it is String } as? String ?: return + if (CAMOUFLAGE_SETTINGS_KEYS.contains(key)) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (config.shouldMock(ctx.packageName) && config.isDevCamouflageEnabled) { + param.result = "0" + } + } + } + }) + } catch (_: Throwable) {} + } + "getInt" -> { + try { + XposedBridge.hookMethod(method, object : XC_MethodHook() { + override fun afterHookedMethod(param: MethodHookParam) { + val key = param.args.firstOrNull { it is String } as? String ?: return + if (CAMOUFLAGE_SETTINGS_KEYS.contains(key)) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (config.shouldMock(ctx.packageName) && config.isDevCamouflageEnabled) { + param.result = 0 + } + } + } + }) + } catch (_: Throwable) {} + } + "getLong" -> { + try { + XposedBridge.hookMethod(method, object : XC_MethodHook() { + override fun afterHookedMethod(param: MethodHookParam) { + val key = param.args.firstOrNull { it is String } as? String ?: return + if (CAMOUFLAGE_SETTINGS_KEYS.contains(key)) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (config.shouldMock(ctx.packageName) && config.isDevCamouflageEnabled) { + param.result = 0L + } + } + } + }) + } catch (_: Throwable) {} + } + } + } + } + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/hook/interceptor/GnssHook.kt b/app/src/main/java/com/lzxnone/openloc/hook/interceptor/GnssHook.kt new file mode 100644 index 0000000..436204a --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/hook/interceptor/GnssHook.kt @@ -0,0 +1,318 @@ +@file:Suppress("DEPRECATION") + +package com.lzxnone.openloc.hook.interceptor + +import android.content.Context +import android.location.GnssStatus +import android.location.GpsStatus +import android.location.LocationManager +import android.location.OnNmeaMessageListener +import android.os.Handler +import android.os.Looper +import com.lzxnone.openloc.hook.ipc.ConfigFetcher +import com.lzxnone.openloc.hook.util.LocationSimulator +import com.lzxnone.openloc.hook.util.VirtualGnssEngine +import de.robv.android.xposed.XC_MethodHook +import de.robv.android.xposed.XposedBridge +import de.robv.android.xposed.XposedHelpers +import java.util.Collections +import java.util.WeakHashMap + +/** + * 全真多星座 GNSS 卫星与 NMEA 报文拦截器 + * + * 1. 深度拦截 GnssStatus.Callback,构造注入 26 颗多星座卫星(GPS、北斗、GLONASS、Galileo) + * 2. 维持 1Hz 卫星心跳分发,室内/无真实信号下仍持续稳定分发有效卫星解 + * 3. 拦截 NMEA 监听器,全量伪造 $GNGGA、$GNRMC、$GNGSA、$BDGSA、$GPGSV、$BDGSV、$GLGSV + * 4. 兼容旧版 GpsStatus.Listener 探测 + */ +object GnssHook { + + private val isDeliveringNmea = ThreadLocal.withInitial { false } + private val activeGnssCallbacks = Collections.newSetFromMap(WeakHashMap()) + private val activeGpsListeners = Collections.newSetFromMap(WeakHashMap()) + + @Volatile + private var isTickerStarted = false + private var mainHandler: Handler? = null + + fun hook(classLoader: ClassLoader, contextProvider: () -> Context?) { + hookNmeaListener(contextProvider) + hookGnssStatusCallbacks(classLoader, contextProvider) + hookGpsStatusLegacy(contextProvider) + } + + /** + * 1. 拦截并分发全真 NMEA-0183 多星座报文阵列 + */ + private fun hookNmeaListener(contextProvider: () -> Context?) { + try { + val methods = LocationManager::class.java.declaredMethods + for (method in methods) { + if (method.name == "addNmeaListener") { + val paramTypes = method.parameterTypes + val listenerIndex = paramTypes.indexOfFirst { + OnNmeaMessageListener::class.java.isAssignableFrom(it) + } + + if (listenerIndex != -1) { + try { + XposedBridge.hookMethod(method, object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val originalListener = param.args[listenerIndex] as? OnNmeaMessageListener ?: return + hookNmeaCallback(originalListener, contextProvider) + } + }) + } catch (_: Throwable) {} + } + } + } + } catch (t: Throwable) { + XposedBridge.log("[OpenLoc] hookNmeaListener error: ${t.message}") + } + } + + private val hookedNmeaClasses = mutableSetOf() + + private fun hookNmeaCallback(listener: OnNmeaMessageListener, contextProvider: () -> Context?) { + val clazz = listener.javaClass + val className = clazz.name + if (hookedNmeaClasses.contains(className)) return + hookedNmeaClasses.add(className) + + try { + XposedHelpers.findAndHookMethod( + clazz, + "onNmeaMessage", + String::class.java, + Long::class.javaPrimitiveType, + object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + if (isDeliveringNmea.get() == true) return + + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (!config.shouldMock(ctx.packageName) || !config.isGnssSimulationEnabled) return + + val rawMessage = param.args[0] as? String ?: return + val timestamp = param.args[1] as? Long ?: System.currentTimeMillis() + + // 当系统开始触发 NMEA 时,动态替换并批量补齐多星座全套报文 + if (rawMessage.startsWith("\$GP") || rawMessage.startsWith("\$GN") || rawMessage.startsWith("\$BD")) { + val (curLat, curLng) = LocationSimulator.getSimulatedCoordinates( + config.latitude, + config.longitude, + config.isJitterEnabled + ) + + val fullNmeaList = VirtualGnssEngine.generateFullNmeaSequence(curLat, curLng, timestamp) + if (fullNmeaList.isNotEmpty()) { + // 替换当前句为第一句($GNGGA) + param.args[0] = fullNmeaList[0] + + // 补发剩余语句 ($GNRMC, $GNGSA, $BDGSA, $GPGSV...) + try { + isDeliveringNmea.set(true) + val targetListener = param.thisObject as? OnNmeaMessageListener + if (targetListener != null) { + for (i in 1 until fullNmeaList.size) { + targetListener.onNmeaMessage(fullNmeaList[i], timestamp) + } + } + } finally { + isDeliveringNmea.set(false) + } + } + } + } + } + ) + } catch (_: Throwable) {} + } + + /** + * 2. 深度拦截 GnssStatus 回调并维持 1Hz 卫星心跳 + */ + private fun hookGnssStatusCallbacks(classLoader: ClassLoader, contextProvider: () -> Context?) { + try { + // (1) 拦截 LocationManager.registerGnssStatusCallback 各重载 + val methods = LocationManager::class.java.declaredMethods + for (method in methods) { + if (method.name == "registerGnssStatusCallback") { + try { + XposedBridge.hookMethod(method, object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val callback = param.args.firstOrNull { it is GnssStatus.Callback } as? GnssStatus.Callback ?: return + synchronized(activeGnssCallbacks) { + activeGnssCallbacks.add(callback) + } + ensureTickerStarted(contextProvider) + hookSingleGnssCallbackClass(callback.javaClass, contextProvider) + } + }) + } catch (_: Throwable) {} + } else if (method.name == "unregisterGnssStatusCallback") { + try { + XposedBridge.hookMethod(method, object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val callback = param.args.firstOrNull { it is GnssStatus.Callback } as? GnssStatus.Callback ?: return + synchronized(activeGnssCallbacks) { + activeGnssCallbacks.remove(callback) + } + } + }) + } catch (_: Throwable) {} + } + } + } catch (t: Throwable) { + XposedBridge.log("[OpenLoc] hookGnssStatusCallbacks error: ${t.message}") + } + } + + private val hookedGnssCallbackClasses = mutableSetOf() + + private fun hookSingleGnssCallbackClass(clazz: Class<*>, contextProvider: () -> Context?) { + val className = clazz.name + if (hookedGnssCallbackClasses.contains(className)) return + hookedGnssCallbackClasses.add(className) + + try { + // Hook onSatelliteStatusChanged(GnssStatus) + XposedHelpers.findAndHookMethod( + clazz, + "onSatelliteStatusChanged", + GnssStatus::class.java, + object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (!config.shouldMock(ctx.packageName) || !config.isGnssSimulationEnabled) return + + val fakeStatus = VirtualGnssEngine.createGnssStatus() + if (fakeStatus != null) { + param.args[0] = fakeStatus + } + } + } + ) + } catch (_: Throwable) {} + } + + /** + * 3. 启动 1Hz 定时卫星仿真分发调度(针对无真实卫星信号、室内等环境兜底) + */ + private fun ensureTickerStarted(contextProvider: () -> Context?) { + if (isTickerStarted) return + synchronized(this) { + if (isTickerStarted) return + isTickerStarted = true + + if (mainHandler == null) { + try { + mainHandler = Handler(Looper.getMainLooper()) + } catch (_: Throwable) {} + } + + mainHandler?.post(object : Runnable { + override fun run() { + try { + dispatchSimulatedGnssTick(contextProvider) + } catch (_: Throwable) {} + mainHandler?.postDelayed(this, 1000L) // 1 秒刷新一次 + } + }) + } + } + + private val notifiedFirstFixSet = Collections.newSetFromMap(WeakHashMap()) + + private fun dispatchSimulatedGnssTick(contextProvider: () -> Context?) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (!config.shouldMock(ctx.packageName) || !config.isGnssSimulationEnabled) return + + val fakeStatus = VirtualGnssEngine.createGnssStatus() ?: return + + val callbacksSnapshot = synchronized(activeGnssCallbacks) { + activeGnssCallbacks.toList() + } + + for (cb in callbacksSnapshot) { + try { + if (!notifiedFirstFixSet.contains(cb)) { + notifiedFirstFixSet.add(cb) + cb.onStarted() + cb.onFirstFix(1200) // 1.2s 极速逼真定位时间 + } + cb.onSatelliteStatusChanged(fakeStatus) + } catch (_: Throwable) {} + } + + // 兼容旧版 GpsStatus + val listenersSnapshot = synchronized(activeGpsListeners) { + activeGpsListeners.toList() + } + for (listener in listenersSnapshot) { + try { + listener.onGpsStatusChanged(GpsStatus.GPS_EVENT_SATELLITE_STATUS) + } catch (_: Throwable) {} + } + } + + /** + * 4. 兼容老版本 SDK 的 GpsStatus.Listener + */ + private fun hookGpsStatusLegacy(contextProvider: () -> Context?) { + try { + // Hook addGpsStatusListener + XposedHelpers.findAndHookMethod( + LocationManager::class.java, + "addGpsStatusListener", + GpsStatus.Listener::class.java, + object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val listener = param.args[0] as? GpsStatus.Listener ?: return + synchronized(activeGpsListeners) { + activeGpsListeners.add(listener) + } + ensureTickerStarted(contextProvider) + } + } + ) + + // Hook removeGpsStatusListener + XposedHelpers.findAndHookMethod( + LocationManager::class.java, + "removeGpsStatusListener", + GpsStatus.Listener::class.java, + object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val listener = param.args[0] as? GpsStatus.Listener ?: return + synchronized(activeGpsListeners) { + activeGpsListeners.remove(listener) + } + } + } + ) + + // Hook getGpsStatus(GpsStatus status) + XposedHelpers.findAndHookMethod( + LocationManager::class.java, + "getGpsStatus", + GpsStatus::class.java, + object : XC_MethodHook() { + override fun afterHookedMethod(param: MethodHookParam) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (!config.shouldMock(ctx.packageName) || !config.isGnssSimulationEnabled) return + + val status = (param.result as? GpsStatus) ?: (param.args[0] as? GpsStatus) ?: return + try { + XposedHelpers.setIntField(status, "mTimeToFirstFix", 1200) + } catch (_: Throwable) {} + } + } + ) + } catch (_: Throwable) {} + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/hook/interceptor/LocationHook.kt b/app/src/main/java/com/lzxnone/openloc/hook/interceptor/LocationHook.kt new file mode 100644 index 0000000..adf08a8 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/hook/interceptor/LocationHook.kt @@ -0,0 +1,226 @@ +package com.lzxnone.openloc.hook.interceptor + +import android.content.Context +import android.location.Location +import android.location.LocationListener +import android.location.LocationManager +import android.os.Build +import com.lzxnone.openloc.hook.ipc.ConfigFetcher +import com.lzxnone.openloc.hook.util.LocationSimulator +import de.robv.android.xposed.XC_MethodHook +import de.robv.android.xposed.XC_MethodReplacement +import de.robv.android.xposed.XposedBridge +import de.robv.android.xposed.XposedHelpers +import java.lang.reflect.Proxy + +/** + * 原生定位服务 LocationManager 与 Location 实体拦截器 + */ +object LocationHook { + + fun hook(classLoader: ClassLoader, contextProvider: () -> Context?) { + hookLocationEntity() + hookLocationManager(classLoader, contextProvider) + } + + /** + * 1. 拦截 Location 实体类中的 Mock 判定方法 + */ + private fun hookLocationEntity() { + try { + // Hook isFromMockProvider 恒返回 false + XposedHelpers.findAndHookMethod( + Location::class.java, + "isFromMockProvider", + object : XC_MethodReplacement() { + override fun replaceHookedMethod(param: MethodHookParam?): Any { + return false + } + } + ) + + // Android 12 (API 31)+ isMock() 恒返回 false + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + try { + XposedHelpers.findAndHookMethod( + Location::class.java, + "isMock", + object : XC_MethodReplacement() { + override fun replaceHookedMethod(param: MethodHookParam?): Any { + return false + } + } + ) + } catch (_: Throwable) {} + } + } catch (t: Throwable) { + XposedBridge.log("[OpenLoc] hookLocationEntity failed: ${t.message}") + } + } + + /** + * 2. 拦截 LocationManager 的核心定位获取方法 + */ + private fun hookLocationManager(classLoader: ClassLoader, contextProvider: () -> Context?) { + try { + // (1) 拦截 getLastKnownLocation + XposedHelpers.findAndHookMethod( + LocationManager::class.java, + "getLastKnownLocation", + String::class.java, + object : XC_MethodHook() { + override fun afterHookedMethod(param: MethodHookParam) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (!config.shouldMock(ctx.packageName)) return + + val provider = param.args[0] as? String ?: LocationManager.GPS_PROVIDER + param.result = LocationSimulator.createMockLocation( + latitude = config.latitude, + longitude = config.longitude, + provider = provider, + isJitterEnabled = config.isJitterEnabled + ) + } + } + ) + + // (2) 拦截 requestLocationUpdates 各重载中传入的 LocationListener + val methods = LocationManager::class.java.declaredMethods + for (method in methods) { + if (method.name == "requestLocationUpdates") { + val paramTypes = method.parameterTypes + val listenerIndex = paramTypes.indexOfFirst { + LocationListener::class.java.isAssignableFrom(it) + } + + if (listenerIndex != -1) { + try { + XposedBridge.hookMethod(method, object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val originalListener = param.args[listenerIndex] as? LocationListener ?: return + // 拦截回调类并 Hook 其 onLocationChanged + hookListenerClass(originalListener.javaClass, contextProvider) + } + }) + } catch (_: Throwable) {} + } + } + } + + // (3) Android 12+ 拦截 getCurrentLocation 异步单次定位 + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + hookGetCurrentLocation(contextProvider) + } + + } catch (t: Throwable) { + XposedBridge.log("[OpenLoc] hookLocationManager failed: ${t.message}") + } + } + + /** + * Hook 具体应用实现的 LocationListener.onLocationChanged + */ + private val hookedListenerClasses = mutableSetOf() + + private fun hookListenerClass(clazz: Class<*>, contextProvider: () -> Context?) { + val className = clazz.name + if (hookedListenerClasses.contains(className)) return + hookedListenerClasses.add(className) + + try { + // Hook onLocationChanged(Location) + XposedHelpers.findAndHookMethod( + clazz, + "onLocationChanged", + Location::class.java, + object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (!config.shouldMock(ctx.packageName)) return + + val location = param.args[0] as? Location + if (location != null) { + LocationSimulator.applyMockData(location, config.latitude, config.longitude, config.isJitterEnabled) + } else { + param.args[0] = LocationSimulator.createMockLocation( + config.latitude, + config.longitude, + isJitterEnabled = config.isJitterEnabled + ) + } + } + } + ) + } catch (_: Throwable) {} + + // Android 14 (API 34)+ 新增 onLocationChanged(List) + try { + XposedHelpers.findAndHookMethod( + clazz, + "onLocationChanged", + List::class.java, + object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (!config.shouldMock(ctx.packageName)) return + + @Suppress("UNCHECKED_CAST") + val list = param.args[0] as? List ?: return + for (loc in list) { + LocationSimulator.applyMockData(loc, config.latitude, config.longitude, config.isJitterEnabled) + } + } + } + ) + } catch (_: Throwable) {} + } + + /** + * Android 11+ / 12+ 单次定位 getCurrentLocation 拦截 + */ + private fun hookGetCurrentLocation(contextProvider: () -> Context?) { + val methods = LocationManager::class.java.declaredMethods + for (method in methods) { + if (method.name == "getCurrentLocation") { + try { + XposedBridge.hookMethod(method, object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (!config.shouldMock(ctx.packageName)) return + + // Consumer 通常位于最后一位 + val lastIndex = param.args.size - 1 + if (lastIndex >= 0) { + val originalConsumer = param.args[lastIndex] ?: return + val consumerInterface = originalConsumer.javaClass.interfaces.firstOrNull { + it.name == "java.util.function.Consumer" + } ?: return + + val proxy = Proxy.newProxyInstance( + consumerInterface.classLoader, + arrayOf(consumerInterface) + ) { _, m, args -> + if (m.name == "accept" && args != null && args.isNotEmpty()) { + val mockLoc = LocationSimulator.createMockLocation( + config.latitude, + config.longitude, + isJitterEnabled = config.isJitterEnabled + ) + m.invoke(originalConsumer, mockLoc) + } else { + m.invoke(originalConsumer, *(args ?: emptyArray())) + } + } + param.args[lastIndex] = proxy + } + } + }) + } catch (_: Throwable) {} + } + } + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/hook/interceptor/NetworkLocationHook.kt b/app/src/main/java/com/lzxnone/openloc/hook/interceptor/NetworkLocationHook.kt new file mode 100644 index 0000000..9c7f628 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/hook/interceptor/NetworkLocationHook.kt @@ -0,0 +1,242 @@ +@file:Suppress("DEPRECATION") + +package com.lzxnone.openloc.hook.interceptor + +import android.content.Context +import android.net.wifi.ScanResult +import android.net.wifi.WifiInfo +import android.net.wifi.WifiManager +import android.os.Build +import android.telephony.CellInfo +import android.telephony.CellLocation +import android.telephony.PhoneStateListener +import android.telephony.TelephonyManager +import com.lzxnone.openloc.hook.ipc.ConfigFetcher +import de.robv.android.xposed.XC_MethodHook +import de.robv.android.xposed.XposedBridge +import de.robv.android.xposed.XposedHelpers + +/** + * Wi-Fi 与基站深度防反查拦截器 + * + * 核心目标: + * 1. 拦截 WifiManager 扫描列表与连接 BSSID/MAC,阻断高德/腾讯/百度云端 Wi-Fi 指纹库反查真实物理位置 + * 2. 拦截 TelephonyManager 基站小区信息与位置监听,杜绝基站 LAC/CID 反查 + * 3. 拦截 PhoneStateListener 与 Android 12+ TelephonyCallback 实时小区回调 + */ +object NetworkLocationHook { + + private const val ANONYMOUS_MAC = "02:00:00:00:00:00" + + fun hook(classLoader: ClassLoader, contextProvider: () -> Context?) { + hookWifiManager(contextProvider) + hookTelephonyManager(classLoader, contextProvider) + } + + /** + * 1. 深度拦截 Wi-Fi 扫描结果与连接 BSSID / MAC + */ + private fun hookWifiManager(contextProvider: () -> Context?) { + try { + // (1) 拦截 WifiManager.getScanResults() + XposedHelpers.findAndHookMethod( + WifiManager::class.java, + "getScanResults", + object : XC_MethodHook() { + override fun afterHookedMethod(param: MethodHookParam) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) { + param.result = emptyList() + } + } + } + ) + + // (2) 拦截 WifiInfo.getBSSID() + XposedHelpers.findAndHookMethod( + WifiInfo::class.java, + "getBSSID", + object : XC_MethodHook() { + override fun afterHookedMethod(param: MethodHookParam) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) { + param.result = ANONYMOUS_MAC + } + } + } + ) + + // (3) 拦截 WifiInfo.getMacAddress() + XposedHelpers.findAndHookMethod( + WifiInfo::class.java, + "getMacAddress", + object : XC_MethodHook() { + override fun afterHookedMethod(param: MethodHookParam) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) { + param.result = ANONYMOUS_MAC + } + } + } + ) + } catch (t: Throwable) { + XposedBridge.log("[OpenLoc] hookWifiManager error: ${t.message}") + } + } + + /** + * 2. 深度拦截基站塔信息(MCC/MNC/LAC/CID)与实时监听器 + */ + private fun hookTelephonyManager(classLoader: ClassLoader, contextProvider: () -> Context?) { + try { + // (1) 拦截 getAllCellInfo + XposedHelpers.findAndHookMethod( + TelephonyManager::class.java, + "getAllCellInfo", + object : XC_MethodHook() { + override fun afterHookedMethod(param: MethodHookParam) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) { + param.result = emptyList() + } + } + } + ) + + // (2) 拦截 getCellLocation + XposedHelpers.findAndHookMethod( + TelephonyManager::class.java, + "getCellLocation", + object : XC_MethodHook() { + override fun afterHookedMethod(param: MethodHookParam) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) { + param.result = null + } + } + } + ) + + // (3) 拦截 TelephonyManager.listen(PhoneStateListener, int) + XposedHelpers.findAndHookMethod( + TelephonyManager::class.java, + "listen", + PhoneStateListener::class.java, + Int::class.javaPrimitiveType, + object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val listener = param.args[0] as? PhoneStateListener ?: return + hookPhoneStateListenerClass(listener.javaClass, contextProvider) + } + } + ) + + // (4) Android 12+ TelephonyCallback 拦截 + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + hookTelephonyCallback(classLoader, contextProvider) + } + } catch (t: Throwable) { + XposedBridge.log("[OpenLoc] hookTelephonyManager error: ${t.message}") + } + } + + private val hookedListenerClasses = mutableSetOf() + + private fun hookPhoneStateListenerClass(clazz: Class<*>, contextProvider: () -> Context?) { + val className = clazz.name + if (hookedListenerClasses.contains(className)) return + hookedListenerClasses.add(className) + + try { + // onCellLocationChanged + XposedHelpers.findAndHookMethod( + clazz, + "onCellLocationChanged", + CellLocation::class.java, + object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) { + param.args[0] = null + } + } + } + ) + } catch (_: Throwable) {} + + try { + // onCellInfoChanged + XposedHelpers.findAndHookMethod( + clazz, + "onCellInfoChanged", + List::class.java, + object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) { + param.args[0] = emptyList() + } + } + } + ) + } catch (_: Throwable) {} + } + + private fun hookTelephonyCallback(classLoader: ClassLoader, contextProvider: () -> Context?) { + try { + val callbackClass = XposedHelpers.findClass("android.telephony.TelephonyCallback", classLoader) + val methods = TelephonyManager::class.java.declaredMethods + for (method in methods) { + if (method.name == "registerTelephonyCallback") { + XposedBridge.hookMethod(method, object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val cb = param.args.firstOrNull { it != null && callbackClass.isAssignableFrom(it.javaClass) } ?: return + hookTelephonyCallbackClass(cb.javaClass, contextProvider) + } + }) + } + } + } catch (_: Throwable) {} + } + + private fun hookTelephonyCallbackClass(clazz: Class<*>, contextProvider: () -> Context?) { + val className = clazz.name + if (hookedListenerClasses.contains(className)) return + hookedListenerClasses.add(className) + + for (method in clazz.declaredMethods) { + if (method.name == "onCellInfoChanged") { + try { + XposedBridge.hookMethod(method, object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) { + param.args[0] = emptyList() + } + } + }) + } catch (_: Throwable) {} + } else if (method.name == "onCellLocationChanged") { + try { + XposedBridge.hookMethod(method, object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (config.shouldMock(ctx.packageName) && config.isNetworkCamouflageEnabled) { + param.args[0] = null + } + } + }) + } catch (_: Throwable) {} + } + } + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/hook/interceptor/SensorHook.kt b/app/src/main/java/com/lzxnone/openloc/hook/interceptor/SensorHook.kt new file mode 100644 index 0000000..60a240c --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/hook/interceptor/SensorHook.kt @@ -0,0 +1,108 @@ +package com.lzxnone.openloc.hook.interceptor + +import android.content.Context +import android.hardware.Sensor +import android.hardware.SensorEvent +import android.hardware.SensorEventListener +import android.hardware.SensorManager +import com.lzxnone.openloc.hook.ipc.ConfigFetcher +import de.robv.android.xposed.XC_MethodHook +import de.robv.android.xposed.XposedBridge +import de.robv.android.xposed.XposedHelpers +import kotlin.random.Random + +/** + * 物理动力学传感器协同与生理微颤拟真拦截器 + * + * 核心目标: + * 1. 拦截 SensorManager.registerListener,捕获应用注册的传感器监听器 + * 2. 针对加速度计 (TYPE_ACCELEROMETER) 与重力传感器 (TYPE_GRAVITY),动态注入人体手持特有的生物力学生理颤动(Physiological Tremor) + * 3. 防止加速度方差几乎为 0 导致被高精风控判定为“放置在桌面的静止刚体设备” + * 4. 针对陀螺仪 (TYPE_GYROSCOPE) 注入极细微的手持角速度扰动 + */ +object SensorHook { + + private val hookedListenerClasses = mutableSetOf() + + fun hook(classLoader: ClassLoader, contextProvider: () -> Context?) { + hookSensorManager(contextProvider) + } + + private fun hookSensorManager(contextProvider: () -> Context?) { + try { + val methods = SensorManager::class.java.declaredMethods + for (method in methods) { + if (method.name == "registerListener") { + val paramTypes = method.parameterTypes + val listenerIndex = paramTypes.indexOfFirst { + SensorEventListener::class.java.isAssignableFrom(it) + } + + if (listenerIndex != -1) { + try { + XposedBridge.hookMethod(method, object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val listener = param.args[listenerIndex] as? SensorEventListener ?: return + hookSensorEventListenerClass(listener.javaClass, contextProvider) + } + }) + } catch (_: Throwable) {} + } + } + } + } catch (t: Throwable) { + XposedBridge.log("[OpenLoc] hookSensorManager error: ${t.message}") + } + } + + private fun hookSensorEventListenerClass(clazz: Class<*>, contextProvider: () -> Context?) { + val className = clazz.name + if (hookedListenerClasses.contains(className)) return + hookedListenerClasses.add(className) + + try { + XposedHelpers.findAndHookMethod( + clazz, + "onSensorChanged", + SensorEvent::class.java, + object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val ctx = contextProvider() ?: return + val config = ConfigFetcher.getConfig(ctx) + if (!config.shouldMock(ctx.packageName) || !config.isSensorSimulationEnabled) return + + val event = param.args[0] as? SensorEvent ?: return + val sensorType = event.sensor?.type ?: return + + when (sensorType) { + // 1. 三轴加速度计(最核心):注入人体手持 ~0.05 m/s² 生理微颤 + Sensor.TYPE_ACCELEROMETER -> { + if (event.values.size >= 3) { + event.values[0] += (Random.nextFloat() - 0.5f) * 0.08f + event.values[1] += (Random.nextFloat() - 0.5f) * 0.08f + event.values[2] += (Random.nextFloat() - 0.5f) * 0.08f + } + } + // 2. 重力传感器:微量波动维持向量模长 + Sensor.TYPE_GRAVITY -> { + if (event.values.size >= 3) { + event.values[0] += (Random.nextFloat() - 0.5f) * 0.04f + event.values[1] += (Random.nextFloat() - 0.5f) * 0.04f + event.values[2] += (Random.nextFloat() - 0.5f) * 0.04f + } + } + // 3. 陀螺仪:手持微弱角速度波动 (rad/s) + Sensor.TYPE_GYROSCOPE -> { + if (event.values.size >= 3) { + event.values[0] += (Random.nextFloat() - 0.5f) * 0.015f + event.values[1] += (Random.nextFloat() - 0.5f) * 0.015f + event.values[2] += (Random.nextFloat() - 0.5f) * 0.015f + } + } + } + } + } + ) + } catch (_: Throwable) {} + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/hook/ipc/ConfigFetcher.kt b/app/src/main/java/com/lzxnone/openloc/hook/ipc/ConfigFetcher.kt new file mode 100644 index 0000000..5dd6f74 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/hook/ipc/ConfigFetcher.kt @@ -0,0 +1,92 @@ +package com.lzxnone.openloc.hook.ipc + +import android.content.Context +import android.net.Uri +import com.lzxnone.openloc.core.provider.ConfigContract +import com.lzxnone.openloc.hook.model.MockConfig +import de.robv.android.xposed.XposedBridge + +/** + * 跨进程配置拉取与缓存器(运行在目标宿主进程) + */ +object ConfigFetcher { + + private val PROVIDER_URI = Uri.parse(ConfigContract.CONTENT_URI) + + @Volatile + private var cachedConfig: MockConfig? = null + + @Volatile + private var lastFetchTime = 0L + + private const val CACHE_DURATION_MS = 1500L // 缓存 1.5 秒,保证即时性同时兼顾性能 + + /** + * 获取最新配置(带平滑缓存) + */ + fun getConfig(context: Context, force: Boolean = false): MockConfig { + val now = System.currentTimeMillis() + if (!force && cachedConfig != null && (now - lastFetchTime < CACHE_DURATION_MS)) { + return cachedConfig!! + } + + return try { + val bundle = context.contentResolver.call( + PROVIDER_URI, + ConfigContract.METHOD_GET_CONFIG, + null, + null + ) + + if (bundle != null) { + val mode = bundle.getString(ConfigContract.KEY_APP_MOCK_MODE, "GLOBAL") ?: "GLOBAL" + val whitelistJson = bundle.getString(ConfigContract.KEY_WHITELIST_APPS, "[]") ?: "[]" + val blacklistJson = bundle.getString(ConfigContract.KEY_BLACKLIST_APPS, "[]") ?: "[]" + + val isJitter = bundle.getBoolean(ConfigContract.KEY_ENABLE_JITTER, true) + val isGnss = bundle.getBoolean(ConfigContract.KEY_ENABLE_GNSS_SIMULATION, true) + val isNetwork = bundle.getBoolean(ConfigContract.KEY_ENABLE_NETWORK_CAMOUFLAGE, true) + val isSensor = bundle.getBoolean(ConfigContract.KEY_ENABLE_SENSOR_SIMULATION, true) + val isStealth = bundle.getBoolean(ConfigContract.KEY_ENABLE_STEALTH, true) + val isDevCamouflage = bundle.getBoolean(ConfigContract.KEY_ENABLE_DEV_CAMOUFLAGE, true) + + val config = MockConfig( + isEnabled = bundle.getBoolean(ConfigContract.KEY_ENABLED, false), + latitude = bundle.getDouble(ConfigContract.KEY_LATITUDE, 39.908722), + longitude = bundle.getDouble(ConfigContract.KEY_LONGITUDE, 116.397496), + locationName = bundle.getString(ConfigContract.KEY_LOCATION_NAME, ""), + mode = mode, + whitelist = parseSet(whitelistJson), + blacklist = parseSet(blacklistJson), + isJitterEnabled = isJitter, + isGnssSimulationEnabled = isGnss, + isNetworkCamouflageEnabled = isNetwork, + isSensorSimulationEnabled = isSensor, + isStealthEnabled = isStealth, + isDevCamouflageEnabled = isDevCamouflage + ) + cachedConfig = config + lastFetchTime = now + config + } else { + cachedConfig ?: MockConfig() + } + } catch (t: Throwable) { + // 在目标尚未完全就绪或权限受限时的静默容错 + cachedConfig ?: MockConfig() + } + } + + private fun parseSet(jsonStr: String): Set { + return try { + val array = org.json.JSONArray(jsonStr) + val set = mutableSetOf() + for (i in 0 until array.length()) { + set.add(array.getString(i)) + } + set + } catch (_: Throwable) { + emptySet() + } + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/hook/model/MockConfig.kt b/app/src/main/java/com/lzxnone/openloc/hook/model/MockConfig.kt new file mode 100644 index 0000000..40ec8b0 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/hook/model/MockConfig.kt @@ -0,0 +1,34 @@ +package com.lzxnone.openloc.hook.model + +import java.util.Locale + +/** + * 虚拟定位配置实体 + */ +data class MockConfig( + val isEnabled: Boolean = false, + val latitude: Double = 39.908722, + val longitude: Double = 116.397496, + val locationName: String = "", + val mode: String = "GLOBAL", + val whitelist: Set = emptySet(), + val blacklist: Set = emptySet(), + val isJitterEnabled: Boolean = true, + val isGnssSimulationEnabled: Boolean = true, + val isNetworkCamouflageEnabled: Boolean = true, + val isSensorSimulationEnabled: Boolean = true, + val isStealthEnabled: Boolean = true, + val isDevCamouflageEnabled: Boolean = true +) { + /** + * 判断指定应用包名是否应当生效虚拟定位 + */ + fun shouldMock(packageName: String): Boolean { + if (!isEnabled) return false + return when (mode.uppercase(Locale.ROOT)) { + "WHITELIST" -> whitelist.contains(packageName) + "BLACKLIST" -> !blacklist.contains(packageName) + else -> true // "GLOBAL" + } + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/hook/system/SystemServerHook.kt b/app/src/main/java/com/lzxnone/openloc/hook/system/SystemServerHook.kt new file mode 100644 index 0000000..fc6d367 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/hook/system/SystemServerHook.kt @@ -0,0 +1,281 @@ +package com.lzxnone.openloc.hook.system + +import android.location.Location +import android.os.Build +import com.lzxnone.openloc.hook.model.MockConfig +import com.lzxnone.openloc.hook.util.LocationSimulator +import de.robv.android.xposed.XC_MethodHook +import de.robv.android.xposed.XposedBridge +import de.robv.android.xposed.XposedHelpers +import org.xmlpull.v1.XmlPullParser +import org.xmlpull.v1.XmlPullParserFactory +import java.io.File +import java.io.FileInputStream + +/** + * 针对 Android 系统框架 (system_server / android) 的系统级全局 Hook + * + * 核心原理: + * 在 Android 操作系统中,整机所有应用调用 LocationManager 获取位置, + * 底层最终全部汇集到 system_server 进程里的 LocationManagerService 中进行统一调度和分发。 + * + * 只要在 LSPosed 作用域中勾选了【Android 系统 (android)】,本拦截器就会在系统服务底层 + * 将发往所有应用的位置数据全部篡改并洗白。 + * 手机里无论是已有应用还是将来新下载的应用,统统无需单独指定,直接全局生效! + */ +object SystemServerHook { + + private const val PREF_FILE_PATH_1 = "/data/data/com.lzxnone.openloc/shared_prefs/openloc_prefs.xml" + private const val PREF_FILE_PATH_2 = "/data/user/0/com.lzxnone.openloc/shared_prefs/openloc_prefs.xml" + + @Volatile + private var lastReadTime = 0L + @Volatile + private var cachedConfig = MockConfig() + + /** + * 在 system_server 进程中直接读取 OpenLoc 的配置文件(system_server 具备最高读取权限) + */ + private fun readConfigDirectly(): MockConfig { + val now = System.currentTimeMillis() + if (now - lastReadTime < 1500L) { + return cachedConfig + } + + val file = listOf(File(PREF_FILE_PATH_1), File(PREF_FILE_PATH_2)).firstOrNull { it.exists() && it.canRead() } + ?: return cachedConfig + + try { + var isEnabled = false + var lat = 39.908722 + var lng = 116.397496 + var mode = "GLOBAL" + val whitelist = mutableSetOf() + val blacklist = mutableSetOf() + var isJitter = true + var isGnss = true + var isNetwork = true + var isSensor = true + var isStealth = true + var isDevCamouflage = true + + FileInputStream(file).use { fis -> + val factory = XmlPullParserFactory.newInstance() + val parser = factory.newPullParser() + parser.setInput(fis, "UTF-8") + + var eventType = parser.eventType + while (eventType != XmlPullParser.END_DOCUMENT) { + if (eventType == XmlPullParser.START_TAG) { + val name = parser.getAttributeValue(null, "name") + when (parser.name) { + "boolean" -> { + when (name) { + "mock_service_enabled" -> { + isEnabled = parser.getAttributeValue(null, "value") == "true" + } + "enable_jitter" -> { + isJitter = parser.getAttributeValue(null, "value") == "true" + } + "enable_gnss_simulation" -> { + isGnss = parser.getAttributeValue(null, "value") == "true" + } + "enable_network_camouflage" -> { + isNetwork = parser.getAttributeValue(null, "value") == "true" + } + "enable_sensor_simulation" -> { + isSensor = parser.getAttributeValue(null, "value") == "true" + } + "enable_stealth" -> { + isStealth = parser.getAttributeValue(null, "value") == "true" + } + "enable_dev_camouflage" -> { + isDevCamouflage = parser.getAttributeValue(null, "value") == "true" + } + } + } + "string" -> { + when (name) { + "mock_latitude" -> { + lat = parser.nextText()?.toDoubleOrNull() ?: lat + } + "mock_longitude" -> { + lng = parser.nextText()?.toDoubleOrNull() ?: lng + } + "app_mock_mode" -> { + mode = parser.nextText() ?: mode + } + "whitelist_apps" -> { + parseJsonArrayToSet(parser.nextText(), whitelist) + } + "blacklist_apps" -> { + parseJsonArrayToSet(parser.nextText(), blacklist) + } + } + } + } + } + eventType = parser.next() + } + } + + cachedConfig = MockConfig( + isEnabled = isEnabled, + latitude = lat, + longitude = lng, + mode = mode, + whitelist = whitelist, + blacklist = blacklist, + isJitterEnabled = isJitter, + isGnssSimulationEnabled = isGnss, + isNetworkCamouflageEnabled = isNetwork, + isSensorSimulationEnabled = isSensor, + isStealthEnabled = isStealth, + isDevCamouflageEnabled = isDevCamouflage + ) + lastReadTime = now + } catch (_: Throwable) {} + + return cachedConfig + } + + private fun parseJsonArrayToSet(jsonStr: String?, target: MutableSet) { + if (jsonStr.isNullOrBlank()) return + try { + val array = org.json.JSONArray(jsonStr) + for (i in 0 until array.length()) { + target.add(array.getString(i)) + } + } catch (_: Throwable) {} + } + + fun hook(classLoader: ClassLoader) { + XposedBridge.log("[OpenLoc] Initializing SystemServerHook for global mock location...") + + hookSystemLocationService(classLoader) + } + + /** + * 拦截系统底层 LocationManagerService 的分发与获取逻辑 + */ + private fun hookSystemLocationService(classLoader: ClassLoader) { + val lmsClassNames = listOf( + "com.android.server.location.LocationManagerService", + "com.android.server.LocationManagerService" + ) + + for (className in lmsClassNames) { + val lmsClass = try { + XposedHelpers.findClass(className, classLoader) + } catch (_: Throwable) { + null + } ?: continue + + hookLmsMethods(lmsClass) + break + } + + // Android 12+ (API 31)+ 核心底层服务 LocationProviderManager 拦截 + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + hookLocationProviderManager(classLoader) + } + } + + private fun hookLmsMethods(lmsClass: Class<*>) { + for (method in lmsClass.declaredMethods) { + // 1. 拦截系统返回给客户端的最后已知位置 getLastLocation + if (method.name == "getLastLocation") { + try { + XposedBridge.hookMethod(method, object : XC_MethodHook() { + override fun afterHookedMethod(param: MethodHookParam) { + val config = readConfigDirectly() + if (!config.isEnabled) return + + val pkg = extractCallingPackage(param) + if (pkg != null && !config.shouldMock(pkg)) return + + val loc = param.result as? Location + if (loc != null) { + LocationSimulator.applyMockData(loc, config.latitude, config.longitude, config.isJitterEnabled) + } else { + param.result = LocationSimulator.createMockLocation( + config.latitude, + config.longitude, + isJitterEnabled = config.isJitterEnabled + ) + } + } + }) + } catch (_: Throwable) {} + } + + // 2. 拦截系统分发定位 reportLocation + if (method.name == "reportLocation") { + try { + XposedBridge.hookMethod(method, object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val config = readConfigDirectly() + if (!config.isEnabled) return + + val loc = param.args.firstOrNull { it is Location } as? Location + if (loc != null) { + LocationSimulator.applyMockData(loc, config.latitude, config.longitude, config.isJitterEnabled) + } + } + }) + } catch (_: Throwable) {} + } + } + } + + /** + * Android 12/13/14+ LocationProviderManager 深度拦截 + */ + private fun hookLocationProviderManager(classLoader: ClassLoader) { + val lpmClasses = listOf( + "com.android.server.location.provider.LocationProviderManager", + "com.android.server.location.LocationProviderManager" + ) + + for (className in lpmClasses) { + val lpmClass = try { + XposedHelpers.findClass(className, classLoader) + } catch (_: Throwable) { + null + } ?: continue + + for (method in lpmClass.declaredMethods) { + if (method.name == "setLastLocation" || method.name == "onReportLocation") { + try { + XposedBridge.hookMethod(method, object : XC_MethodHook() { + override fun beforeHookedMethod(param: MethodHookParam) { + val config = readConfigDirectly() + if (!config.isEnabled) return + + val loc = param.args.firstOrNull { it is Location } as? Location + if (loc != null) { + LocationSimulator.applyMockData(loc, config.latitude, config.longitude, config.isJitterEnabled) + } + } + }) + } catch (_: Throwable) {} + } + } + } + } + + private fun extractCallingPackage(param: XC_MethodHook.MethodHookParam): String? { + for (arg in param.args) { + if (arg is String && arg.contains(".") && !arg.contains("/")) { + return arg + } + if (arg != null && arg.javaClass.name.contains("AttributionSource")) { + try { + val pkg = XposedHelpers.callMethod(arg, "getPackageName") as? String + if (!pkg.isNullOrBlank()) return pkg + } catch (_: Throwable) {} + } + } + return null + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/hook/util/LocationSimulator.kt b/app/src/main/java/com/lzxnone/openloc/hook/util/LocationSimulator.kt new file mode 100644 index 0000000..e11a9a3 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/hook/util/LocationSimulator.kt @@ -0,0 +1,154 @@ +package com.lzxnone.openloc.hook.util + +import android.location.Location +import android.location.LocationManager +import android.os.Build +import android.os.SystemClock +import de.robv.android.xposed.XposedHelpers +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.sqrt +import kotlin.random.Random + +/** + * 虚拟位置模拟生成与洗白工具 + */ +object LocationSimulator { + + @Volatile + private var driftOffsetX = 0.0 // meters (East-West) + @Volatile + private var driftOffsetY = 0.0 // meters (North-South) + @Volatile + private var lastDriftTime = 0L + @Volatile + private var currentBearing = 0.0f + @Volatile + private var currentSpeed = 0.0f + + /** + * 计算并获取经过自然微漂移(平滑布朗运动)后的实时坐标 + */ + @Synchronized + fun getSimulatedCoordinates( + latitude: Double, + longitude: Double, + isJitterEnabled: Boolean + ): Pair { + if (!isJitterEnabled) { + return Pair(latitude, longitude) + } + + val now = SystemClock.elapsedRealtime() + val dt = if (lastDriftTime == 0L) 1.0 else ((now - lastDriftTime).coerceIn(100L, 5000L) / 1000.0) + lastDriftTime = now + + // 随机步长(随时间平滑积累,约每秒 0.15~0.3m) + val stepStdDev = 0.20 * sqrt(dt) + val dX = (Random.nextDouble() - 0.5) * 2.0 * stepStdDev + val dY = (Random.nextDouble() - 0.5) * 2.0 * stepStdDev + + // 类似弹簧向中心回拉,确保长期稳定在一个极小的真实扰动圆圈内(半径约 1.5 米以内) + val springFactor = 0.08 * dt + driftOffsetX = (driftOffsetX + dX) * (1.0 - springFactor) + driftOffsetY = (driftOffsetY + dY) * (1.0 - springFactor) + + val dist = sqrt(driftOffsetX * driftOffsetX + driftOffsetY * driftOffsetY) + val maxRadius = 1.8 // 最大漂移半径 1.8 米 + if (dist > maxRadius) { + driftOffsetX = (driftOffsetX / dist) * maxRadius + driftOffsetY = (driftOffsetY / dist) * maxRadius + } + + // 米转换为纬度与经度增量 + val metersPerLatDegree = 111132.92 + val latRad = Math.toRadians(latitude) + val metersPerLngDegree = (111412.84 * cos(latRad)).coerceAtLeast(1.0) + + val finalLat = latitude + (driftOffsetY / metersPerLatDegree) + val finalLng = longitude + (driftOffsetX / metersPerLngDegree) + + // 计算微弱的自然速度和方向 + currentSpeed = (dist * 0.04 + Random.nextDouble(0.01, 0.06)).toFloat() + if (dist > 0.15) { + currentBearing = ((Math.toDegrees(atan2(driftOffsetX, driftOffsetY)) + 360) % 360).toFloat() + } + + return Pair(finalLat, finalLng) + } + + /** + * 生成一个全新且各项指标逼真的 Location 实例 + */ + fun createMockLocation( + latitude: Double, + longitude: Double, + provider: String = LocationManager.GPS_PROVIDER, + isJitterEnabled: Boolean = true + ): Location { + return Location(provider).apply { + applyMockData(this, latitude, longitude, isJitterEnabled) + } + } + + /** + * 将虚拟数据注入到现有的 Location 实例中,并彻底抹除 Mock 标志 + */ + fun applyMockData( + location: Location, + latitude: Double, + longitude: Double, + isJitterEnabled: Boolean = true + ) { + val (finalLat, finalLng) = getSimulatedCoordinates(latitude, longitude, isJitterEnabled) + val dist = sqrt(driftOffsetX * driftOffsetX + driftOffsetY * driftOffsetY) + + location.latitude = finalLat + location.longitude = finalLng + location.altitude = if (isJitterEnabled) { + 25.0 + (driftOffsetY * 0.1) + Random.nextDouble(-0.3, 0.3) + } else { + 25.0 + } + location.accuracy = if (isJitterEnabled) { + 3.5f + (dist * 0.6f).toFloat() + Random.nextFloat() * 0.5f // 3.5m ~ 5.5m 真实波动 + } else { + 3.5f + } + location.speed = if (isJitterEnabled) currentSpeed else 0.0f + location.bearing = if (isJitterEnabled) currentBearing else 0.0f + location.time = System.currentTimeMillis() + location.elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos() + + // 彻底洗白:抹除系统自带的 isFromMockProvider 标志 + stripMockFlags(location) + } + + /** + * 抹除 Location 对象上的所有模拟位置痕迹 + */ + fun stripMockFlags(location: Location) { + try { + // Android 12 (API 31)+ 官方新增属性 + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + location.isMock = false + } + + // 针对各版本 Android 内部 mIsFromMockProvider 字段反射清洗 + try { + XposedHelpers.setBooleanField(location, "mIsFromMockProvider", false) + } catch (_: Throwable) {} + + try { + XposedHelpers.callMethod(location, "setIsFromMockProvider", false) + } catch (_: Throwable) {} + + // Android 9+ (API 28)+ 内部的 mFieldsMask 标志位清洗 + try { + val fieldsMask = XposedHelpers.getIntField(location, "mFieldsMask") + // 清除 HAS_MOCK_PROVIDER 标志位 (通常是 0x10 或类似) + XposedHelpers.setIntField(location, "mFieldsMask", fieldsMask and 0x10.inv()) + } catch (_: Throwable) {} + } catch (_: Throwable) {} + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/hook/util/VirtualGnssEngine.kt b/app/src/main/java/com/lzxnone/openloc/hook/util/VirtualGnssEngine.kt new file mode 100644 index 0000000..c0f491b --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/hook/util/VirtualGnssEngine.kt @@ -0,0 +1,276 @@ +package com.lzxnone.openloc.hook.util + +import android.location.GnssStatus +import android.os.Build +import de.robv.android.xposed.XposedHelpers +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale +import java.util.TimeZone +import kotlin.math.sin +import kotlin.random.Random + +/** + * 全真多星座 GNSS 虚拟卫星仿真引擎 + * + * 1. 提供覆盖全球及中国主流芯片的多星座卫星池(GPS、北斗、GLONASS、Galileo,共 26 颗) + * 2. 依据仰角几何球坐标动态生成符合物理传输衰减的载噪比 (C/N0, 18~42 dB-Hz) 与时变微弱抖动 + * 3. 动态构建原生系统级 GnssStatus 实例(支持 Android 11+ Builder 与反射双重兜底) + * 4. 动态生成工业标准的 NMEA-0183 报文阵列($GNGGA, $GNRMC, $GNGSA, $BDGSA, $GPGSV, $BDGSV, $GLGSV) + */ +object VirtualGnssEngine { + + data class VirtualSatellite( + val constellationType: Int, + val svid: Int, + val elevation: Float, + val azimuth: Float, + val carrierFrequencyHz: Float, + val usedInFix: Boolean + ) + + // 预设全真多星座卫星池(分布在 0~360° 方位角与 10~85° 仰角的完整半球星空) + private val SATELLITE_POOL = listOf( + // GPS (Constellation 1) - 8 颗,6 颗参与 Fix + VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 3, 68f, 120f, 1575420000f, true), + VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 7, 42f, 280f, 1575420000f, true), + VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 14, 81f, 45f, 1575420000f, true), + VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 16, 25f, 190f, 1575420000f, true), + VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 22, 14f, 330f, 1575420000f, false), + VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 27, 53f, 85f, 1575420000f, true), + VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 30, 32f, 240f, 1575420000f, true), + VirtualSatellite(GnssStatus.CONSTELLATION_GPS, 31, 11f, 15f, 1575420000f, false), + + // BDS 北斗 (Constellation 5) - 10 颗,8 颗参与 Fix (国内核心主力) + VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 1, 40f, 140f, 1561098000f, true), + VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 6, 75f, 210f, 1561098000f, true), + VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 9, 58f, 60f, 1561098000f, true), + VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 13, 84f, 175f, 1561098000f, true), + VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 19, 30f, 310f, 1561098000f, true), + VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 21, 49f, 15f, 1561098000f, true), + VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 26, 63f, 105f, 1561098000f, true), + VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 33, 22f, 265f, 1561098000f, false), + VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 35, 37f, 195f, 1561098000f, true), + VirtualSatellite(GnssStatus.CONSTELLATION_BEIDOU, 37, 12f, 80f, 1561098000f, false), + + // GLONASS (Constellation 3) - 5 颗,4 颗参与 Fix + VirtualSatellite(GnssStatus.CONSTELLATION_GLONASS, 66, 55f, 350f, 1602000000f, true), + VirtualSatellite(GnssStatus.CONSTELLATION_GLONASS, 71, 70f, 135f, 1602000000f, true), + VirtualSatellite(GnssStatus.CONSTELLATION_GLONASS, 74, 38f, 225f, 1602000000f, true), + VirtualSatellite(GnssStatus.CONSTELLATION_GLONASS, 82, 18f, 95f, 1602000000f, false), + VirtualSatellite(GnssStatus.CONSTELLATION_GLONASS, 88, 28f, 170f, 1602000000f, true), + + // GALILEO (Constellation 6) - 3 颗,2 颗参与 Fix + VirtualSatellite(GnssStatus.CONSTELLATION_GALILEO, 4, 64f, 290f, 1575420000f, true), + VirtualSatellite(GnssStatus.CONSTELLATION_GALILEO, 12, 45f, 50f, 1575420000f, true), + VirtualSatellite(GnssStatus.CONSTELLATION_GALILEO, 19, 15f, 160f, 1575420000f, false) + ) + + private val timeFormat = SimpleDateFormat("HHmmss.SS", Locale.US).apply { + timeZone = TimeZone.getTimeZone("UTC") + } + private val dateFormat = SimpleDateFormat("ddMMyy", Locale.US).apply { + timeZone = TimeZone.getTimeZone("UTC") + } + + /** + * 根据仰角计算符合真实物理衰减的 C/N0 载噪比(单位 dB-Hz) + */ + fun computeCn0(sat: VirtualSatellite): Float { + val elevRad = Math.toRadians(sat.elevation.toDouble()) + val baseCn0 = 18.0 + 23.0 * sin(elevRad) + val noise = (Random.nextDouble() - 0.5) * 1.5 + return (baseCn0 + noise).coerceIn(16.0, 42.5).toFloat() + } + + /** + * 构建或获取原生系统的 GnssStatus 实例 + */ + fun createGnssStatus(): GnssStatus? { + // 优先使用 Android 11+ (API 30+) 官方提供的 GnssStatus.Builder + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + try { + val builder = GnssStatus.Builder() + val addSatelliteMethod = builder.javaClass.methods.firstOrNull { it.name == "addSatellite" } + if (addSatelliteMethod != null) { + val paramCount = addSatelliteMethod.parameterTypes.size + for (sat in SATELLITE_POOL) { + val cn0 = computeCn0(sat) + if (paramCount >= 12) { + addSatelliteMethod.invoke( + builder, + sat.constellationType, + sat.svid, + cn0, + sat.elevation, + sat.azimuth, + true, // hasEphemeris + true, // hasAlmanac + sat.usedInFix, + true, // hasCarrierFrequency + sat.carrierFrequencyHz, + true, // hasBasebandCn0 + (cn0 - 2.0f).coerceAtLeast(10.0f) // basebandCn0 + ) + } else { + addSatelliteMethod.invoke( + builder, + sat.constellationType, + sat.svid, + cn0, + sat.elevation, + sat.azimuth, + true, // hasEphemeris + true, // hasAlmanac + sat.usedInFix, + true, // hasCarrierFrequency + sat.carrierFrequencyHz + ) + } + } + return builder.build() + } + } catch (_: Throwable) {} + } + + // 低版本反射兜底(构造私有构造器) + return try { + val count = SATELLITE_POOL.size + val svidWithFlags = IntArray(count) + val cn0s = FloatArray(count) + val elevations = FloatArray(count) + val azimuths = FloatArray(count) + val carrierFreqs = FloatArray(count) + + for (i in 0 until count) { + val sat = SATELLITE_POOL[i] + // 编码 svidWithFlags (AOSP 规范) + var flags = (sat.constellationType and 0x0F) shl 4 + flags = flags or (sat.svid shl 8) + flags = flags or 1 // hasEphemeris + flags = flags or 2 // hasAlmanac + if (sat.usedInFix) flags = flags or 4 + flags = flags or 8 // hasCarrierFrequency + + svidWithFlags[i] = flags + cn0s[i] = computeCn0(sat) + elevations[i] = sat.elevation + azimuths[i] = sat.azimuth + carrierFreqs[i] = sat.carrierFrequencyHz + } + + try { + // Android 10+ 构造函数含 carrierFrequencies + XposedHelpers.newInstance( + GnssStatus::class.java, + count, + svidWithFlags, + cn0s, + elevations, + azimuths, + carrierFreqs + ) as? GnssStatus + } catch (_: Throwable) { + // Android 7~9 构造函数 5 参数 + XposedHelpers.newInstance( + GnssStatus::class.java, + count, + svidWithFlags, + cn0s, + elevations, + azimuths + ) as? GnssStatus + } + } catch (_: Throwable) { + null + } + } + + /** + * 生成全套完整的工业级 NMEA-0183 报文序列(包含 GGA, RMC, GSA, GSV 多星座信标) + */ + fun generateFullNmeaSequence(lat: Double, lng: Double, time: Long): List { + val result = mutableListOf() + val utcTime = timeFormat.format(Date(time)) + val dateStr = dateFormat.format(Date(time)) + val latStr = formatToNmeaCoord(lat, true) + val lngStr = formatToNmeaCoord(lng, false) + + val totalUsedSats = SATELLITE_POOL.count { it.usedInFix } + + // 1. $GNGGA 定位解数据 + val ggaContent = "GNGGA,$utcTime,$latStr,$lngStr,1,$totalUsedSats,0.8,25.0,M,0.0,M,," + result.add("\$$ggaContent*${calculateChecksum(ggaContent)}\r\n") + + // 2. $GNRMC 推荐最小导航数据 + val rmcContent = "GNRMC,$utcTime,A,$latStr,$lngStr,0.0,0.0,$dateStr,,,A" + result.add("\$$rmcContent*${calculateChecksum(rmcContent)}\r\n") + + // 3. $GNGSA (GPS 精度因子与解算卫星) + val gpsUsedSats = SATELLITE_POOL.filter { it.constellationType == GnssStatus.CONSTELLATION_GPS && it.usedInFix } + val gpsPrnSlots = (0 until 12).map { index -> + if (index < gpsUsedSats.size) String.format(Locale.US, "%02d", gpsUsedSats[index].svid) else "" + }.joinToString(",") + val gsaGpsContent = "GNGSA,A,3,$gpsPrnSlots,1.2,0.8,0.9,1" + result.add("\$$gsaGpsContent*${calculateChecksum(gsaGpsContent)}\r\n") + + // 4. $BDGSA (北斗精度因子与解算卫星) + val bdsUsedSats = SATELLITE_POOL.filter { it.constellationType == GnssStatus.CONSTELLATION_BEIDOU && it.usedInFix } + val bdsPrnSlots = (0 until 12).map { index -> + if (index < bdsUsedSats.size) String.format(Locale.US, "%02d", bdsUsedSats[index].svid) else "" + }.joinToString(",") + val gsaBdsContent = "BDGSA,A,3,$bdsPrnSlots,1.2,0.8,0.9,4" + result.add("\$$gsaBdsContent*${calculateChecksum(gsaBdsContent)}\r\n") + + // 5. $GPGSV (GPS 可见卫星星标,每页至多 4 颗) + val gpsSats = SATELLITE_POOL.filter { it.constellationType == GnssStatus.CONSTELLATION_GPS } + appendGsvSentences("GPGSV", gpsSats, result) + + // 6. $BDGSV (北斗可见卫星星标,每页至多 4 颗) + val bdsSats = SATELLITE_POOL.filter { it.constellationType == GnssStatus.CONSTELLATION_BEIDOU } + appendGsvSentences("BDGSV", bdsSats, result) + + // 7. $GLGSV (GLONASS 可见卫星星标,每页至多 4 颗) + val gloSats = SATELLITE_POOL.filter { it.constellationType == GnssStatus.CONSTELLATION_GLONASS } + appendGsvSentences("GLGSV", gloSats, result) + + return result + } + + private fun appendGsvSentences(talker: String, sats: List, target: MutableList) { + val totalSats = sats.size + val totalPages = (totalSats + 3) / 4 + for (page in 1..totalPages) { + val chunk = sats.drop((page - 1) * 4).take(4) + val sb = java.lang.StringBuilder("$talker,$totalPages,$page,$totalSats") + for (s in chunk) { + val cn0 = computeCn0(s).toInt() + sb.append(String.format(Locale.US, ",%02d,%02d,%03d,%02d", s.svid, s.elevation.toInt(), s.azimuth.toInt(), cn0)) + } + sb.append(",1") // 信号 ID (L1/B1) + val content = sb.toString() + target.add("\$$content*${calculateChecksum(content)}\r\n") + } + } + + private fun formatToNmeaCoord(coord: Double, isLat: Boolean): String { + val abs = Math.abs(coord) + val degrees = abs.toInt() + val minutes = (abs - degrees) * 60.0 + val direction = if (isLat) { + if (coord >= 0) "N" else "S" + } else { + if (coord >= 0) "E" else "W" + } + val coordFormat = if (isLat) "%02d%07.4f" else "%03d%07.4f" + return String.format(Locale.US, "$coordFormat,$direction", degrees, minutes) + } + + private fun calculateChecksum(sentence: String): String { + var sum = 0 + for (ch in sentence) { + sum = sum xor ch.code + } + return String.format(Locale.US, "%02X", sum) + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/ui/components/OpenLocBottomBar.kt b/app/src/main/java/com/lzxnone/openloc/ui/components/OpenLocBottomBar.kt new file mode 100644 index 0000000..2dc263b --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/ui/components/OpenLocBottomBar.kt @@ -0,0 +1,56 @@ +package com.lzxnone.openloc.ui.components + +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.NavigationBar +import androidx.compose.material3.NavigationBarItem +import androidx.compose.material3.NavigationBarItemDefaults +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import com.lzxnone.openloc.ui.navigation.NavTab + +/** + * 底部导航栏组件 (Material 3 NavigationBar) + */ +@Composable +fun OpenLocBottomBar( + currentTab: NavTab, + onTabSelected: (NavTab) -> Unit, + modifier: Modifier = Modifier +) { + NavigationBar( + modifier = modifier, + containerColor = MaterialTheme.colorScheme.surface, + contentColor = MaterialTheme.colorScheme.onSurface + ) { + NavTab.entries.forEach { tab -> + val isSelected = currentTab == tab + NavigationBarItem( + selected = isSelected, + onClick = { onTabSelected(tab) }, + icon = { + Icon( + imageVector = if (isSelected) tab.selectedIcon else tab.unselectedIcon, + contentDescription = stringResource(id = tab.titleRes) + ) + }, + label = { + Text( + text = stringResource(id = tab.titleRes), + fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal + ) + }, + colors = NavigationBarItemDefaults.colors( + indicatorColor = MaterialTheme.colorScheme.primaryContainer, + selectedIconColor = MaterialTheme.colorScheme.onPrimaryContainer, + selectedTextColor = MaterialTheme.colorScheme.primary, + unselectedIconColor = MaterialTheme.colorScheme.onSurfaceVariant, + unselectedTextColor = MaterialTheme.colorScheme.onSurfaceVariant + ) + ) + } + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/ui/components/OpenLocTopBar.kt b/app/src/main/java/com/lzxnone/openloc/ui/components/OpenLocTopBar.kt new file mode 100644 index 0000000..48f696d --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/ui/components/OpenLocTopBar.kt @@ -0,0 +1,38 @@ +package com.lzxnone.openloc.ui.components + +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import com.lzxnone.openloc.R + +/** + * 统一顶部标题栏 (Material 3) + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun OpenLocTopBar( + title: String = stringResource(id = R.string.app_name), + modifier: Modifier = Modifier +) { + TopAppBar( + title = { + Text( + text = title, + style = MaterialTheme.typography.titleLarge.copy( + fontWeight = FontWeight.SemiBold + ) + ) + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.background, + titleContentColor = MaterialTheme.colorScheme.onBackground + ), + modifier = modifier + ) +} diff --git a/app/src/main/java/com/lzxnone/openloc/ui/navigation/NavTab.kt b/app/src/main/java/com/lzxnone/openloc/ui/navigation/NavTab.kt new file mode 100644 index 0000000..a781e96 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/ui/navigation/NavTab.kt @@ -0,0 +1,37 @@ +package com.lzxnone.openloc.ui.navigation + +import androidx.annotation.StringRes +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Home +import androidx.compose.material.icons.filled.Place +import androidx.compose.material.icons.filled.Settings +import androidx.compose.material.icons.outlined.Home +import androidx.compose.material.icons.outlined.Place +import androidx.compose.material.icons.outlined.Settings +import androidx.compose.ui.graphics.vector.ImageVector +import com.lzxnone.openloc.R + +/** + * 底部导航栏选项定义 + */ +enum class NavTab( + @param:StringRes val titleRes: Int, + val selectedIcon: ImageVector, + val unselectedIcon: ImageVector +) { + HOME( + titleRes = R.string.nav_home, + selectedIcon = Icons.Filled.Home, + unselectedIcon = Icons.Outlined.Home + ), + LOCATION( + titleRes = R.string.nav_location, + selectedIcon = Icons.Filled.Place, + unselectedIcon = Icons.Outlined.Place + ), + SETTINGS( + titleRes = R.string.nav_settings, + selectedIcon = Icons.Filled.Settings, + unselectedIcon = Icons.Outlined.Settings + ) +} diff --git a/app/src/main/java/com/lzxnone/openloc/ui/screens/MainScreen.kt b/app/src/main/java/com/lzxnone/openloc/ui/screens/MainScreen.kt new file mode 100644 index 0000000..fd4012b --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/ui/screens/MainScreen.kt @@ -0,0 +1,103 @@ +package com.lzxnone.openloc.ui.screens + +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.togetherWith +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.Scaffold +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import com.lzxnone.openloc.core.util.HookStatus +import com.lzxnone.openloc.data.preference.AppPreferences +import com.lzxnone.openloc.ui.components.OpenLocBottomBar +import com.lzxnone.openloc.ui.components.OpenLocTopBar +import com.lzxnone.openloc.ui.navigation.NavTab +import com.lzxnone.openloc.ui.screens.home.HomeScreen +import com.lzxnone.openloc.ui.screens.location.LocationScreen +import com.lzxnone.openloc.ui.screens.settings.SettingsScreen + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.slideInHorizontally +import androidx.compose.animation.slideOutHorizontally +import androidx.compose.foundation.layout.Box +import com.lzxnone.openloc.data.preference.AppMockMode +import com.lzxnone.openloc.ui.screens.apps.AppSelectionScreen + +/** + * 根容器页面:承载 TopAppBar、底部导航栏与各个 Tab 内容切换 + */ +@Composable +fun MainScreen( + modifier: Modifier = Modifier +) { + var currentTab by rememberSaveable { mutableStateOf(NavTab.HOME) } + var activeAppSelectionMode by rememberSaveable { mutableStateOf(null) } + + // 响应式的总开关状态与激活状态 + val isServiceEnabled = AppPreferences.isServiceEnabled + val isModuleActive = remember { HookStatus.isModuleActive() } + + Box(modifier = modifier.fillMaxSize()) { + Scaffold( + modifier = Modifier.fillMaxSize(), + contentWindowInsets = WindowInsets(0, 0, 0, 0), + topBar = { + if (currentTab != NavTab.LOCATION) { + OpenLocTopBar() + } + }, + bottomBar = { + OpenLocBottomBar( + currentTab = currentTab, + onTabSelected = { currentTab = it } + ) + } + ) { innerPadding -> + AnimatedContent( + targetState = currentTab, + transitionSpec = { + fadeIn() togetherWith fadeOut() + }, + label = "TabContentAnimation", + modifier = Modifier.padding(innerPadding) + ) { targetTab -> + when (targetTab) { + NavTab.HOME -> HomeScreen( + isModuleActive = isModuleActive, + isServiceEnabled = isServiceEnabled, + onServiceEnabledChange = { enabled -> + AppPreferences.updateServiceEnabled(enabled) + }, + onOpenBlacklist = { activeAppSelectionMode = AppMockMode.BLACKLIST }, + onOpenWhitelist = { activeAppSelectionMode = AppMockMode.WHITELIST } + ) + NavTab.LOCATION -> LocationScreen() + NavTab.SETTINGS -> SettingsScreen() + } + } + } + + // 应用选择全屏浮层(黑名单 / 白名单独立管理) + AnimatedVisibility( + visible = activeAppSelectionMode != null, + enter = slideInHorizontally(initialOffsetX = { it }) + fadeIn(), + exit = slideOutHorizontally(targetOffsetX = { it }) + fadeOut(), + modifier = Modifier.fillMaxSize() + ) { + activeAppSelectionMode?.let { mode -> + AppSelectionScreen( + mode = mode, + onNavigateBack = { activeAppSelectionMode = null } + ) + } + } + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/ui/screens/apps/AppSelectionScreen.kt b/app/src/main/java/com/lzxnone/openloc/ui/screens/apps/AppSelectionScreen.kt new file mode 100644 index 0000000..de2c8c5 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/ui/screens/apps/AppSelectionScreen.kt @@ -0,0 +1,504 @@ +package com.lzxnone.openloc.ui.screens.apps + +import android.content.pm.ApplicationInfo +import androidx.activity.compose.BackHandler +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.foundation.Image +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.outlined.Android +import androidx.compose.material.icons.outlined.Deselect +import androidx.compose.material.icons.outlined.FilterList +import androidx.compose.material.icons.outlined.SelectAll +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.Checkbox +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilterChip +import androidx.compose.material3.FilterChipDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.OutlinedTextFieldDefaults +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.core.graphics.drawable.toBitmap +import com.lzxnone.openloc.R +import com.lzxnone.openloc.data.preference.AppMockMode +import com.lzxnone.openloc.data.preference.AppPreferences +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.util.Locale + +/** + * 已安装应用数据模型 + */ +data class InstalledAppItem( + val packageName: String, + val appName: String, + val isSystemApp: Boolean, + val iconBitmap: ImageBitmap? = null +) + +/** + * 黑名单 / 白名单应用勾选管理页面 + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun AppSelectionScreen( + mode: AppMockMode, + onNavigateBack: () -> Unit, + modifier: Modifier = Modifier +) { + val context = LocalContext.current + var searchQuery by remember { mutableStateOf("") } + var showSystemApps by remember { mutableStateOf(false) } + + var installedApps by remember { mutableStateOf>(emptyList()) } + var isLoading by remember { mutableStateOf(true) } + + // 拦截返回按键 + BackHandler(onBack = onNavigateBack) + + // 异步加载所有已安装应用及其图标 + LaunchedEffect(Unit) { + withContext(Dispatchers.IO) { + val pm = context.packageManager + val packages = pm.getInstalledPackages(0) + val list = ArrayList(packages.size) + + for (pkg in packages) { + val appInfo = pkg.applicationInfo ?: continue + // 排除本应用自身 + if (pkg.packageName == context.packageName) continue + + val appName = appInfo.loadLabel(pm).toString() + val isSystem = (appInfo.flags and ApplicationInfo.FLAG_SYSTEM) != 0 + + val iconBitmap = try { + val iconDrawable = appInfo.loadIcon(pm) + iconDrawable.toBitmap(96, 96).asImageBitmap() + } catch (_: Throwable) { + null + } + + list.add( + InstalledAppItem( + packageName = pkg.packageName, + appName = appName, + isSystemApp = isSystem, + iconBitmap = iconBitmap + ) + ) + } + + // 用户应用排在前面,系统应用排在后面;组内按应用名称字母排序 + list.sortWith( + compareBy { it.isSystemApp } + .thenBy { it.appName.lowercase(Locale.ROOT) } + ) + + installedApps = list + isLoading = false + } + } + + // 关联当前名单选中的包名集合 + val selectedPackages = if (mode == AppMockMode.BLACKLIST) { + AppPreferences.blacklistApps + } else { + AppPreferences.whitelistApps + } + + // 根据搜索词和系统应用开关进行过滤 + val filteredApps = remember(installedApps, searchQuery, showSystemApps) { + installedApps.filter { app -> + (showSystemApps || !app.isSystemApp) && + (searchQuery.isBlank() || + app.appName.contains(searchQuery, ignoreCase = true) || + app.packageName.contains(searchQuery, ignoreCase = true)) + } + } + + // 标题与说明 + val titleText = if (mode == AppMockMode.BLACKLIST) { + stringResource(id = R.string.apps_blacklist_title) + } else { + stringResource(id = R.string.apps_whitelist_title) + } + + Scaffold( + modifier = modifier.fillMaxSize(), + topBar = { + TopAppBar( + title = { + Column { + Text( + text = titleText, + fontWeight = FontWeight.SemiBold, + style = MaterialTheme.typography.titleLarge + ) + Text( + text = stringResource( + id = R.string.apps_selected_count, + selectedPackages.size, + installedApps.size + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + }, + navigationIcon = { + IconButton(onClick = onNavigateBack) { + Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(id = R.string.location_search_back) + ) + } + }, + actions = { + // 全选 / 全不选按钮 + val allVisibleSelected = filteredApps.isNotEmpty() && + filteredApps.all { selectedPackages.contains(it.packageName) } + + IconButton( + onClick = { + if (allVisibleSelected) { + // 取消当前可见的所有选中 + val visiblePackageSet = filteredApps.map { it.packageName }.toSet() + val updated = selectedPackages - visiblePackageSet + if (mode == AppMockMode.BLACKLIST) { + AppPreferences.updateBlacklistApps(updated) + } else { + AppPreferences.updateWhitelistApps(updated) + } + } else { + // 选中当前可见的所有应用 + val visiblePackageSet = filteredApps.map { it.packageName }.toSet() + val updated = selectedPackages + visiblePackageSet + if (mode == AppMockMode.BLACKLIST) { + AppPreferences.updateBlacklistApps(updated) + } else { + AppPreferences.updateWhitelistApps(updated) + } + } + } + ) { + Icon( + imageVector = if (allVisibleSelected) Icons.Outlined.Deselect else Icons.Outlined.SelectAll, + contentDescription = stringResource( + id = if (allVisibleSelected) R.string.apps_deselect_all else R.string.apps_select_all + ) + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.surface, + titleContentColor = MaterialTheme.colorScheme.onSurface, + navigationIconContentColor = MaterialTheme.colorScheme.onSurface, + actionIconContentColor = MaterialTheme.colorScheme.primary + ) + ) + } + ) { innerPadding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + ) { + // 搜索栏与系统应用开关 + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 6.dp) + ) { + OutlinedTextField( + value = searchQuery, + onValueChange = { searchQuery = it }, + modifier = Modifier.fillMaxWidth(), + placeholder = { + Text( + text = stringResource(id = R.string.apps_search_hint), + style = MaterialTheme.typography.bodyMedium + ) + }, + leadingIcon = { + Icon( + imageVector = Icons.Filled.Search, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary + ) + }, + trailingIcon = { + if (searchQuery.isNotEmpty()) { + IconButton(onClick = { searchQuery = "" }) { + Icon( + imageVector = Icons.Filled.Close, + contentDescription = stringResource(id = R.string.location_search_clear), + modifier = Modifier.size(18.dp) + ) + } + } + }, + shape = RoundedCornerShape(16.dp), + singleLine = true, + colors = OutlinedTextFieldDefaults.colors( + focusedContainerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f), + unfocusedContainerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.2f), + focusedBorderColor = MaterialTheme.colorScheme.primary, + unfocusedBorderColor = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) + ) + ) + + Spacer(modifier = Modifier.height(6.dp)) + + // 筛选过滤 Chips + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.End, + verticalAlignment = Alignment.CenterVertically + ) { + FilterChip( + selected = showSystemApps, + onClick = { showSystemApps = !showSystemApps }, + label = { + Text( + text = stringResource( + id = if (showSystemApps) R.string.apps_hide_system_apps else R.string.apps_show_system_apps + ), + style = MaterialTheme.typography.labelSmall + ) + }, + leadingIcon = { + Icon( + imageVector = Icons.Outlined.FilterList, + contentDescription = null, + modifier = Modifier.size(16.dp) + ) + }, + shape = RoundedCornerShape(10.dp), + colors = FilterChipDefaults.filterChipColors( + selectedContainerColor = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.6f) + ) + ) + } + } + + // 应用列表展示 + if (isLoading) { + Box( + modifier = Modifier + .fillMaxSize() + .padding(32.dp), + contentAlignment = Alignment.Center + ) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + CircularProgressIndicator(modifier = Modifier.size(36.dp)) + Text( + text = stringResource(id = R.string.apps_loading), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } else if (filteredApps.isEmpty()) { + Box( + modifier = Modifier + .fillMaxSize() + .padding(32.dp), + contentAlignment = Alignment.Center + ) { + Text( + text = if (searchQuery.isNotEmpty()) { + stringResource(id = R.string.apps_empty_search) + } else { + stringResource(id = R.string.apps_empty_installed) + }, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } else { + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 6.dp), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + items(filteredApps, key = { it.packageName }) { app -> + val isChecked = selectedPackages.contains(app.packageName) + AppItemCard( + app = app, + isChecked = isChecked, + onToggle = { + if (mode == AppMockMode.BLACKLIST) { + AppPreferences.toggleBlacklistApp(app.packageName) + } else { + AppPreferences.toggleWhitelistApp(app.packageName) + } + } + ) + } + } + } + } + } +} + +/** + * 单个应用卡片条目 + */ +@Composable +private fun AppItemCard( + app: InstalledAppItem, + isChecked: Boolean, + onToggle: () -> Unit, + modifier: Modifier = Modifier +) { + Card( + modifier = modifier + .fillMaxWidth() + .clickable(onClick = onToggle), + shape = RoundedCornerShape(14.dp), + colors = CardDefaults.cardColors( + containerColor = if (isChecked) { + MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.45f) + } else { + MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f) + } + ), + elevation = CardDefaults.cardElevation(defaultElevation = 0.dp) + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 14.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically + ) { + // 应用图标 + if (app.iconBitmap != null) { + Image( + bitmap = app.iconBitmap, + contentDescription = null, + modifier = Modifier.size(42.dp) + ) + } else { + Surface( + shape = CircleShape, + color = MaterialTheme.colorScheme.surfaceVariant, + modifier = Modifier.size(42.dp) + ) { + Box(contentAlignment = Alignment.Center) { + Icon( + imageVector = Icons.Outlined.Android, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(24.dp) + ) + } + } + } + + Spacer(modifier = Modifier.width(14.dp)) + + // 名称与包名 + Column( + modifier = Modifier.weight(1f) + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp) + ) { + Text( + text = app.appName, + style = MaterialTheme.typography.bodyLarge.copy( + fontWeight = FontWeight.SemiBold + ), + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f, fill = false) + ) + + if (app.isSystemApp) { + Surface( + shape = RoundedCornerShape(4.dp), + color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.7f) + ) { + Text( + text = stringResource(id = R.string.apps_system_app_tag), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSecondaryContainer, + modifier = Modifier.padding(horizontal = 5.dp, vertical = 1.dp) + ) + } + } + } + + Spacer(modifier = Modifier.height(2.dp)) + + Text( + text = app.packageName, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + + Spacer(modifier = Modifier.width(8.dp)) + + // 复选框 + Checkbox( + checked = isChecked, + onCheckedChange = { onToggle() } + ) + } + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/ui/screens/favorites/FavoritesScreen.kt b/app/src/main/java/com/lzxnone/openloc/ui/screens/favorites/FavoritesScreen.kt new file mode 100644 index 0000000..c3a0ece --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/ui/screens/favorites/FavoritesScreen.kt @@ -0,0 +1,714 @@ +package com.lzxnone.openloc.ui.screens.favorites + +import android.widget.Toast +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.detectDragGestures +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.BookmarkBorder +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.DeleteOutline +import androidx.compose.material.icons.filled.DragHandle +import androidx.compose.material.icons.filled.LocationOn +import androidx.compose.material.icons.filled.Search +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.OutlinedTextFieldDefaults +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.zIndex +import com.lzxnone.openloc.LocalizedDialogContent +import com.lzxnone.openloc.R +import com.lzxnone.openloc.core.util.LocationResolver +import com.lzxnone.openloc.data.model.FavoriteItem +import com.lzxnone.openloc.data.preference.AppPreferences +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import java.util.Locale + +/** + * 收藏列表拖拽排序状态管理 + */ +class FavoriteDragDropState( + val lazyListState: LazyListState, + val getItems: () -> List, + val onMove: (Int, Int) -> Unit +) { + var draggingItemId by mutableStateOf(null) + var dragDeltaY by mutableStateOf(0f) + + fun onDragStart(id: String) { + draggingItemId = id + dragDeltaY = 0f + } + + fun onDrag(delta: Float) { + val currentId = draggingItemId ?: return + dragDeltaY += delta + + val items = getItems() + val currentIndex = items.indexOfFirst { it.id == currentId } + if (currentIndex == -1) return + + val visibleItems = lazyListState.layoutInfo.visibleItemsInfo + val currentItemInfo = visibleItems.firstOrNull { it.key == currentId } ?: return + val currentItemMiddle = currentItemInfo.offset + currentItemInfo.size / 2 + dragDeltaY + + val targetItem = visibleItems.firstOrNull { item -> + item.key != currentId && + currentItemMiddle in item.offset.toFloat()..(item.offset + item.size).toFloat() + } + + if (targetItem != null) { + val targetIndex = items.indexOfFirst { it.id == targetItem.key } + if (targetIndex != -1 && targetIndex != currentIndex) { + onMove(currentIndex, targetIndex) + dragDeltaY += (currentItemInfo.offset - targetItem.offset) + } + } + } + + fun onDragEnd() { + draggingItemId = null + dragDeltaY = 0f + } + + fun onDragCancel() { + draggingItemId = null + dragDeltaY = 0f + } +} + +/** + * 收藏夹页面 + * 包含搜索栏、条目列表(支持拖拽排序)以及添加新地址 Dialog + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun FavoritesScreen( + currentWgsLat: Double, + currentWgsLng: Double, + currentAddress: String, + onNavigateBack: () -> Unit, + onSelectFavorite: (FavoriteItem) -> Unit, + modifier: Modifier = Modifier +) { + val context = LocalContext.current + var searchQuery by remember { mutableStateOf("") } + var showAddDialog by remember { mutableStateOf(false) } + var itemToDelete by remember { mutableStateOf(null) } + + val lazyListState = rememberLazyListState() + val dragDropState = remember(lazyListState) { + FavoriteDragDropState( + lazyListState = lazyListState, + getItems = { AppPreferences.favorites }, + onMove = { from, to -> + AppPreferences.moveFavorite(from, to) + } + ) + } + + // 系统返回拦截 + BackHandler(onBack = onNavigateBack) + + Scaffold( + modifier = modifier.fillMaxSize(), + topBar = { + TopAppBar( + title = { + Text( + text = stringResource(id = R.string.favorites_title), + fontWeight = FontWeight.SemiBold + ) + }, + navigationIcon = { + IconButton(onClick = onNavigateBack) { + Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(id = R.string.action_cancel) + ) + } + }, + actions = { + IconButton(onClick = { showAddDialog = true }) { + Icon( + imageVector = Icons.Filled.Add, + contentDescription = stringResource(id = R.string.favorite_add_title) + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.surface, + titleContentColor = MaterialTheme.colorScheme.onSurface, + navigationIconContentColor = MaterialTheme.colorScheme.onSurface, + actionIconContentColor = MaterialTheme.colorScheme.primary + ) + ) + } + ) { innerPadding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(innerPadding) + ) { + // 搜索栏 + OutlinedTextField( + value = searchQuery, + onValueChange = { searchQuery = it }, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp), + placeholder = { + Text( + text = stringResource(id = R.string.favorite_search_hint), + style = MaterialTheme.typography.bodyMedium + ) + }, + leadingIcon = { + Icon( + imageVector = Icons.Filled.Search, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary + ) + }, + trailingIcon = { + if (searchQuery.isNotEmpty()) { + IconButton(onClick = { searchQuery = "" }) { + Icon( + imageVector = Icons.Filled.Close, + contentDescription = null, + modifier = Modifier.size(18.dp) + ) + } + } + }, + shape = RoundedCornerShape(16.dp), + singleLine = true, + colors = OutlinedTextFieldDefaults.colors( + focusedContainerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f), + unfocusedContainerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.2f), + focusedBorderColor = MaterialTheme.colorScheme.primary, + unfocusedBorderColor = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) + ) + ) + + // 过滤收藏列表 + val allFavorites = AppPreferences.favorites + val filteredFavorites = remember(searchQuery, allFavorites) { + if (searchQuery.isBlank()) { + allFavorites + } else { + allFavorites.filter { item -> + item.name.contains(searchQuery, ignoreCase = true) || + item.address.contains(searchQuery, ignoreCase = true) + } + } + } + + if (allFavorites.isEmpty()) { + // 无收藏数据时空状态提示 + Box( + modifier = Modifier + .fillMaxSize() + .padding(32.dp), + contentAlignment = Alignment.Center + ) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + Surface( + shape = CircleShape, + color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.5f), + modifier = Modifier.size(72.dp) + ) { + Box(contentAlignment = Alignment.Center) { + Icon( + imageVector = Icons.Filled.BookmarkBorder, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(36.dp) + ) + } + } + Text( + text = stringResource(id = R.string.favorite_empty_list), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } else if (filteredFavorites.isEmpty()) { + // 搜索无结果 + Box( + modifier = Modifier + .fillMaxSize() + .padding(32.dp), + contentAlignment = Alignment.Center + ) { + Text( + text = stringResource(id = R.string.favorite_search_empty), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } else { + // 列表区域(支持拖动排序) + LazyColumn( + state = lazyListState, + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(10.dp) + ) { + items(filteredFavorites, key = { it.id }) { item -> + val isDragging = dragDropState.draggingItemId == item.id + FavoriteItemCard( + item = item, + isDragging = isDragging, + dragDeltaY = if (isDragging) dragDropState.dragDeltaY else 0f, + showDragHandle = searchQuery.isBlank(), + onDragStart = { dragDropState.onDragStart(item.id) }, + onDrag = { dragDropState.onDrag(it) }, + onDragEnd = { dragDropState.onDragEnd() }, + onDragCancel = { dragDropState.onDragCancel() }, + onClick = { onSelectFavorite(item) }, + onDelete = { itemToDelete = item }, + modifier = if (isDragging) Modifier else Modifier.animateItem() + ) + } + } + } + } + } + + // 新增收藏 Dialog + if (showAddDialog) { + AddFavoriteDialog( + initialLat = currentWgsLat, + initialLng = currentWgsLng, + initialAddress = currentAddress, + onDismiss = { showAddDialog = false }, + onConfirm = { newItem -> + AppPreferences.addFavorite(newItem) + Toast.makeText(context, context.getString(R.string.favorite_added_success), Toast.LENGTH_SHORT).show() + showAddDialog = false + } + ) + } + + // 删除确认 Dialog + itemToDelete?.let { item -> + AlertDialog( + onDismissRequest = { itemToDelete = null }, + title = { + Text(text = stringResource(id = R.string.favorite_delete_confirm_title)) + }, + text = { + Text(text = stringResource(id = R.string.favorite_delete_confirm_msg, item.name)) + }, + confirmButton = { + Button( + onClick = { + AppPreferences.removeFavorite(item.id) + Toast.makeText(context, context.getString(R.string.favorite_deleted_success), Toast.LENGTH_SHORT).show() + itemToDelete = null + } + ) { + Text(text = stringResource(id = R.string.favorite_delete)) + } + }, + dismissButton = { + TextButton(onClick = { itemToDelete = null }) { + Text(text = stringResource(id = R.string.action_cancel)) + } + } + ) + } +} + +/** + * 单条收藏条目卡片 + * 支持拖动排序手柄与点击选定 + */ +@Composable +private fun FavoriteItemCard( + item: FavoriteItem, + isDragging: Boolean, + dragDeltaY: Float, + showDragHandle: Boolean, + onDragStart: () -> Unit, + onDrag: (Float) -> Unit, + onDragEnd: () -> Unit, + onDragCancel: () -> Unit, + onClick: () -> Unit, + onDelete: () -> Unit, + modifier: Modifier = Modifier +) { + val currentOnDragStart by rememberUpdatedState(onDragStart) + val currentOnDrag by rememberUpdatedState(onDrag) + val currentOnDragEnd by rememberUpdatedState(onDragEnd) + val currentOnDragCancel by rememberUpdatedState(onDragCancel) + + Card( + modifier = modifier + .fillMaxWidth() + .zIndex(if (isDragging) 2f else 0f) + .graphicsLayer { + translationY = if (isDragging) dragDeltaY else 0f + shadowElevation = if (isDragging) 24f else 0f + scaleX = if (isDragging) 1.02f else 1f + scaleY = if (isDragging) 1.02f else 1f + } + .clickable(enabled = !isDragging, onClick = onClick), + shape = RoundedCornerShape(16.dp), + colors = CardDefaults.cardColors( + containerColor = if (isDragging) { + MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.55f) + } else { + MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f) + } + ), + elevation = CardDefaults.cardElevation( + defaultElevation = if (isDragging) 8.dp else 0.dp + ) + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(14.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Surface( + shape = CircleShape, + color = MaterialTheme.colorScheme.primaryContainer, + modifier = Modifier.size(42.dp) + ) { + Box(contentAlignment = Alignment.Center) { + Icon( + imageVector = Icons.Filled.LocationOn, + contentDescription = null, + tint = MaterialTheme.colorScheme.onPrimaryContainer, + modifier = Modifier.size(22.dp) + ) + } + } + + Spacer(modifier = Modifier.width(14.dp)) + + Column( + modifier = Modifier.weight(1f) + ) { + // 名称 + Text( + text = item.name, + style = MaterialTheme.typography.titleMedium.copy( + fontWeight = FontWeight.Bold + ), + color = MaterialTheme.colorScheme.onSurface, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + + Spacer(modifier = Modifier.height(2.dp)) + + // 地区名称小字 + Text( + text = item.address.ifEmpty { stringResource(id = R.string.location_unknown_address) }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis + ) + + Spacer(modifier = Modifier.height(3.dp)) + + // 经纬度小字 + Text( + text = "${stringResource(id = R.string.location_latitude_format, item.latitude)} ${stringResource(id = R.string.location_longitude_format, item.longitude)}", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.primary + ) + } + + // 删除按钮 + IconButton( + onClick = onDelete, + modifier = Modifier.size(36.dp) + ) { + Icon( + imageVector = Icons.Filled.DeleteOutline, + contentDescription = stringResource(id = R.string.favorite_delete), + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + // 拖动手柄 (仅在未进行搜索过滤时显示) + if (showDragHandle) { + Box( + modifier = Modifier + .size(40.dp) + .pointerInput(Unit) { + detectDragGestures( + onDragStart = { currentOnDragStart() }, + onDrag = { change, dragAmount -> + change.consume() + currentOnDrag(dragAmount.y) + }, + onDragEnd = { currentOnDragEnd() }, + onDragCancel = { currentOnDragCancel() } + ) + }, + contentAlignment = Alignment.Center + ) { + Icon( + imageVector = Icons.Filled.DragHandle, + contentDescription = stringResource(id = R.string.favorite_drag_handle), + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } + } +} + +/** + * 新增地址 Dialog + * 默认填入当前地图坐标与地区名称 + * 名称默认与地区名称相同 + * 地区名称彻底禁用,经纬度修改时自动推导地区名称与同步默认名称 + */ +@Composable +private fun AddFavoriteDialog( + initialLat: Double, + initialLng: Double, + initialAddress: String, + onDismiss: () -> Unit, + onConfirm: (FavoriteItem) -> Unit +) { + val context = LocalContext.current + val coroutineScope = rememberCoroutineScope() + + // 默认名称与地区名称相同 + var name by remember { mutableStateOf(initialAddress) } + var latText by remember { mutableStateOf(String.format(Locale.US, "%.6f", initialLat)) } + var lngText by remember { mutableStateOf(String.format(Locale.US, "%.6f", initialLng)) } + var address by remember { mutableStateOf(initialAddress) } + var isResolvingAddress by remember { mutableStateOf(false) } + var resolveJob by remember { mutableStateOf(null) } + var errorMessage by remember { mutableStateOf(null) } + + // 经纬度变化时,防抖 500ms 自动推导地区名称 + fun triggerAddressResolve() { + val lat = latText.toDoubleOrNull() + val lng = lngText.toDoubleOrNull() + if (lat != null && lng != null && lat in -90.0..90.0 && lng in -180.0..180.0) { + errorMessage = null + resolveJob?.cancel() + val oldAddress = address + resolveJob = coroutineScope.launch { + delay(500) + isResolvingAddress = true + val resolved = LocationResolver.resolveLocationName(context, lat, lng) + val resolvedAddr = resolved.ifBlank { context.getString(R.string.location_unknown_address) } + // 如果用户尚未手动修改名称,或名称仍为旧推导地名,则随之更新默认名称 + if (name.isBlank() || name == oldAddress) { + name = resolvedAddr + } + address = resolvedAddr + isResolvingAddress = false + } + } else { + errorMessage = context.getString(R.string.favorite_invalid_coords) + } + } + + AlertDialog( + onDismissRequest = onDismiss, + title = { + LocalizedDialogContent { + Text( + text = stringResource(id = R.string.favorite_add_title), + style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold) + ) + } + }, + text = { + LocalizedDialogContent { + Column( + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + // 名称输入 (默认与地区名称相同) + OutlinedTextField( + value = name, + onValueChange = { + name = it + if (errorMessage != null) errorMessage = null + }, + label = { Text(text = stringResource(id = R.string.favorite_name_label)) }, + placeholder = { Text(text = stringResource(id = R.string.favorite_name_hint)) }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(12.dp) + ) + + // 地区名称 (禁用不可修改,由经纬度自动推导) + OutlinedTextField( + value = if (isResolvingAddress) stringResource(id = R.string.favorite_address_deriving) else address, + onValueChange = {}, + label = { Text(text = stringResource(id = R.string.favorite_address_label)) }, + enabled = false, + singleLine = false, + maxLines = 3, + trailingIcon = { + if (isResolvingAddress) { + CircularProgressIndicator( + modifier = Modifier.size(18.dp), + strokeWidth = 2.dp + ) + } + }, + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(12.dp), + colors = OutlinedTextFieldDefaults.colors( + disabledTextColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f), + disabledLabelColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f), + disabledBorderColor = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f), + disabledContainerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.25f) + ) + ) + + // 纬度与经度输入 + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + OutlinedTextField( + value = latText, + onValueChange = { + latText = it + triggerAddressResolve() + }, + label = { Text(text = stringResource(id = R.string.favorite_latitude_label)) }, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal), + singleLine = true, + modifier = Modifier.weight(1f), + shape = RoundedCornerShape(12.dp) + ) + + OutlinedTextField( + value = lngText, + onValueChange = { + lngText = it + triggerAddressResolve() + }, + label = { Text(text = stringResource(id = R.string.favorite_longitude_label)) }, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal), + singleLine = true, + modifier = Modifier.weight(1f), + shape = RoundedCornerShape(12.dp) + ) + } + + // 错误提示 + if (errorMessage != null) { + Text( + text = errorMessage ?: "", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error + ) + } + } + } + }, + confirmButton = { + LocalizedDialogContent { + Button( + onClick = { + val trimmedName = name.trim() + val lat = latText.toDoubleOrNull() + val lng = lngText.toDoubleOrNull() + + if (trimmedName.isEmpty()) { + errorMessage = context.getString(R.string.favorite_invalid_name) + return@Button + } + if (lat == null || lng == null || lat !in -90.0..90.0 || lng !in -180.0..180.0) { + errorMessage = context.getString(R.string.favorite_invalid_coords) + return@Button + } + + onConfirm( + FavoriteItem( + name = trimmedName, + address = address.trim(), + latitude = lat, + longitude = lng + ) + ) + } + ) { + Text(text = stringResource(id = R.string.settings_amap_key_save)) + } + } + }, + dismissButton = { + LocalizedDialogContent { + TextButton(onClick = onDismiss) { + Text(text = stringResource(id = R.string.action_cancel)) + } + } + } + ) +} diff --git a/app/src/main/java/com/lzxnone/openloc/ui/screens/home/AppManagementCard.kt b/app/src/main/java/com/lzxnone/openloc/ui/screens/home/AppManagementCard.kt new file mode 100644 index 0000000..502e1f2 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/ui/screens/home/AppManagementCard.kt @@ -0,0 +1,262 @@ +package com.lzxnone.openloc.ui.screens.home + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight +import androidx.compose.material.icons.outlined.Block +import androidx.compose.material.icons.outlined.CheckCircleOutline +import androidx.compose.material.icons.outlined.Tune +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.SegmentedButton +import androidx.compose.material3.SegmentedButtonDefaults +import androidx.compose.material3.SingleChoiceSegmentedButtonRow +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.lzxnone.openloc.R +import com.lzxnone.openloc.data.preference.AppMockMode +import com.lzxnone.openloc.data.preference.AppPreferences + +/** + * 主页应用作用域管理卡片 + * 支持切换模式(全局 / 黑名单 / 白名单)及分别进入黑名单与白名单管理页面 + */ +@Composable +fun AppManagementCard( + currentMode: AppMockMode, + onModeChange: (AppMockMode) -> Unit, + blacklistCount: Int, + whitelistCount: Int, + onOpenBlacklist: () -> Unit, + onOpenWhitelist: () -> Unit, + modifier: Modifier = Modifier +) { + Card( + modifier = modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surface + ), + elevation = CardDefaults.cardElevation( + defaultElevation = 1.dp + ) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(20.dp) + ) { + // 头部标题与图标 + Row( + verticalAlignment = Alignment.CenterVertically + ) { + Surface( + shape = CircleShape, + color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.6f), + modifier = Modifier.size(36.dp) + ) { + Box(contentAlignment = Alignment.Center) { + Icon( + imageVector = Icons.Outlined.Tune, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(20.dp) + ) + } + } + + Spacer(modifier = Modifier.width(12.dp)) + + Column { + Text( + text = stringResource(id = R.string.apps_management_title), + style = MaterialTheme.typography.titleMedium.copy( + fontWeight = FontWeight.Bold + ), + color = MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.height(2.dp)) + Text( + text = stringResource(id = R.string.apps_management_desc), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + Spacer(modifier = Modifier.height(16.dp)) + + // 模式选择分段选择器 + SingleChoiceSegmentedButtonRow( + modifier = Modifier.fillMaxWidth() + ) { + SegmentedButton( + selected = currentMode == AppMockMode.GLOBAL, + onClick = { onModeChange(AppMockMode.GLOBAL) }, + shape = SegmentedButtonDefaults.itemShape(index = 0, count = 3) + ) { + Text( + text = stringResource(id = R.string.apps_mode_global), + style = MaterialTheme.typography.labelMedium + ) + } + + SegmentedButton( + selected = currentMode == AppMockMode.BLACKLIST, + onClick = { onModeChange(AppMockMode.BLACKLIST) }, + shape = SegmentedButtonDefaults.itemShape(index = 1, count = 3) + ) { + Text( + text = stringResource(id = R.string.apps_mode_blacklist), + style = MaterialTheme.typography.labelMedium + ) + } + + SegmentedButton( + selected = currentMode == AppMockMode.WHITELIST, + onClick = { onModeChange(AppMockMode.WHITELIST) }, + shape = SegmentedButtonDefaults.itemShape(index = 2, count = 3) + ) { + Text( + text = stringResource(id = R.string.apps_mode_whitelist), + style = MaterialTheme.typography.labelMedium + ) + } + } + + Spacer(modifier = Modifier.height(8.dp)) + + // 当前模式说明提示 + val modeDesc = when (currentMode) { + AppMockMode.GLOBAL -> stringResource(id = R.string.apps_mode_global_desc) + AppMockMode.BLACKLIST -> stringResource(id = R.string.apps_mode_blacklist_desc) + AppMockMode.WHITELIST -> stringResource(id = R.string.apps_mode_whitelist_desc) + } + Text( + text = modeDesc, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp) + ) + + Spacer(modifier = Modifier.height(14.dp)) + HorizontalDivider( + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) + ) + Spacer(modifier = Modifier.height(8.dp)) + + // 黑名单列表入口 + AppScopeListEntry( + icon = Icons.Outlined.Block, + title = stringResource(id = R.string.apps_blacklist_title), + subtitle = stringResource(id = R.string.apps_blacklist_subtitle, blacklistCount), + onClick = onOpenBlacklist, + isHighlighted = currentMode == AppMockMode.BLACKLIST + ) + + Spacer(modifier = Modifier.height(6.dp)) + + // 白名单列表入口 + AppScopeListEntry( + icon = Icons.Outlined.CheckCircleOutline, + title = stringResource(id = R.string.apps_whitelist_title), + subtitle = stringResource(id = R.string.apps_whitelist_subtitle, whitelistCount), + onClick = onOpenWhitelist, + isHighlighted = currentMode == AppMockMode.WHITELIST + ) + } + } +} + +/** + * 黑/白名单列表条目入口 + */ +@Composable +private fun AppScopeListEntry( + icon: ImageVector, + title: String, + subtitle: String, + onClick: () -> Unit, + isHighlighted: Boolean, + modifier: Modifier = Modifier +) { + Surface( + onClick = onClick, + shape = RoundedCornerShape(12.dp), + color = if (isHighlighted) { + MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.35f) + } else { + MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.25f) + }, + modifier = modifier.fillMaxWidth() + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 14.dp, vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Row( + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = icon, + contentDescription = null, + tint = if (isHighlighted) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + modifier = Modifier.size(22.dp) + ) + + Spacer(modifier = Modifier.width(12.dp)) + + Column { + Text( + text = title, + style = MaterialTheme.typography.bodyMedium.copy( + fontWeight = FontWeight.SemiBold + ), + color = MaterialTheme.colorScheme.onSurface + ) + Text( + text = subtitle, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + Icon( + imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f), + modifier = Modifier.size(20.dp) + ) + } + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/ui/screens/home/HomeScreen.kt b/app/src/main/java/com/lzxnone/openloc/ui/screens/home/HomeScreen.kt new file mode 100644 index 0000000..b2abdad --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/ui/screens/home/HomeScreen.kt @@ -0,0 +1,64 @@ +package com.lzxnone.openloc.ui.screens.home + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp + +import com.lzxnone.openloc.data.preference.AppPreferences + +/** + * 主页 Screen + */ +@Composable +fun HomeScreen( + isModuleActive: Boolean, + isServiceEnabled: Boolean, + onServiceEnabledChange: (Boolean) -> Unit, + onOpenBlacklist: () -> Unit, + onOpenWhitelist: () -> Unit, + modifier: Modifier = Modifier +) { + val scrollState = rememberScrollState() + + Column( + modifier = modifier + .fillMaxSize() + .verticalScroll(scrollState) + .padding(horizontal = 16.dp, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + // 1. 模块激活状态卡片(根据激活/未激活显示绿/红纯净状态) + ModuleStatusCard( + isModuleActive = isModuleActive + ) + + // 2. 虚拟定位总开关卡片(未激活时禁用) + ServiceSwitchCard( + isModuleActive = isModuleActive, + isServiceEnabled = isServiceEnabled, + onServiceEnabledChange = onServiceEnabledChange + ) + + // 3. 应用作用域管理卡片(全局 / 黑名单 / 白名单) + AppManagementCard( + currentMode = AppPreferences.appMockMode, + onModeChange = { AppPreferences.updateAppMockMode(it) }, + blacklistCount = AppPreferences.blacklistApps.size, + whitelistCount = AppPreferences.whitelistApps.size, + onOpenBlacklist = onOpenBlacklist, + onOpenWhitelist = onOpenWhitelist + ) + + // 4. 版本与更新模块卡片 + VersionCard( + versionName = "v1.0.0" + ) + } +} + diff --git a/app/src/main/java/com/lzxnone/openloc/ui/screens/home/ModuleStatusCard.kt b/app/src/main/java/com/lzxnone/openloc/ui/screens/home/ModuleStatusCard.kt new file mode 100644 index 0000000..297deb4 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/ui/screens/home/ModuleStatusCard.kt @@ -0,0 +1,101 @@ +package com.lzxnone.openloc.ui.screens.home + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Cancel +import androidx.compose.material.icons.filled.CheckCircle +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.lzxnone.openloc.R + +/** + * 模块状态卡片:仅展示“已激活”或“未激活”,根据状态展示鲜明颜色(绿/红) + */ +@Composable +fun ModuleStatusCard( + isModuleActive: Boolean, + modifier: Modifier = Modifier +) { + val isDark = MaterialTheme.colorScheme.surface.red < 0.5f + + // 激活对应绿色,未激活对应红色 + val statusColor = if (isModuleActive) { + if (isDark) Color(0xFF81C784) else Color(0xFF2E7D32) + } else { + if (isDark) Color(0xFFEF5350) else Color(0xFFC62828) + } + + val cardBgColor = if (isModuleActive) { + if (isDark) Color(0xFF142E18) else Color(0xFFE8F5E9) + } else { + if (isDark) Color(0xFF331616) else Color(0xFFFFEBEE) + } + + Card( + modifier = modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + colors = CardDefaults.cardColors( + containerColor = cardBgColor + ), + elevation = CardDefaults.cardElevation( + defaultElevation = 0.dp + ) + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 20.dp, vertical = 18.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.Start + ) { + Box( + modifier = Modifier + .size(44.dp) + .clip(CircleShape) + .background(statusColor.copy(alpha = 0.18f)), + contentAlignment = Alignment.Center + ) { + Icon( + imageVector = if (isModuleActive) Icons.Filled.CheckCircle else Icons.Filled.Cancel, + contentDescription = null, + tint = statusColor, + modifier = Modifier.size(28.dp) + ) + } + + Spacer(modifier = Modifier.width(16.dp)) + + Text( + text = stringResource( + id = if (isModuleActive) R.string.module_status_activated + else R.string.module_status_inactive + ), + style = MaterialTheme.typography.titleLarge.copy( + fontWeight = FontWeight.Bold + ), + color = statusColor + ) + } + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/ui/screens/home/ServiceSwitchCard.kt b/app/src/main/java/com/lzxnone/openloc/ui/screens/home/ServiceSwitchCard.kt new file mode 100644 index 0000000..17cc373 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/ui/screens/home/ServiceSwitchCard.kt @@ -0,0 +1,106 @@ +package com.lzxnone.openloc.ui.screens.home + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Switch +import androidx.compose.material3.SwitchDefaults +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.lzxnone.openloc.R + +/** + * 虚拟定位总开关独立卡片 + * - 未激活时:禁用 Switch,并提示未激活 + * - 激活时:允许用户自由启停服务 + */ +@Composable +fun ServiceSwitchCard( + isModuleActive: Boolean, + isServiceEnabled: Boolean, + onServiceEnabledChange: (Boolean) -> Unit, + modifier: Modifier = Modifier +) { + Card( + modifier = modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surface + ), + elevation = CardDefaults.cardElevation( + defaultElevation = 1.dp + ) + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 20.dp, vertical = 18.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Column( + modifier = Modifier.weight(1f) + ) { + Text( + text = stringResource(id = R.string.service_switch_title), + style = MaterialTheme.typography.titleMedium.copy( + fontWeight = FontWeight.SemiBold + ), + color = if (isModuleActive) { + MaterialTheme.colorScheme.onSurface + } else { + MaterialTheme.colorScheme.onSurface.copy(alpha = 0.5f) + } + ) + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = stringResource( + id = if (!isModuleActive) { + R.string.service_switch_disabled_hint + } else if (isServiceEnabled) { + R.string.service_switch_desc_enabled + } else { + R.string.service_switch_desc_disabled + } + ), + style = MaterialTheme.typography.bodySmall, + color = if (!isModuleActive) { + MaterialTheme.colorScheme.error.copy(alpha = 0.7f) + } else if (isServiceEnabled) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.onSurfaceVariant + } + ) + } + + Spacer(modifier = Modifier.width(16.dp)) + + Switch( + checked = isServiceEnabled && isModuleActive, + onCheckedChange = { if (isModuleActive) onServiceEnabledChange(it) }, + enabled = isModuleActive, + colors = SwitchDefaults.colors( + checkedThumbColor = MaterialTheme.colorScheme.onPrimary, + checkedTrackColor = MaterialTheme.colorScheme.primary, + uncheckedThumbColor = MaterialTheme.colorScheme.outline, + uncheckedTrackColor = MaterialTheme.colorScheme.surfaceVariant + ) + ) + } + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/ui/screens/home/VersionCard.kt b/app/src/main/java/com/lzxnone/openloc/ui/screens/home/VersionCard.kt new file mode 100644 index 0000000..d81ccbe --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/ui/screens/home/VersionCard.kt @@ -0,0 +1,135 @@ +package com.lzxnone.openloc.ui.screens.home + +import android.widget.Toast +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Info +import androidx.compose.material.icons.outlined.Refresh +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.lzxnone.openloc.R + +/** + * 主页底部版本模块卡片 + * 显示应用当前版本(如 v1.0.0)与“检查更新”按钮 + */ +@Composable +fun VersionCard( + versionName: String = stringResource(id = R.string.home_version_name), + onCheckUpdate: (() -> Unit)? = null, + modifier: Modifier = Modifier +) { + val context = LocalContext.current + val placeholderToast = stringResource(id = R.string.home_check_updates_placeholder) + + Card( + modifier = modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surface + ), + elevation = CardDefaults.cardElevation( + defaultElevation = 1.dp + ) + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 20.dp, vertical = 16.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.weight(1f) + ) { + Surface( + shape = CircleShape, + color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.5f), + modifier = Modifier.size(40.dp) + ) { + Box(contentAlignment = Alignment.Center) { + Icon( + imageVector = Icons.Outlined.Info, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(22.dp) + ) + } + } + + Spacer(modifier = Modifier.width(14.dp)) + + Column { + Text( + text = stringResource(id = R.string.home_version_card_title), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(modifier = Modifier.height(2.dp)) + Text( + text = versionName, + style = MaterialTheme.typography.titleMedium.copy( + fontWeight = FontWeight.Bold + ), + color = MaterialTheme.colorScheme.onSurface + ) + } + } + + Spacer(modifier = Modifier.width(12.dp)) + + FilledTonalButton( + onClick = { + if (onCheckUpdate != null) { + onCheckUpdate() + } else { + Toast.makeText(context, placeholderToast, Toast.LENGTH_SHORT).show() + } + }, + shape = RoundedCornerShape(12.dp), + colors = ButtonDefaults.filledTonalButtonColors( + containerColor = MaterialTheme.colorScheme.secondaryContainer, + contentColor = MaterialTheme.colorScheme.onSecondaryContainer + ) + ) { + Icon( + imageVector = Icons.Outlined.Refresh, + contentDescription = null, + modifier = Modifier.size(16.dp) + ) + Spacer(modifier = Modifier.width(6.dp)) + Text( + text = stringResource(id = R.string.home_check_updates_btn), + style = MaterialTheme.typography.labelLarge.copy( + fontWeight = FontWeight.Medium + ) + ) + } + } + } +} diff --git a/app/src/main/java/com/lzxnone/openloc/ui/screens/location/LocationScreen.kt b/app/src/main/java/com/lzxnone/openloc/ui/screens/location/LocationScreen.kt new file mode 100644 index 0000000..0fee1c9 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/ui/screens/location/LocationScreen.kt @@ -0,0 +1,1389 @@ +package com.lzxnone.openloc.ui.screens.location + +import android.Manifest +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.content.pm.PackageManager +import android.location.Location +import android.location.LocationListener +import android.location.LocationManager +import android.os.Bundle +import android.os.Looper +import android.widget.Toast +import androidx.activity.compose.BackHandler +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.animateContentSize +import androidx.compose.animation.expandVertically +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.shrinkVertically +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Bookmark +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.ContentCopy +import androidx.compose.material.icons.filled.DeleteOutline +import androidx.compose.material.icons.filled.ErrorOutline +import androidx.compose.material.icons.filled.History +import androidx.compose.material.icons.filled.KeyboardArrowDown +import androidx.compose.material.icons.filled.KeyboardArrowUp +import androidx.compose.material.icons.filled.Key +import androidx.compose.material.icons.filled.LocationOn +import androidx.compose.material.icons.filled.MyLocation +import androidx.compose.material.icons.filled.Public +import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.filled.Tune +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.FilledTonalIconButton +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.IconButtonDefaults +import androidx.compose.material3.ListItem +import androidx.compose.material3.ListItemDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.OutlinedTextFieldDefaults +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import com.lzxnone.openloc.LocalizedDialogContent +import com.lzxnone.openloc.data.preference.SearchProvider +import com.lzxnone.openloc.ui.screens.favorites.FavoritesScreen +import kotlinx.coroutines.launch +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableDoubleStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalSoftwareKeyboardController +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.unit.dp +import androidx.compose.ui.viewinterop.AndroidView +import androidx.core.content.ContextCompat +import com.lzxnone.openloc.R +import com.lzxnone.openloc.core.util.CoordinateConverter +import com.lzxnone.openloc.core.util.LocationResolver +import com.lzxnone.openloc.core.util.SearchResult +import com.lzxnone.openloc.data.preference.AppPreferences +import kotlinx.coroutines.delay +import org.osmdroid.config.Configuration +import org.osmdroid.events.MapEventsReceiver +import org.osmdroid.tileprovider.tilesource.OnlineTileSourceBase +import org.osmdroid.util.GeoPoint +import org.osmdroid.util.MapTileIndex +import org.osmdroid.views.CustomZoomButtonsController +import org.osmdroid.views.MapView +import org.osmdroid.views.overlay.MapEventsOverlay +import org.osmdroid.views.overlay.Marker +import java.util.Locale +import kotlin.math.roundToInt + +/** + * 国内极速免 Key 高德瓦片源 + */ +val AMapVectorTileSource = object : OnlineTileSourceBase( + "AMap-Vector", + 3, 19, 256, ".png", + arrayOf( + "https://wprd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&", + "https://wprd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&", + "https://wprd03.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&", + "https://wprd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&" + ) +) { + override fun getTileURLString(pMapTileIndex: Long): String { + return baseUrl + "x=" + MapTileIndex.getX(pMapTileIndex) + + "&y=" + MapTileIndex.getY(pMapTileIndex) + + "&z=" + MapTileIndex.getZoom(pMapTileIndex) + } +} + +/** + * 虚拟定位地图页面 + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun LocationScreen( + modifier: Modifier = Modifier +) { + val context = LocalContext.current + val keyboardController = LocalSoftwareKeyboardController.current + val coroutineScope = rememberCoroutineScope() + + var isSearchActive by rememberSaveable { mutableStateOf(false) } + var searchQuery by rememberSaveable { mutableStateOf("") } + var isSearching by remember { mutableStateOf(false) } + var searchResults by remember { mutableStateOf>(emptyList()) } + var searchErrorMessage by remember { mutableStateOf(null) } + var showApiKeyDialog by remember { mutableStateOf(false) } + var showSearchProviderSheet by remember { mutableStateOf(false) } + val searchProviderSheetState = rememberModalBottomSheetState() + val focusRequester = remember { FocusRequester() } + val searchHistory = AppPreferences.searchHistory + + var currentGeoPoint by remember { + val gcj = CoordinateConverter.wgs84ToGcj02(AppPreferences.mockLatitude, AppPreferences.mockLongitude) + mutableStateOf(GeoPoint(gcj[0], gcj[1])) + } + var currentZoom by remember { mutableDoubleStateOf(15.0) } + var locationName by remember { mutableStateOf(AppPreferences.mockLocationName) } + var isCardCollapsed by rememberSaveable { mutableStateOf(false) } + var showFavoritesScreen by rememberSaveable { mutableStateOf(false) } + + var mapViewRef by remember { mutableStateOf(null) } + var currentMarker by remember { mutableStateOf(null) } + + // 初始化 OSMDroid 配置(强制指定内部私有目录,避免外置存储权限异常) + DisposableEffect(Unit) { + val basePath = java.io.File(context.cacheDir, "osmdroid") + Configuration.getInstance().osmdroidBasePath = basePath + Configuration.getInstance().osmdroidTileCache = java.io.File(basePath, "tiles") + Configuration.getInstance().userAgentValue = context.packageName + onDispose { + mapViewRef?.onDetach() + } + } + + // 搜索输入防抖监听 (400ms,感知搜索引擎和各Key的变化) + LaunchedEffect( + searchQuery, + AppPreferences.searchProvider, + AppPreferences.amapApiKey, + AppPreferences.baiduApiKey + ) { + if (searchQuery.isBlank()) { + searchResults = emptyList() + searchErrorMessage = null + isSearching = false + } else { + isSearching = true + delay(400) + val response = LocationResolver.searchPlaces(context, searchQuery) + searchResults = response.results + searchErrorMessage = response.errorMessage + isSearching = false + } + } + + // 展开搜索时自动获得输入焦点 + LaunchedEffect(isSearchActive) { + if (isSearchActive) { + focusRequester.requestFocus() + } + } + + // 系统返回手势/按键拦截:展开搜索时收起搜索层 + BackHandler(enabled = isSearchActive) { + isSearchActive = false + keyboardController?.hide() + } + + // 更新定位并异步解析地名 + // pointOnMap: 地图上的火星坐标 (GCJ-02) + // centerMap: 是否强制移动地图视野中心(点击地图时设为 false,不强制拉拽视野) + fun updatePositionAndResolveName( + pointOnMap: GeoPoint, + isUserManual: Boolean, + centerMap: Boolean = false, + animate: Boolean = false + ) { + currentGeoPoint = pointOnMap + currentMarker?.position = pointOnMap + if (centerMap) { + if (animate) { + mapViewRef?.controller?.animateTo(pointOnMap) + } else { + mapViewRef?.controller?.setCenter(pointOnMap) + } + } + mapViewRef?.invalidate() + + // 高德底图上的坐标是 GCJ-02(火星坐标系),需转换为国际标准 WGS-84 写入系统模拟位置 + // 从而彻底杜绝百度地图、微信等第三方应用在读取系统 GPS 时发生二次加偏(消除几百米偏差) + val wgs = CoordinateConverter.gcj02ToWgs84(pointOnMap.latitude, pointOnMap.longitude) + val wgsLat = wgs[0] + val wgsLng = wgs[1] + + val coordFallback = String.format(Locale.getDefault(), "%.5f, %.5f", wgsLat, wgsLng) + locationName = coordFallback + AppPreferences.updateMockLocation(wgsLat, wgsLng, name = coordFallback, isUserManual = isUserManual) + + coroutineScope.launch { + val resolvedName = LocationResolver.resolveLocationName(context, wgsLat, wgsLng) + locationName = resolvedName + currentMarker?.title = resolvedName + AppPreferences.updateMockLocation(wgsLat, wgsLng, name = resolvedName, isUserManual = isUserManual) + } + } + + // 选择搜索结果地点 + fun selectSearchResult(result: SearchResult) { + AppPreferences.addSearchHistory(result) + isSearchActive = false + keyboardController?.hide() + + // 搜索结果的经纬度是国际 WGS-84 标准,转为 GCJ-02 对应高德地图的像素位置 + val gcj = CoordinateConverter.wgs84ToGcj02(result.latitude, result.longitude) + val mapPoint = GeoPoint(gcj[0], gcj[1]) + + currentGeoPoint = mapPoint + currentMarker?.position = mapPoint + mapViewRef?.controller?.animateTo(mapPoint) + mapViewRef?.invalidate() + + locationName = result.name + currentMarker?.title = result.name + AppPreferences.updateMockLocation(result.latitude, result.longitude, name = result.name, isUserManual = true) + } + + // 定位到设备当前真实物理位置逻辑(例如在武汉则精确定位到武汉) + fun locateToDeviceRealPosition(animate: Boolean = true) { + val lm = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return + val hasFine = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED + val hasCoarse = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED + + if (hasFine || hasCoarse) { + val gpsLoc = try { lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) } catch (_: SecurityException) { null } + val netLoc = try { lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER) } catch (_: SecurityException) { null } + + val bestLoc = when { + gpsLoc != null && netLoc != null -> if (gpsLoc.time > netLoc.time) gpsLoc else netLoc + gpsLoc != null -> gpsLoc + netLoc != null -> netLoc + else -> null + } + + if (bestLoc != null) { + // 真实硬件 GPS 返回 WGS-84,转换为 GCJ-02 精准标在高德瓦片上 + val gcj = CoordinateConverter.wgs84ToGcj02(bestLoc.latitude, bestLoc.longitude) + updatePositionAndResolveName( + pointOnMap = GeoPoint(gcj[0], gcj[1]), + isUserManual = false, + centerMap = true, + animate = animate + ) + } + + // 异步刷新获取最新单次定位 + try { + if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) { + lm.getCurrentLocation( + LocationManager.NETWORK_PROVIDER, + null, + context.mainExecutor + ) { loc -> + if (loc != null) { + val gcj = CoordinateConverter.wgs84ToGcj02(loc.latitude, loc.longitude) + updatePositionAndResolveName( + pointOnMap = GeoPoint(gcj[0], gcj[1]), + isUserManual = false, + centerMap = true, + animate = true + ) + } + } + } else { + @Suppress("DEPRECATION") + val singleListener = object : LocationListener { + override fun onLocationChanged(loc: Location) { + val gcj = CoordinateConverter.wgs84ToGcj02(loc.latitude, loc.longitude) + updatePositionAndResolveName( + pointOnMap = GeoPoint(gcj[0], gcj[1]), + isUserManual = false, + centerMap = true, + animate = true + ) + try { lm.removeUpdates(this) } catch (_: Throwable) {} + } + override fun onProviderDisabled(p: String) {} + override fun onProviderEnabled(p: String) {} + override fun onStatusChanged(p: String?, s: Int, e: Bundle?) {} + } + + if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { + @Suppress("DEPRECATION") + lm.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, singleListener, Looper.getMainLooper()) + } + } + } catch (_: SecurityException) {} + } + } + + // 权限请求器(仅在用户点击“回到原位”按钮时按需触发) + val permissionLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.RequestMultiplePermissions() + ) { permissions -> + val granted = permissions[Manifest.permission.ACCESS_FINE_LOCATION] == true || + permissions[Manifest.permission.ACCESS_COARSE_LOCATION] == true + if (granted) { + locateToDeviceRealPosition(animate = true) + } + } + + Box( + modifier = modifier.fillMaxSize() + ) { + // ------------------ 1. 地图底层视图 (OSMDroid) ------------------ + AndroidView( + factory = { ctx -> + MapView(ctx).apply { + setTileSource(AMapVectorTileSource) + setMultiTouchControls(true) + zoomController.setVisibility(CustomZoomButtonsController.Visibility.NEVER) + + controller.setZoom(currentZoom) + controller.setCenter(currentGeoPoint) + + // 标记点 Marker + val marker = Marker(this).apply { + position = currentGeoPoint + setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM) + title = locationName.ifEmpty { ctx.getString(R.string.location_default_name) } + } + overlays.add(marker) + currentMarker = marker + + // 点击即移动位置(无需确认) + val tapOverlay = MapEventsOverlay(object : MapEventsReceiver { + override fun singleTapConfirmedHelper(p: GeoPoint): Boolean { + // 点击地图位置时,只移动标记,不把点击位置强制作为视图中心 + updatePositionAndResolveName( + pointOnMap = p, + isUserManual = true, + centerMap = false, + animate = false + ) + return true + } + + override fun longPressHelper(p: GeoPoint): Boolean = false + }) + overlays.add(tapOverlay) + + mapViewRef = this + } + }, + modifier = Modifier.fillMaxSize(), + update = { mapView -> + currentMarker?.position = currentGeoPoint + mapView.invalidate() + } + ) + + // ------------------ 2. 顶部未激活时的浮动搜索胶囊 ------------------ + Surface( + modifier = Modifier + .fillMaxWidth() + .align(Alignment.TopCenter) + .statusBarsPadding() + .padding(horizontal = 16.dp, vertical = 12.dp) + .clickable { + isSearchActive = true + }, + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.surface.copy(alpha = 0.95f), + shadowElevation = 4.dp + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp) + ) { + Icon( + imageVector = Icons.Filled.Search, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary + ) + Spacer(modifier = Modifier.width(12.dp)) + Text( + text = searchQuery.ifEmpty { stringResource(id = R.string.location_search_hint) }, + style = MaterialTheme.typography.bodyMedium, + color = if (searchQuery.isEmpty()) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.onSurface + ) + } + } + + // ------------------ 3. 搜索栏下方靠右:回到原位与收藏夹按钮 ------------------ + Row( + modifier = Modifier + .align(Alignment.TopEnd) + .statusBarsPadding() + .padding(top = 76.dp, end = 16.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + // 回到原位 (定位当前位置) + FilledTonalIconButton( + onClick = { + val hasFine = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED + val hasCoarse = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED + if (hasFine || hasCoarse) { + locateToDeviceRealPosition(animate = true) + } else { + permissionLauncher.launch( + arrayOf( + Manifest.permission.ACCESS_FINE_LOCATION, + Manifest.permission.ACCESS_COARSE_LOCATION + ) + ) + } + }, + shape = CircleShape, + colors = IconButtonDefaults.filledTonalIconButtonColors( + containerColor = MaterialTheme.colorScheme.surface.copy(alpha = 0.95f), + contentColor = MaterialTheme.colorScheme.primary + ), + modifier = Modifier.size(44.dp) + ) { + Icon( + imageVector = Icons.Filled.MyLocation, + contentDescription = stringResource(id = R.string.location_reset_current), + modifier = Modifier.size(22.dp) + ) + } + + // 收藏夹按钮(位于定位当前位置按钮右方) + FilledTonalIconButton( + onClick = { showFavoritesScreen = true }, + shape = CircleShape, + colors = IconButtonDefaults.filledTonalIconButtonColors( + containerColor = MaterialTheme.colorScheme.surface.copy(alpha = 0.95f), + contentColor = MaterialTheme.colorScheme.primary + ), + modifier = Modifier.size(44.dp) + ) { + Icon( + imageVector = Icons.Filled.Bookmark, + contentDescription = stringResource(id = R.string.favorites_title), + modifier = Modifier.size(22.dp) + ) + } + } + + // ------------------ 4. 屏幕下方浮动:地点介绍卡片 ------------------ + Card( + modifier = Modifier + .fillMaxWidth() + .align(Alignment.BottomCenter) + .padding(horizontal = 16.dp, vertical = 14.dp) + .animateContentSize(), + shape = RoundedCornerShape(20.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surface.copy(alpha = 0.96f) + ), + elevation = CardDefaults.cardElevation(defaultElevation = 4.dp) + ) { + Column( + modifier = Modifier.padding( + start = 18.dp, + end = 12.dp, + top = if (isCardCollapsed) 10.dp else 14.dp, + bottom = if (isCardCollapsed) 10.dp else 16.dp + ) + ) { + // 地点名称与右上角折叠/展开按钮(同行) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = if (isCardCollapsed) Alignment.CenterVertically else Alignment.Top + ) { + Text( + text = locationName.ifEmpty { stringResource(id = R.string.location_default_name) }, + style = MaterialTheme.typography.titleMedium.copy( + fontWeight = FontWeight.Bold + ), + color = MaterialTheme.colorScheme.onSurface, + maxLines = if (isCardCollapsed) 1 else Int.MAX_VALUE, + overflow = if (isCardCollapsed) TextOverflow.Ellipsis else TextOverflow.Clip, + modifier = Modifier + .weight(1f) + .padding(end = 8.dp) + ) + + IconButton( + onClick = { isCardCollapsed = !isCardCollapsed }, + modifier = Modifier.size(36.dp) + ) { + Icon( + imageVector = if (isCardCollapsed) Icons.Filled.KeyboardArrowUp else Icons.Filled.KeyboardArrowDown, + contentDescription = stringResource( + id = if (isCardCollapsed) R.string.location_card_expand else R.string.location_card_collapse + ), + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + // 经纬度信息与复制按钮 (折叠时隐藏) + AnimatedVisibility( + visible = !isCardCollapsed, + enter = expandVertically() + fadeIn(), + exit = shrinkVertically() + fadeOut() + ) { + Column( + modifier = Modifier.padding(end = 6.dp) + ) { + Spacer(modifier = Modifier.height(8.dp)) + + // 经纬度信息与复制按钮 (展示与复制国际标准 WGS-84 坐标,即注入模拟系统的真实坐标) + val wgsCoords = remember(currentGeoPoint) { + CoordinateConverter.gcj02ToWgs84(currentGeoPoint.latitude, currentGeoPoint.longitude) + } + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column { + Text( + text = stringResource(id = R.string.location_latitude_format, wgsCoords[0]), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(modifier = Modifier.height(2.dp)) + Text( + text = stringResource(id = R.string.location_longitude_format, wgsCoords[1]), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + FilledTonalButton( + onClick = { + val coordsText = "${wgsCoords[0]}, ${wgsCoords[1]}" + copyToClipboard(context, coordsText) + Toast.makeText( + context, + context.getString(R.string.location_coords_copied), + Toast.LENGTH_SHORT + ).show() + }, + shape = RoundedCornerShape(12.dp), + contentPadding = PaddingValues(horizontal = 14.dp, vertical = 8.dp) + ) { + Icon( + imageVector = Icons.Filled.ContentCopy, + contentDescription = null, + modifier = Modifier.size(16.dp) + ) + Spacer(modifier = Modifier.width(6.dp)) + Text( + text = stringResource(id = R.string.location_copy_coords), + style = MaterialTheme.typography.labelMedium.copy( + fontWeight = FontWeight.SemiBold + ) + ) + } + } + } + } + } + } + + // ------------------ 5. 点击搜索栏后展开的完整覆盖视图 (完全遮住地图与按钮) ------------------ + AnimatedVisibility( + visible = isSearchActive, + enter = fadeIn(), + exit = fadeOut(), + modifier = Modifier.fillMaxSize() + ) { + Surface( + modifier = Modifier + .fillMaxSize() + .statusBarsPadding(), + color = MaterialTheme.colorScheme.surface + ) { + Column( + modifier = Modifier.fillMaxSize() + ) { + // 顶栏:返回键 + 搜索输入框 + 状态图标(加载/清除) + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 8.dp, vertical = 8.dp) + ) { + IconButton( + onClick = { + isSearchActive = false + keyboardController?.hide() + } + ) { + Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(id = R.string.location_search_back), + tint = MaterialTheme.colorScheme.onSurface + ) + } + + OutlinedTextField( + value = searchQuery, + onValueChange = { searchQuery = it }, + placeholder = { + Text( + text = stringResource(id = R.string.location_search_hint), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + }, + singleLine = true, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), + keyboardActions = KeyboardActions( + onSearch = { + keyboardController?.hide() + if (searchResults.isNotEmpty()) { + selectSearchResult(searchResults[0]) + } + } + ), + trailingIcon = { + if (isSearching) { + CircularProgressIndicator( + modifier = Modifier.size(18.dp), + strokeWidth = 2.dp, + color = MaterialTheme.colorScheme.primary + ) + } else if (searchQuery.isNotEmpty()) { + IconButton( + onClick = { + searchQuery = "" + searchResults = emptyList() + } + ) { + Icon( + imageVector = Icons.Filled.Close, + contentDescription = stringResource(id = R.string.location_search_clear), + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + }, + shape = RoundedCornerShape(16.dp), + colors = OutlinedTextFieldDefaults.colors( + focusedBorderColor = MaterialTheme.colorScheme.primary, + unfocusedBorderColor = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f), + focusedContainerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f), + unfocusedContainerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.2f) + ), + modifier = Modifier + .weight(1f) + .padding(end = 8.dp) + .focusRequester(focusRequester) + ) + } + + HorizontalDivider( + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.3f) + ) + + // 搜索内容区 + Box( + modifier = Modifier + .fillMaxWidth() + .weight(1f) + ) { + if (searchQuery.isBlank()) { + // 状态 A: 搜索历史与引导 + Column(modifier = Modifier.fillMaxSize()) { + // 如果当前引擎需要 Key 且尚未配置,展示引导条 + val currentProvider = AppPreferences.searchProvider + if (currentProvider.requiresKey && AppPreferences.getCurrentProviderKey().isBlank()) { + Surface( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp) + .clickable { showApiKeyDialog = true }, + shape = RoundedCornerShape(12.dp), + color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.45f) + ) { + Row( + modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Filled.Key, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(18.dp) + ) + Spacer(modifier = Modifier.width(10.dp)) + Text( + text = stringResource(id = R.string.search_no_api_key_desc_dynamic), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onPrimaryContainer, + modifier = Modifier.weight(1f) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = stringResource(id = R.string.search_configure_key_button), + style = MaterialTheme.typography.labelMedium.copy(fontWeight = FontWeight.Bold), + color = MaterialTheme.colorScheme.primary + ) + } + } + } + + if (searchHistory.isNotEmpty()) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = stringResource(id = R.string.location_search_history), + style = MaterialTheme.typography.titleSmall.copy( + fontWeight = FontWeight.Bold + ), + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + TextButton( + onClick = { AppPreferences.clearSearchHistory() }, + contentPadding = PaddingValues(horizontal = 8.dp, vertical = 2.dp) + ) { + Icon( + imageVector = Icons.Filled.DeleteOutline, + contentDescription = null, + modifier = Modifier.size(16.dp) + ) + Spacer(modifier = Modifier.width(4.dp)) + Text( + text = stringResource(id = R.string.location_search_clear_history), + style = MaterialTheme.typography.labelMedium + ) + } + } + + LazyColumn(modifier = Modifier.fillMaxSize()) { + items(searchHistory, key = { "${it.name}_${it.latitude}_${it.longitude}" }) { item -> + ListItem( + headlineContent = { + Text( + text = item.name, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface + ) + }, + supportingContent = { + Text( + text = item.address, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + }, + leadingContent = { + Icon( + imageVector = Icons.Filled.History, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + }, + trailingContent = { + IconButton( + onClick = { AppPreferences.removeSearchHistory(item) } + ) { + Icon( + imageVector = Icons.Filled.Close, + contentDescription = null, + modifier = Modifier.size(16.dp), + tint = MaterialTheme.colorScheme.outline + ) + } + }, + colors = ListItemDefaults.colors(containerColor = MaterialTheme.colorScheme.surface), + modifier = Modifier.clickable { selectSearchResult(item) } + ) + HorizontalDivider( + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.2f), + modifier = Modifier.padding(horizontal = 16.dp) + ) + } + } + } else { + // 无历史记录时的引导提示 + Column( + modifier = Modifier + .fillMaxSize() + .padding(32.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + Icon( + imageVector = Icons.Filled.Search, + contentDescription = null, + modifier = Modifier.size(56.dp), + tint = MaterialTheme.colorScheme.outlineVariant + ) + Spacer(modifier = Modifier.height(16.dp)) + Text( + text = stringResource(id = R.string.location_search_empty_hint), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } + } else { + // 状态 B: 搜索结果展示与错误提示 + val currentProvider = AppPreferences.searchProvider + if (searchErrorMessage == "NO_API_KEY") { + // 未配置 API Key 时的提示面板 + Card( + modifier = Modifier + .fillMaxWidth() + .padding(24.dp), + shape = RoundedCornerShape(20.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f) + ) + ) { + Column( + modifier = Modifier.padding(24.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Icon( + imageVector = Icons.Filled.Key, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(44.dp) + ) + Spacer(modifier = Modifier.height(12.dp)) + Text( + text = stringResource(id = R.string.search_no_api_key_title_dynamic, stringResource(id = currentProvider.titleRes)), + style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), + color = MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.height(8.dp)) + Text( + text = stringResource(id = R.string.search_no_api_key_desc_dynamic), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center + ) + Spacer(modifier = Modifier.height(18.dp)) + Row( + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Button( + onClick = { showApiKeyDialog = true }, + shape = RoundedCornerShape(12.dp) + ) { + Icon(Icons.Filled.Key, contentDescription = null, modifier = Modifier.size(16.dp)) + Spacer(modifier = Modifier.width(6.dp)) + Text(stringResource(id = R.string.search_configure_key_button)) + } + FilledTonalButton( + onClick = { showSearchProviderSheet = true }, + shape = RoundedCornerShape(12.dp) + ) { + Icon(Icons.Filled.Public, contentDescription = null, modifier = Modifier.size(16.dp)) + Spacer(modifier = Modifier.width(6.dp)) + Text(stringResource(id = R.string.search_switch_provider_button)) + } + } + } + } + } else if (searchErrorMessage?.startsWith("KEY_INVALID") == true) { + // Key 无效或超额时的提示面板 + Card( + modifier = Modifier + .fillMaxWidth() + .padding(24.dp), + shape = RoundedCornerShape(20.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.35f) + ) + ) { + Column( + modifier = Modifier.padding(24.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Icon( + imageVector = Icons.Filled.ErrorOutline, + contentDescription = null, + tint = MaterialTheme.colorScheme.error, + modifier = Modifier.size(44.dp) + ) + Spacer(modifier = Modifier.height(12.dp)) + Text( + text = stringResource(id = R.string.search_key_invalid_title_dynamic, stringResource(id = currentProvider.titleRes)), + style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), + color = MaterialTheme.colorScheme.error + ) + Spacer(modifier = Modifier.height(8.dp)) + Text( + text = stringResource( + id = R.string.search_key_invalid_desc, + searchErrorMessage?.removePrefix("KEY_INVALID:")?.trim() ?: "" + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onErrorContainer, + textAlign = TextAlign.Center + ) + Spacer(modifier = Modifier.height(18.dp)) + Row( + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalAlignment = Alignment.CenterVertically + ) { + FilledTonalButton( + onClick = { showApiKeyDialog = true }, + shape = RoundedCornerShape(12.dp) + ) { + Text(stringResource(id = R.string.search_edit_key_button)) + } + Button( + onClick = { showSearchProviderSheet = true }, + shape = RoundedCornerShape(12.dp) + ) { + Text(stringResource(id = R.string.search_switch_provider_button)) + } + } + } + } + } else if (searchErrorMessage?.startsWith("NETWORK_ERROR") == true || searchErrorMessage?.startsWith("HTTP_ERROR") == true) { + Column( + modifier = Modifier + .fillMaxSize() + .padding(32.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + Text( + text = stringResource(id = R.string.search_network_error), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } else if (isSearching && searchResults.isEmpty()) { + Column( + modifier = Modifier + .fillMaxSize() + .padding(32.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + CircularProgressIndicator( + modifier = Modifier.size(36.dp), + color = MaterialTheme.colorScheme.primary + ) + } + } else if (!isSearching && searchResults.isEmpty()) { + Column( + modifier = Modifier + .fillMaxSize() + .padding(32.dp), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center + ) { + Text( + text = stringResource(id = R.string.location_search_no_results), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } else { + LazyColumn(modifier = Modifier.fillMaxSize()) { + items(searchResults, key = { "${it.name}_${it.latitude}_${it.longitude}" }) { result -> + ListItem( + headlineContent = { + Text( + text = result.name, + style = MaterialTheme.typography.bodyLarge.copy( + fontWeight = FontWeight.SemiBold + ), + color = MaterialTheme.colorScheme.onSurface + ) + }, + supportingContent = { + Text( + text = result.address, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis + ) + }, + leadingContent = { + Icon( + imageVector = Icons.Filled.LocationOn, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary + ) + }, + colors = ListItemDefaults.colors(containerColor = MaterialTheme.colorScheme.surface), + modifier = Modifier.clickable { selectSearchResult(result) } + ) + HorizontalDivider( + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.2f), + modifier = Modifier.padding(horizontal = 16.dp) + ) + } + } + } + } + } + } + } + } + + // ------------------ 6. 收藏夹页面 (全屏覆盖视图) ------------------ + AnimatedVisibility( + visible = showFavoritesScreen, + enter = fadeIn(), + exit = fadeOut(), + modifier = Modifier.fillMaxSize() + ) { + val wgsCoords = remember(currentGeoPoint) { + CoordinateConverter.gcj02ToWgs84(currentGeoPoint.latitude, currentGeoPoint.longitude) + } + FavoritesScreen( + currentWgsLat = wgsCoords[0], + currentWgsLng = wgsCoords[1], + currentAddress = locationName.ifEmpty { stringResource(id = R.string.location_default_name) }, + onNavigateBack = { showFavoritesScreen = false }, + onSelectFavorite = { favorite -> + val gcj = CoordinateConverter.wgs84ToGcj02(favorite.latitude, favorite.longitude) + val targetPoint = GeoPoint(gcj[0], gcj[1]) + updatePositionAndResolveName( + pointOnMap = targetPoint, + isUserManual = true, + centerMap = true, + animate = true + ) + locationName = favorite.name + showFavoritesScreen = false + Toast.makeText( + context, + context.getString(R.string.favorite_applied_success, favorite.name), + Toast.LENGTH_SHORT + ).show() + } + ) + } + } + + // ------------------ 搜索引擎提供商快捷切换抽屉 (ModalBottomSheet) ------------------ + if (showSearchProviderSheet) { + ModalBottomSheet( + onDismissRequest = { showSearchProviderSheet = false }, + sheetState = searchProviderSheetState, + containerColor = MaterialTheme.colorScheme.surface, + shape = RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp) + ) { + LocalizedDialogContent(context) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 20.dp) + .navigationBarsPadding() + ) { + Text( + text = stringResource(id = R.string.settings_search_provider_sheet_title), + style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold), + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.padding(vertical = 12.dp) + ) + + SearchProvider.entries.forEach { provider -> + val isSelected = provider == AppPreferences.searchProvider + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .background( + if (isSelected) MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.45f) + else Color.Transparent + ) + .clickable { + AppPreferences.updateSearchProvider(provider) + coroutineScope.launch { + searchProviderSheetState.hide() + showSearchProviderSheet = false + } + } + .padding(horizontal = 16.dp, vertical = 16.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.weight(1f) + ) { + Text( + text = stringResource(id = provider.titleRes), + style = MaterialTheme.typography.bodyLarge.copy( + fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Medium + ), + color = if (isSelected) MaterialTheme.colorScheme.primary + else MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.width(10.dp)) + Surface( + shape = RoundedCornerShape(6.dp), + color = if (provider.requiresKey) MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = 0.7f) + else MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.7f) + ) { + Text( + text = if (provider.requiresKey) stringResource(id = R.string.search_provider_badge_requires_key) + else stringResource(id = R.string.search_provider_badge_free), + style = MaterialTheme.typography.labelSmall.copy(fontWeight = FontWeight.SemiBold), + color = if (provider.requiresKey) MaterialTheme.colorScheme.onTertiaryContainer + else MaterialTheme.colorScheme.onSecondaryContainer, + modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp) + ) + } + } + + if (isSelected) { + Icon( + imageVector = Icons.Filled.Check, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(22.dp) + ) + } + } + } + + Spacer(modifier = Modifier.height(24.dp)) + } + } + } + } + + // ------------------ API Key 配置快速弹窗 (AlertDialog,带一键测试功能) ------------------ + if (showApiKeyDialog) { + val currentProvider = AppPreferences.searchProvider + var tempKey by remember { mutableStateOf(AppPreferences.getCurrentProviderKey()) } + var testStatus by remember { mutableStateOf(null) } + var isTesting by remember { mutableStateOf(false) } + + val dialogTitleRes = when (currentProvider) { + SearchProvider.AMAP -> R.string.settings_amap_key_dialog_title + SearchProvider.BAIDU -> R.string.settings_baidu_key_dialog_title + else -> R.string.settings_amap_key_dialog_title + } + + AlertDialog( + onDismissRequest = { showApiKeyDialog = false }, + title = { + LocalizedDialogContent(context) { + Text( + text = stringResource(id = dialogTitleRes), + style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold) + ) + } + }, + text = { + LocalizedDialogContent(context) { + Column { + val hintRes = when (currentProvider) { + SearchProvider.AMAP -> R.string.settings_amap_key_hint + SearchProvider.BAIDU -> R.string.settings_baidu_key_hint + else -> R.string.settings_amap_key_hint + } + Text( + text = stringResource(id = hintRes), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(modifier = Modifier.height(12.dp)) + + OutlinedTextField( + value = tempKey, + onValueChange = { + tempKey = it + testStatus = null + }, + placeholder = { + Text( + text = stringResource(id = R.string.settings_api_key_placeholder), + style = MaterialTheme.typography.bodyMedium + ) + }, + trailingIcon = { + if (tempKey.isNotBlank()) { + IconButton(onClick = { + tempKey = "" + testStatus = null + }) { + Icon( + imageVector = Icons.Filled.Close, + contentDescription = null, + modifier = Modifier.size(18.dp) + ) + } + } + }, + singleLine = true, + shape = RoundedCornerShape(12.dp), + modifier = Modifier.fillMaxWidth() + ) + + Spacer(modifier = Modifier.height(10.dp)) + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Box(modifier = Modifier.weight(1f).padding(end = 8.dp)) { + when { + isTesting -> { + Text( + text = stringResource(id = R.string.settings_api_key_testing), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.primary + ) + } + testStatus == "SUCCESS" -> { + Text( + text = stringResource(id = R.string.settings_api_key_test_success), + style = MaterialTheme.typography.bodySmall.copy(fontWeight = FontWeight.Medium), + color = MaterialTheme.colorScheme.primary + ) + } + testStatus?.startsWith("FAILED:") == true -> { + val errCode = testStatus?.removePrefix("FAILED:")?.trim() ?: "" + val errDisplay = when (errCode) { + "KEY_EMPTY" -> stringResource(id = R.string.settings_api_key_empty) + "NETWORK_ERROR" -> stringResource(id = R.string.search_network_error) + else -> errCode.ifBlank { stringResource(id = R.string.error_unknown) } + } + Text( + text = stringResource( + id = R.string.settings_api_key_test_failed, + errDisplay + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + maxLines = 2 + ) + } + } + } + + FilledTonalButton( + onClick = { + if (tempKey.isNotBlank()) { + isTesting = true + testStatus = null + coroutineScope.launch { + val (success, err) = LocationResolver.testApiKey(currentProvider, tempKey) + isTesting = false + testStatus = if (success) "SUCCESS" else "FAILED: ${err ?: ""}" + } + } + }, + enabled = tempKey.isNotBlank() && !isTesting, + shape = RoundedCornerShape(8.dp), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 4.dp) + ) { + Text(stringResource(id = R.string.settings_api_key_test), style = MaterialTheme.typography.labelMedium) + } + } + } + } + }, + confirmButton = { + LocalizedDialogContent(context) { + TextButton( + onClick = { + AppPreferences.updateCurrentProviderKey(tempKey) + showApiKeyDialog = false + } + ) { + Text(stringResource(id = R.string.settings_amap_key_save)) + } + } + }, + dismissButton = { + LocalizedDialogContent(context) { + Row { + if (AppPreferences.getCurrentProviderKey().isNotBlank()) { + TextButton( + onClick = { + AppPreferences.updateCurrentProviderKey("") + showApiKeyDialog = false + } + ) { + Text( + text = stringResource(id = R.string.settings_amap_key_clear), + color = MaterialTheme.colorScheme.error + ) + } + } + TextButton(onClick = { showApiKeyDialog = false }) { + Text(stringResource(id = R.string.action_cancel)) + } + } + } + } + ) + } +} + +/** + * 复制文本到系统剪贴板工具函数 + */ +private fun copyToClipboard(context: Context, text: String) { + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + val clip = ClipData.newPlainText("Coordinates", text) + clipboard.setPrimaryClip(clip) +} diff --git a/app/src/main/java/com/lzxnone/openloc/ui/screens/settings/SettingsScreen.kt b/app/src/main/java/com/lzxnone/openloc/ui/screens/settings/SettingsScreen.kt new file mode 100644 index 0000000..e84bf39 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/ui/screens/settings/SettingsScreen.kt @@ -0,0 +1,1041 @@ +package com.lzxnone.openloc.ui.screens.settings + +import android.app.Activity +import android.os.Build +import androidx.compose.ui.platform.LocalContext +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight +import androidx.compose.material.icons.filled.AutoAwesome +import androidx.compose.material.icons.filled.CellTower +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.ColorLens +import androidx.compose.material.icons.filled.DarkMode +import androidx.compose.material.icons.filled.DeveloperMode +import androidx.compose.material.icons.filled.Explore +import androidx.compose.material.icons.filled.Key +import androidx.compose.material.icons.filled.SatelliteAlt +import androidx.compose.material.icons.filled.Security +import androidx.compose.material.icons.filled.Translate +import androidx.compose.material.icons.filled.Vibration +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Switch +import androidx.compose.material3.SwitchDefaults +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.lzxnone.openloc.R +import com.lzxnone.openloc.LocalizedDialogContent +import com.lzxnone.openloc.updateActivityLocale +import com.lzxnone.openloc.data.preference.AppLanguage +import com.lzxnone.openloc.data.preference.AppPreferences +import com.lzxnone.openloc.data.preference.ThemeMode +import kotlinx.coroutines.launch + +/** + * 设置界面:采用底部抽屉(ModalBottomSheet)作为下拉选择面板 + */ +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.material.icons.filled.KeyOff +import androidx.compose.material.icons.filled.Public +import androidx.compose.material3.FilledTonalButton +import com.lzxnone.openloc.core.util.LocationResolver +import com.lzxnone.openloc.data.preference.SearchProvider +import kotlinx.coroutines.launch + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun SettingsScreen( + modifier: Modifier = Modifier +) { + val scrollState = rememberScrollState() + val coroutineScope = rememberCoroutineScope() + val context = LocalContext.current + + // 控制各个面板显示状态 + var showLanguageSheet by remember { mutableStateOf(false) } + var showThemeModeSheet by remember { mutableStateOf(false) } + var showColorPickerDialog by remember { mutableStateOf(false) } + var showSearchProviderSheet by remember { mutableStateOf(false) } + var showApiKeyConfigDialog by remember { mutableStateOf(false) } + + val currentThemeMode = AppPreferences.themeMode + val currentThemeColor = Color(AppPreferences.themeColor) + val isDynamicColorSupported = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S + val isDynamicColor = AppPreferences.isDynamicColor && isDynamicColorSupported + val currentLanguage = AppPreferences.appLanguage + + val languageSheetState = rememberModalBottomSheetState() + val themeModeSheetState = rememberModalBottomSheetState() + val searchProviderSheetState = rememberModalBottomSheetState() + + Column( + modifier = modifier + .fillMaxSize() + .verticalScroll(scrollState) + .padding(horizontal = 16.dp, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + // ------------------ 1. 语言设置板块 ------------------ + Text( + text = stringResource(id = R.string.settings_category_language), + style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.Bold), + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.padding(start = 4.dp, top = 4.dp) + ) + + Card( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), + elevation = CardDefaults.cardElevation(defaultElevation = 1.dp) + ) { + SettingRowItem( + title = stringResource(id = R.string.settings_language_title), + value = stringResource(id = currentLanguage.titleRes), + icon = Icons.Filled.Translate, + onClick = { showLanguageSheet = true } + ) + } + + // ------------------ 2. 外观设置板块 ------------------ + Text( + text = stringResource(id = R.string.settings_category_appearance), + style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.Bold), + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.padding(start = 4.dp, top = 8.dp) + ) + + Card( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), + elevation = CardDefaults.cardElevation(defaultElevation = 1.dp) + ) { + Column { + // (1) 主题模式 + SettingRowItem( + title = stringResource(id = R.string.settings_theme_mode_title), + value = stringResource(id = currentThemeMode.titleRes), + icon = Icons.Filled.DarkMode, + onClick = { showThemeModeSheet = true } + ) + + HorizontalDivider( + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f), + modifier = Modifier.padding(horizontal = 16.dp) + ) + + // (2) 系统主题颜色 Switch(低版本直接禁用,无副标题小字) + val dynamicColorItemEnabled = isDynamicColorSupported + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 18.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.weight(1f) + ) { + Box( + modifier = Modifier + .size(36.dp) + .clip(CircleShape) + .background( + if (dynamicColorItemEnabled) MaterialTheme.colorScheme.primary.copy(alpha = 0.12f) + else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.06f) + ), + contentAlignment = Alignment.Center + ) { + Icon( + imageVector = Icons.Filled.AutoAwesome, + contentDescription = null, + tint = if (dynamicColorItemEnabled) MaterialTheme.colorScheme.primary + else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f), + modifier = Modifier.size(20.dp) + ) + } + Spacer(modifier = Modifier.width(14.dp)) + Text( + text = stringResource(id = R.string.settings_dynamic_color_title), + style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Medium), + color = if (dynamicColorItemEnabled) MaterialTheme.colorScheme.onSurface + else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f) + ) + } + + Spacer(modifier = Modifier.width(12.dp)) + + Switch( + checked = isDynamicColor, + onCheckedChange = { AppPreferences.updateDynamicColor(it) }, + enabled = dynamicColorItemEnabled, + colors = SwitchDefaults.colors( + checkedThumbColor = MaterialTheme.colorScheme.onPrimary, + checkedTrackColor = MaterialTheme.colorScheme.primary + ) + ) + } + + HorizontalDivider( + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f), + modifier = Modifier.padding(horizontal = 16.dp) + ) + + // (3) 主题颜色(受 isDynamicColor 联动禁用) + val isThemeColorEnabled = !isDynamicColor + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(16.dp)) + .clickable(enabled = isThemeColorEnabled) { showColorPickerDialog = true } + .padding(horizontal = 16.dp, vertical = 18.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.weight(1f) + ) { + Box( + modifier = Modifier + .size(36.dp) + .clip(CircleShape) + .background( + if (isThemeColorEnabled) MaterialTheme.colorScheme.primary.copy(alpha = 0.12f) + else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.06f) + ), + contentAlignment = Alignment.Center + ) { + Icon( + imageVector = Icons.Filled.ColorLens, + contentDescription = null, + tint = if (isThemeColorEnabled) MaterialTheme.colorScheme.primary + else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f), + modifier = Modifier.size(20.dp) + ) + } + Spacer(modifier = Modifier.width(14.dp)) + Text( + text = stringResource(id = R.string.settings_theme_color_title), + style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Medium), + color = if (isThemeColorEnabled) MaterialTheme.colorScheme.onSurface + else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f) + ) + } + + Row(verticalAlignment = Alignment.CenterVertically) { + Box( + modifier = Modifier + .size(24.dp) + .clip(CircleShape) + .background( + if (isThemeColorEnabled) currentThemeColor + else currentThemeColor.copy(alpha = 0.35f) + ) + .border( + width = 1.5.dp, + color = if (isThemeColorEnabled) MaterialTheme.colorScheme.outline.copy(alpha = 0.35f) + else MaterialTheme.colorScheme.outline.copy(alpha = 0.15f), + shape = CircleShape + ) + ) + Spacer(modifier = Modifier.width(8.dp)) + Icon( + imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, + contentDescription = null, + tint = if (isThemeColorEnabled) MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f) + else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.25f), + modifier = Modifier.size(20.dp) + ) + } + } + } + } + + // ------------------ 3. 地图与搜索服务板块 ------------------ + Text( + text = stringResource(id = R.string.settings_category_map_service), + style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.Bold), + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.padding(start = 4.dp, top = 8.dp) + ) + + Card( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), + elevation = CardDefaults.cardElevation(defaultElevation = 1.dp) + ) { + Column { + // (1) 搜索引擎提供商选择行 + SettingRowItem( + title = stringResource(id = R.string.settings_search_provider_title), + value = stringResource(id = AppPreferences.searchProvider.titleRes), + icon = Icons.Filled.Public, + onClick = { showSearchProviderSheet = true } + ) + + HorizontalDivider( + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f), + modifier = Modifier.padding(horizontal = 16.dp) + ) + + // (2) API Key 配置行(若选中的搜索引擎无需Key,则置灰并禁用) + val currentProvider = AppPreferences.searchProvider + val isKeyRequired = currentProvider.requiresKey + + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(16.dp)) + .clickable(enabled = isKeyRequired) { showApiKeyConfigDialog = true } + .padding(horizontal = 16.dp, vertical = 18.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.weight(1f) + ) { + Box( + modifier = Modifier + .size(36.dp) + .clip(CircleShape) + .background( + if (isKeyRequired) MaterialTheme.colorScheme.primary.copy(alpha = 0.12f) + else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.06f) + ), + contentAlignment = Alignment.Center + ) { + Icon( + imageVector = if (isKeyRequired) Icons.Filled.Key else Icons.Filled.KeyOff, + contentDescription = null, + tint = if (isKeyRequired) MaterialTheme.colorScheme.primary + else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f), + modifier = Modifier.size(20.dp) + ) + } + Spacer(modifier = Modifier.width(14.dp)) + Text( + text = stringResource(id = R.string.settings_api_key_title), + style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Medium), + color = if (isKeyRequired) MaterialTheme.colorScheme.onSurface + else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f) + ) + } + + Row(verticalAlignment = Alignment.CenterVertically) { + val displayValue = if (isKeyRequired) { + val key = AppPreferences.getCurrentProviderKey() + if (key.isNotBlank()) { + if (key.length > 8) "${key.take(4)}****${key.takeLast(4)}" else stringResource(R.string.settings_amap_key_configured) + } else { + stringResource(id = R.string.settings_amap_key_not_configured) + } + } else { + stringResource(id = R.string.settings_api_key_free_value) + } + + Text( + text = displayValue, + style = MaterialTheme.typography.bodyMedium, + color = if (isKeyRequired) MaterialTheme.colorScheme.onSurfaceVariant + else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.38f) + ) + Spacer(modifier = Modifier.width(8.dp)) + Icon( + imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, + contentDescription = null, + tint = if (isKeyRequired) MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f) + else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.25f), + modifier = Modifier.size(20.dp) + ) + } + } + } + } + + // ------------------ 4. 防检测与真实度增强板块 ------------------ + Text( + text = stringResource(id = R.string.settings_category_anti_detection), + style = MaterialTheme.typography.titleSmall.copy(fontWeight = FontWeight.Bold), + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.padding(start = 4.dp, top = 8.dp) + ) + + Card( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface), + elevation = CardDefaults.cardElevation(defaultElevation = 1.dp) + ) { + Column { + // (1) 位置自然微漂移 + SettingSwitchItem( + title = stringResource(id = R.string.settings_anti_jitter_title), + description = stringResource(id = R.string.settings_anti_jitter_desc), + icon = Icons.Filled.Explore, + checked = AppPreferences.isJitterEnabled, + onCheckedChange = { AppPreferences.updateJitterEnabled(it) } + ) + + HorizontalDivider( + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f), + modifier = Modifier.padding(horizontal = 16.dp) + ) + + // (2) 全真多星座卫星仿真 + SettingSwitchItem( + title = stringResource(id = R.string.settings_anti_gnss_title), + description = stringResource(id = R.string.settings_anti_gnss_desc), + icon = Icons.Filled.SatelliteAlt, + checked = AppPreferences.isGnssSimulationEnabled, + onCheckedChange = { AppPreferences.updateGnssSimulationEnabled(it) } + ) + + HorizontalDivider( + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f), + modifier = Modifier.padding(horizontal = 16.dp) + ) + + // (3) 基站与 Wi-Fi 防反查 + SettingSwitchItem( + title = stringResource(id = R.string.settings_anti_network_title), + description = stringResource(id = R.string.settings_anti_network_desc), + icon = Icons.Filled.CellTower, + checked = AppPreferences.isNetworkCamouflageEnabled, + onCheckedChange = { AppPreferences.updateNetworkCamouflageEnabled(it) } + ) + + HorizontalDivider( + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f), + modifier = Modifier.padding(horizontal = 16.dp) + ) + + // (4) 传感器手持生理拟真 + SettingSwitchItem( + title = stringResource(id = R.string.settings_anti_sensor_title), + description = stringResource(id = R.string.settings_anti_sensor_desc), + icon = Icons.Filled.Vibration, + checked = AppPreferences.isSensorSimulationEnabled, + onCheckedChange = { AppPreferences.updateSensorSimulationEnabled(it) } + ) + + HorizontalDivider( + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f), + modifier = Modifier.padding(horizontal = 16.dp) + ) + + // (5) 堆栈与模块自隐匿 + SettingSwitchItem( + title = stringResource(id = R.string.settings_anti_stealth_title), + description = stringResource(id = R.string.settings_anti_stealth_desc), + icon = Icons.Filled.Security, + checked = AppPreferences.isStealthEnabled, + onCheckedChange = { AppPreferences.updateStealthEnabled(it) } + ) + + HorizontalDivider( + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.4f), + modifier = Modifier.padding(horizontal = 16.dp) + ) + + // (6) 开发者选项伪装 + SettingSwitchItem( + title = stringResource(id = R.string.settings_anti_dev_title), + description = stringResource(id = R.string.settings_anti_dev_desc), + icon = Icons.Filled.DeveloperMode, + checked = AppPreferences.isDevCamouflageEnabled, + onCheckedChange = { AppPreferences.updateDevCamouflageEnabled(it) } + ) + } + } + } + + // ------------------ 搜索引擎提供商选择底部抽屉 (ModalBottomSheet) ------------------ + if (showSearchProviderSheet) { + ModalBottomSheet( + onDismissRequest = { showSearchProviderSheet = false }, + sheetState = searchProviderSheetState, + containerColor = MaterialTheme.colorScheme.surface, + shape = RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp) + ) { + LocalizedDialogContent(context) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 20.dp) + .navigationBarsPadding() + ) { + Text( + text = stringResource(id = R.string.settings_search_provider_sheet_title), + style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold), + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.padding(vertical = 12.dp) + ) + + SearchProvider.entries.forEach { provider -> + val isSelected = provider == AppPreferences.searchProvider + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .background( + if (isSelected) MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.45f) + else Color.Transparent + ) + .clickable { + AppPreferences.updateSearchProvider(provider) + coroutineScope.launch { + searchProviderSheetState.hide() + showSearchProviderSheet = false + } + } + .padding(horizontal = 16.dp, vertical = 16.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.weight(1f) + ) { + Text( + text = stringResource(id = provider.titleRes), + style = MaterialTheme.typography.bodyLarge.copy( + fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Medium + ), + color = if (isSelected) MaterialTheme.colorScheme.primary + else MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.width(10.dp)) + Surface( + shape = RoundedCornerShape(6.dp), + color = if (provider.requiresKey) MaterialTheme.colorScheme.tertiaryContainer.copy(alpha = 0.7f) + else MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.7f) + ) { + Text( + text = if (provider.requiresKey) stringResource(id = R.string.search_provider_badge_requires_key) + else stringResource(id = R.string.search_provider_badge_free), + style = MaterialTheme.typography.labelSmall.copy(fontWeight = FontWeight.SemiBold), + color = if (provider.requiresKey) MaterialTheme.colorScheme.onTertiaryContainer + else MaterialTheme.colorScheme.onSecondaryContainer, + modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp) + ) + } + } + + if (isSelected) { + Icon( + imageVector = Icons.Filled.Check, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(22.dp) + ) + } + } + } + + Spacer(modifier = Modifier.height(24.dp)) + } + } + } + } + + // ------------------ API Key 配置弹窗 (AlertDialog,带一键测试功能) ------------------ + if (showApiKeyConfigDialog) { + val currentProvider = AppPreferences.searchProvider + var tempKey by remember { mutableStateOf(AppPreferences.getCurrentProviderKey()) } + var testStatus by remember { mutableStateOf(null) } + var isTesting by remember { mutableStateOf(false) } + + val dialogTitleRes = when (currentProvider) { + SearchProvider.AMAP -> R.string.settings_amap_key_dialog_title + SearchProvider.BAIDU -> R.string.settings_baidu_key_dialog_title + else -> R.string.settings_amap_key_dialog_title + } + + AlertDialog( + onDismissRequest = { showApiKeyConfigDialog = false }, + title = { + LocalizedDialogContent(context) { + Text( + text = stringResource(id = dialogTitleRes), + style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold) + ) + } + }, + text = { + LocalizedDialogContent(context) { + Column { + val hintRes = when (currentProvider) { + SearchProvider.AMAP -> R.string.settings_amap_key_hint + SearchProvider.BAIDU -> R.string.settings_baidu_key_hint + else -> R.string.settings_amap_key_hint + } + Text( + text = stringResource(id = hintRes), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(modifier = Modifier.height(12.dp)) + + OutlinedTextField( + value = tempKey, + onValueChange = { + tempKey = it + testStatus = null + }, + placeholder = { + Text( + text = stringResource(id = R.string.settings_api_key_placeholder), + style = MaterialTheme.typography.bodyMedium + ) + }, + trailingIcon = { + if (tempKey.isNotBlank()) { + IconButton(onClick = { + tempKey = "" + testStatus = null + }) { + Icon( + imageVector = Icons.Filled.Close, + contentDescription = null, + modifier = Modifier.size(18.dp) + ) + } + } + }, + singleLine = true, + shape = RoundedCornerShape(12.dp), + modifier = Modifier.fillMaxWidth() + ) + + Spacer(modifier = Modifier.height(10.dp)) + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + // 测试状态提示 + Box(modifier = Modifier.weight(1f).padding(end = 8.dp)) { + when { + isTesting -> { + Text( + text = stringResource(id = R.string.settings_api_key_testing), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.primary + ) + } + testStatus == "SUCCESS" -> { + Text( + text = stringResource(id = R.string.settings_api_key_test_success), + style = MaterialTheme.typography.bodySmall.copy(fontWeight = FontWeight.Medium), + color = MaterialTheme.colorScheme.primary + ) + } + testStatus?.startsWith("FAILED:") == true -> { + val errCode = testStatus?.removePrefix("FAILED:")?.trim() ?: "" + val errDisplay = when (errCode) { + "KEY_EMPTY" -> stringResource(id = R.string.settings_api_key_empty) + "NETWORK_ERROR" -> stringResource(id = R.string.search_network_error) + else -> errCode.ifBlank { stringResource(id = R.string.error_unknown) } + } + Text( + text = stringResource( + id = R.string.settings_api_key_test_failed, + errDisplay + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error, + maxLines = 2 + ) + } + } + } + + // 测试按钮 + FilledTonalButton( + onClick = { + if (tempKey.isNotBlank()) { + isTesting = true + testStatus = null + coroutineScope.launch { + val (success, err) = LocationResolver.testApiKey(currentProvider, tempKey) + isTesting = false + testStatus = if (success) "SUCCESS" else "FAILED: ${err ?: ""}" + } + } + }, + enabled = tempKey.isNotBlank() && !isTesting, + shape = RoundedCornerShape(8.dp), + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 4.dp) + ) { + Text(stringResource(id = R.string.settings_api_key_test), style = MaterialTheme.typography.labelMedium) + } + } + } + } + }, + confirmButton = { + LocalizedDialogContent(context) { + TextButton( + onClick = { + AppPreferences.updateCurrentProviderKey(tempKey) + showApiKeyConfigDialog = false + } + ) { + Text(stringResource(id = R.string.settings_amap_key_save)) + } + } + }, + dismissButton = { + LocalizedDialogContent(context) { + Row { + if (AppPreferences.getCurrentProviderKey().isNotBlank()) { + TextButton( + onClick = { + AppPreferences.updateCurrentProviderKey("") + showApiKeyConfigDialog = false + } + ) { + Text( + text = stringResource(id = R.string.settings_amap_key_clear), + color = MaterialTheme.colorScheme.error + ) + } + } + TextButton(onClick = { showApiKeyConfigDialog = false }) { + Text(stringResource(id = R.string.action_cancel)) + } + } + } + } + ) + } + + // ------------------ 语言选择底部抽屉 (ModalBottomSheet) ------------------ + if (showLanguageSheet) { + ModalBottomSheet( + onDismissRequest = { showLanguageSheet = false }, + sheetState = languageSheetState, + containerColor = MaterialTheme.colorScheme.surface, + shape = RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp) + ) { + LocalizedDialogContent(context) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 20.dp) + .navigationBarsPadding() + ) { + Text( + text = stringResource(id = R.string.settings_language_sheet_title), + style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold), + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.padding(vertical = 12.dp) + ) + + AppLanguage.entries.forEach { language -> + val isSelected = language == currentLanguage + BottomSheetOptionItem( + text = stringResource(id = language.titleRes), + isSelected = isSelected, + onClick = { + AppPreferences.updateAppLanguage(language) + coroutineScope.launch { + languageSheetState.hide() + showLanguageSheet = false + val activity = context as? Activity + if (activity != null) { + updateActivityLocale(activity, language) + activity.recreate() + } + } + } + ) + } + + Spacer(modifier = Modifier.height(24.dp)) + } + } + } + } + + // ------------------ 主题模式选择底部抽屉 (ModalBottomSheet) ------------------ + if (showThemeModeSheet) { + ModalBottomSheet( + onDismissRequest = { showThemeModeSheet = false }, + sheetState = themeModeSheetState, + containerColor = MaterialTheme.colorScheme.surface, + shape = RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp) + ) { + LocalizedDialogContent(context) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 20.dp) + .navigationBarsPadding() + ) { + Text( + text = stringResource(id = R.string.settings_theme_mode_sheet_title), + style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold), + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.padding(vertical = 12.dp) + ) + + ThemeMode.entries.forEach { mode -> + val isSelected = mode == currentThemeMode + BottomSheetOptionItem( + text = stringResource(id = mode.titleRes), + isSelected = isSelected, + onClick = { + AppPreferences.updateThemeMode(mode) + coroutineScope.launch { + themeModeSheetState.hide() + showThemeModeSheet = false + } + } + ) + } + + Spacer(modifier = Modifier.height(24.dp)) + } + } + } + } + + // ------------------ 主题颜色调色板对话框 ------------------ + if (showColorPickerDialog) { + ThemeColorPickerDialog( + currentColor = currentThemeColor, + onDismissRequest = { showColorPickerDialog = false }, + onColorSelected = { newColor -> + AppPreferences.updateThemeColor(newColor) + } + ) + } +} + +/** + * 统一样式的设置卡片单行条目 + */ +@Composable +private fun SettingRowItem( + title: String, + value: String, + icon: ImageVector, + onClick: () -> Unit, + modifier: Modifier = Modifier +) { + Row( + modifier = modifier + .fillMaxWidth() + .clip(RoundedCornerShape(16.dp)) + .clickable(onClick = onClick) + .padding(horizontal = 16.dp, vertical = 18.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.weight(1f) + ) { + Box( + modifier = Modifier + .size(36.dp) + .clip(CircleShape) + .background(MaterialTheme.colorScheme.primary.copy(alpha = 0.12f)), + contentAlignment = Alignment.Center + ) { + Icon( + imageVector = icon, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(20.dp) + ) + } + Spacer(modifier = Modifier.width(14.dp)) + Text( + text = title, + style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Medium), + color = MaterialTheme.colorScheme.onSurface + ) + } + + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = value, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(modifier = Modifier.width(8.dp)) + Icon( + imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f), + modifier = Modifier.size(20.dp) + ) + } + } +} + +/** + * 底部抽屉中的选项条目 + */ +@Composable +private fun BottomSheetOptionItem( + text: String, + isSelected: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier +) { + Row( + modifier = modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .background( + if (isSelected) MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.45f) + else Color.Transparent + ) + .clickable(onClick = onClick) + .padding(horizontal = 16.dp, vertical = 16.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Text( + text = text, + style = MaterialTheme.typography.bodyLarge.copy( + fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal + ), + color = if (isSelected) MaterialTheme.colorScheme.primary + else MaterialTheme.colorScheme.onSurface + ) + + if (isSelected) { + Icon( + imageVector = Icons.Filled.Check, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(22.dp) + ) + } + } +} + +/** + * 统一样式的带开关设置条目(支持副标题与点击整行切换) + */ +@Composable +private fun SettingSwitchItem( + title: String, + description: String? = null, + icon: ImageVector, + checked: Boolean, + onCheckedChange: (Boolean) -> Unit, + modifier: Modifier = Modifier +) { + Row( + modifier = modifier + .fillMaxWidth() + .clip(RoundedCornerShape(16.dp)) + .clickable { onCheckedChange(!checked) } + .padding(horizontal = 16.dp, vertical = 14.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.weight(1f) + ) { + Box( + modifier = Modifier + .size(36.dp) + .clip(CircleShape) + .background(MaterialTheme.colorScheme.primary.copy(alpha = 0.12f)), + contentAlignment = Alignment.Center + ) { + Icon( + imageVector = icon, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(20.dp) + ) + } + Spacer(modifier = Modifier.width(14.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = title, + style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Medium), + color = MaterialTheme.colorScheme.onSurface + ) + if (!description.isNullOrBlank()) { + Spacer(modifier = Modifier.height(2.dp)) + Text( + text = description, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } + + Spacer(modifier = Modifier.width(12.dp)) + + Switch( + checked = checked, + onCheckedChange = onCheckedChange, + colors = SwitchDefaults.colors( + checkedThumbColor = MaterialTheme.colorScheme.onPrimary, + checkedTrackColor = MaterialTheme.colorScheme.primary + ) + ) + } +} + diff --git a/app/src/main/java/com/lzxnone/openloc/ui/screens/settings/ThemeColorPickerDialog.kt b/app/src/main/java/com/lzxnone/openloc/ui/screens/settings/ThemeColorPickerDialog.kt new file mode 100644 index 0000000..67f6fb8 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/ui/screens/settings/ThemeColorPickerDialog.kt @@ -0,0 +1,130 @@ +package com.lzxnone.openloc.ui.screens.settings + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Check +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.lzxnone.openloc.R +import com.lzxnone.openloc.data.preference.PresetThemeColors + +/** + * 主题颜色调色板选择对话框 + */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +fun ThemeColorPickerDialog( + currentColor: Color, + onDismissRequest: () -> Unit, + onColorSelected: (Color) -> Unit +) { + var selectedColor by remember { mutableStateOf(currentColor) } + + AlertDialog( + onDismissRequest = onDismissRequest, + shape = RoundedCornerShape(24.dp), + title = { + com.lzxnone.openloc.LocalizedDialogContent { + Text( + text = stringResource(id = R.string.settings_theme_color_dialog_title), + style = MaterialTheme.typography.titleLarge.copy( + fontWeight = FontWeight.Bold + ) + ) + } + }, + text = { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 8.dp) + ) { + // 预设主题色块矩阵 + FlowRow( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceAround, + verticalArrangement = Arrangement.spacedBy(16.dp), + maxItemsInEachRow = 4 + ) { + PresetThemeColors.forEach { color -> + val isSelected = color.toArgb() == selectedColor.toArgb() + + Box( + modifier = Modifier + .size(54.dp) + .clip(CircleShape) + .background(color) + .border( + width = if (isSelected) 3.dp else 1.dp, + color = if (isSelected) MaterialTheme.colorScheme.onSurface + else color.copy(alpha = 0.3f), + shape = CircleShape + ) + .clickable { selectedColor = color }, + contentAlignment = Alignment.Center + ) { + if (isSelected) { + Icon( + imageVector = Icons.Filled.Check, + contentDescription = null, + tint = Color.White, + modifier = Modifier.size(24.dp) + ) + } + } + } + } + } + }, + confirmButton = { + com.lzxnone.openloc.LocalizedDialogContent { + TextButton( + onClick = { + onColorSelected(selectedColor) + onDismissRequest() + } + ) { + Text(text = stringResource(id = R.string.action_confirm)) + } + } + }, + dismissButton = { + com.lzxnone.openloc.LocalizedDialogContent { + TextButton(onClick = onDismissRequest) { + Text(text = stringResource(id = R.string.action_cancel)) + } + } + } + ) +} diff --git a/app/src/main/java/com/lzxnone/openloc/ui/theme/Color.kt b/app/src/main/java/com/lzxnone/openloc/ui/theme/Color.kt new file mode 100644 index 0000000..f260c58 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/ui/theme/Color.kt @@ -0,0 +1,62 @@ +package com.lzxnone.openloc.ui.theme + +import androidx.compose.ui.graphics.Color + +// 浅色主题 - 现代科技蓝 +val PrimaryLight = Color(0xFF0061A4) +val OnPrimaryLight = Color(0xFFFFFFFF) +val PrimaryContainerLight = Color(0xFFD1E4FF) +val OnPrimaryContainerLight = Color(0xFF001D36) + +val SecondaryLight = Color(0xFF535F70) +val OnSecondaryLight = Color(0xFFFFFFFF) +val SecondaryContainerLight = Color(0xFFD7E3F7) +val OnSecondaryContainerLight = Color(0xFF101C2B) + +val TertiaryLight = Color(0xFF6B5778) +val OnTertiaryLight = Color(0xFFFFFFFF) +val TertiaryContainerLight = Color(0xFFF2DAFF) +val OnTertiaryContainerLight = Color(0xFF251431) + +val BackgroundLight = Color(0xFFF8F9FA) +val OnBackgroundLight = Color(0xFF191C1E) +val SurfaceLight = Color(0xFFFFFFFF) +val OnSurfaceLight = Color(0xFF191C1E) +val SurfaceVariantLight = Color(0xFFDFE2EB) +val OnSurfaceVariantLight = Color(0xFF43474E) +val OutlineLight = Color(0xFF73777F) + +// 深色主题 - 现代科技蓝 +val PrimaryDark = Color(0xFF9ECAFF) +val OnPrimaryDark = Color(0xFF003258) +val PrimaryContainerDark = Color(0xFF00497D) +val OnPrimaryContainerDark = Color(0xFFD1E4FF) + +val SecondaryDark = Color(0xFFBBC7DB) +val OnSecondaryDark = Color(0xFF253140) +val SecondaryContainerDark = Color(0xFF3B4858) +val OnSecondaryContainerDark = Color(0xFFD7E3F7) + +val TertiaryDark = Color(0xFFD6BEE4) +val OnTertiaryDark = Color(0xFF3B2948) +val TertiaryContainerDark = Color(0xFF523F5F) +val OnTertiaryContainerDark = Color(0xFFF2DAFF) + +val BackgroundDark = Color(0xFF111416) +val OnBackgroundDark = Color(0xFFE2E2E6) +val SurfaceDark = Color(0xFF1A1C1E) +val OnSurfaceDark = Color(0xFFE2E2E6) +val SurfaceVariantDark = Color(0xFF43474E) +val OnSurfaceVariantDark = Color(0xFFC3C7CF) +val OutlineDark = Color(0xFF8D9199) + +// 状态强调色(激活绿色 & 未激活警告橙色) +val StatusActiveLight = Color(0xFF2E7D32) +val StatusActiveContainerLight = Color(0xFFE8F5E9) +val StatusActiveDark = Color(0xFF81C784) +val StatusActiveContainerDark = Color(0xFF143017) + +val StatusInactiveLight = Color(0xFFE65100) +val StatusInactiveContainerLight = Color(0xFFFFF3E0) +val StatusInactiveDark = Color(0xFFFFB74D) +val StatusInactiveContainerDark = Color(0xFF3E2723) \ No newline at end of file diff --git a/app/src/main/java/com/lzxnone/openloc/ui/theme/Theme.kt b/app/src/main/java/com/lzxnone/openloc/ui/theme/Theme.kt new file mode 100644 index 0000000..d43202d --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/ui/theme/Theme.kt @@ -0,0 +1,137 @@ +package com.lzxnone.openloc.ui.theme + +import android.os.Build +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.ColorScheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.dynamicDarkColorScheme +import androidx.compose.material3.dynamicLightColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.platform.LocalContext +import com.lzxnone.openloc.data.preference.AppPreferences +import com.lzxnone.openloc.data.preference.ThemeMode + +private val DefaultDarkColorScheme = darkColorScheme( + primary = PrimaryDark, + onPrimary = OnPrimaryDark, + primaryContainer = PrimaryContainerDark, + onPrimaryContainer = OnPrimaryContainerDark, + secondary = SecondaryDark, + onSecondary = OnSecondaryDark, + secondaryContainer = SecondaryContainerDark, + onSecondaryContainer = OnSecondaryContainerDark, + tertiary = TertiaryDark, + onTertiary = OnTertiaryDark, + tertiaryContainer = TertiaryContainerDark, + onTertiaryContainer = OnTertiaryContainerDark, + background = BackgroundDark, + onBackground = OnBackgroundDark, + surface = SurfaceDark, + onSurface = OnSurfaceDark, + surfaceVariant = SurfaceVariantDark, + onSurfaceVariant = OnSurfaceVariantDark, + outline = OutlineDark +) + +private val DefaultLightColorScheme = lightColorScheme( + primary = PrimaryLight, + onPrimary = OnPrimaryLight, + primaryContainer = PrimaryContainerLight, + onPrimaryContainer = OnPrimaryContainerLight, + secondary = SecondaryLight, + onSecondary = OnSecondaryLight, + secondaryContainer = SecondaryContainerLight, + onSecondaryContainer = OnSecondaryContainerLight, + tertiary = TertiaryLight, + onTertiary = OnTertiaryLight, + tertiaryContainer = TertiaryContainerLight, + onTertiaryContainer = OnTertiaryContainerLight, + background = BackgroundLight, + onBackground = OnBackgroundLight, + surface = SurfaceLight, + onSurface = OnSurfaceLight, + surfaceVariant = SurfaceVariantLight, + onSurfaceVariant = OnSurfaceVariantLight, + outline = OutlineLight +) + +/** + * 根据所选的主色调生成对应的深/浅色配色方案 + */ +fun generateDynamicColorScheme(primary: Color, isDark: Boolean): ColorScheme { + return if (isDark) { + darkColorScheme( + primary = primary, + onPrimary = Color.White, + primaryContainer = primary.copy(alpha = 0.35f), + onPrimaryContainer = Color.White, + secondary = primary.copy(alpha = 0.75f), + onSecondary = Color.Black, + secondaryContainer = primary.copy(alpha = 0.25f), + onSecondaryContainer = Color.White, + background = BackgroundDark, + onBackground = OnBackgroundDark, + surface = SurfaceDark, + onSurface = OnSurfaceDark, + surfaceVariant = SurfaceVariantDark, + onSurfaceVariant = OnSurfaceVariantDark, + outline = OutlineDark + ) + } else { + lightColorScheme( + primary = primary, + onPrimary = Color.White, + primaryContainer = primary.copy(alpha = 0.15f), + onPrimaryContainer = primary, + secondary = primary.copy(alpha = 0.8f), + onSecondary = Color.White, + secondaryContainer = primary.copy(alpha = 0.12f), + onSecondaryContainer = primary, + background = BackgroundLight, + onBackground = OnBackgroundLight, + surface = SurfaceLight, + onSurface = OnSurfaceLight, + surfaceVariant = SurfaceVariantLight, + onSurfaceVariant = OnSurfaceVariantLight, + outline = OutlineLight + ) + } +} + +@Composable +fun OpenLocTheme( + themeMode: ThemeMode = AppPreferences.themeMode, + themeColor: Color = Color(AppPreferences.themeColor), + isDynamicColor: Boolean = AppPreferences.isDynamicColor, + content: @Composable () -> Unit +) { + val systemInDark = isSystemInDarkTheme() + val isDark = when (themeMode) { + ThemeMode.SYSTEM -> systemInDark + ThemeMode.LIGHT -> false + ThemeMode.DARK -> true + } + + val context = LocalContext.current + val colorScheme = when { + isDynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { + if (isDark) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) + } + PrimaryLight.toArgb() == themeColor.toArgb() -> { + if (isDark) DefaultDarkColorScheme else DefaultLightColorScheme + } + else -> { + generateDynamicColorScheme(themeColor, isDark) + } + } + + MaterialTheme( + colorScheme = colorScheme, + typography = Typography, + content = content + ) +} \ No newline at end of file diff --git a/app/src/main/java/com/lzxnone/openloc/ui/theme/Type.kt b/app/src/main/java/com/lzxnone/openloc/ui/theme/Type.kt new file mode 100644 index 0000000..1afb2b7 --- /dev/null +++ b/app/src/main/java/com/lzxnone/openloc/ui/theme/Type.kt @@ -0,0 +1,34 @@ +package com.lzxnone.openloc.ui.theme + +import androidx.compose.material3.Typography +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.sp + +// Set of Material typography styles to start with +val Typography = Typography( + bodyLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 16.sp, + lineHeight = 24.sp, + letterSpacing = 0.5.sp + ) + /* Other default text styles to override + titleLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 22.sp, + lineHeight = 28.sp, + letterSpacing = 0.sp + ), + labelSmall = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Medium, + fontSize = 11.sp, + lineHeight = 16.sp, + letterSpacing = 0.5.sp + ) + */ +) \ No newline at end of file diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..07b2dc9 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..2b068d1 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi/ic_launcher.xml b/app/src/main/res/mipmap-anydpi/ic_launcher.xml new file mode 100644 index 0000000..033bd78 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml new file mode 100644 index 0000000..033bd78 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.png b/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..9e8ce7f Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..c02ddc0 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 0000000..00e634b Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.png b/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..2e0e060 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..ff606f1 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 0000000..76819a5 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..bdfac42 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..349ed8a Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 0000000..a0e1a88 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..b1b5cb5 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..8e5b313 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..1ae8dde Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..e33adb0 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..b662301 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 0000000..7b7b9a4 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml new file mode 100644 index 0000000..ca91b26 --- /dev/null +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -0,0 +1,176 @@ + + OpenLoc + OpenLoc 虚拟定位 Hook 模块 + + + 主页 + 定位 + 设置 + + + 模块状态 + 已激活 + 未激活 + + + 虚拟定位总开关 + 虚拟定位已开启,正在模拟位置 + 虚拟定位已关闭,使用真实位置 + 模块未激活,总开关已被禁用 + + + 语言设置 + 外观设置 + + + 应用语言 + 选择语言 + 跟随系统 + 简体中文 + English + + + 主题模式 + 选择主题模式 + 跟随系统 + 浅色模式 + 深色模式 + + 系统主题颜色 + 跟随系统壁纸动态提取主题色 (Android 12+) + + 主题颜色 + 选择主题颜色 + + 取消 + 确定 + + + 搜索地区 / 地名… + 选定位置 + 纬度: %1$.6f + 经度: %1$.6f + 复制坐标 + 已复制坐标到剪贴板 + 回到原位 + 已定位到当前真实位置 + 返回 + 清空 + 搜索历史 + 清空历史 + 未找到相关地点 + 输入地点名称或经纬度进行搜索 + 跳转至经纬度坐标 + + + 地图与搜索服务 + 搜索引擎提供商 + 选择搜索引擎提供商 + 高德地图 + 百度地图 + Photon + Nominatim + 需 Key + 完全免费 + + API Key + 无需配置 + 请输入 Key / AK + Key 不能为空 + 未知错误 + 经度: %1$.6f, 纬度: %2$.6f + 测试 + 正在测试... + 测试通过,Key 有效! + 测试失败: %1$s + + 配置高德 Key + 前往高德开放平台 (lbs.amap.com) 获取 Web服务 Key + 配置百度 AK + 前往百度地图开放平台 (lbsyun.baidu.com) 获取服务端 AK + 已配置 + 未配置 + 清空 + 保存 + + 未配置 %1$s Key + 当前搜索引擎需要 API Key,可前往配置或切换为免费引擎。 + 配置 Key + 切换搜索引擎 + %1$s Key 无效 + Key 验证失败(%1$s)。请检查平台类型或重新输入。 + 修改 Key + 网络连接失败,请检查网络后重试 + 折叠 + 展开 + + + 收藏夹 + 新增收藏地址 + 名称 + 例如:家 / 公司 + 地区名称 + 正在根据经纬度推导地区… + 纬度 (WGS-84) + 经度 (WGS-84) + 搜索收藏条目的名称、地区名称… + 暂无收藏地址,点击右上角 + 新增 + 未找到匹配的收藏条目 + 删除收藏 + 确定要删除收藏“%1$s”吗? + 已添加到收藏夹 + 已删除收藏 + 已选定定位:%1$s + 请输入有效的纬度(-90~90)与经度(-180~180) + 名称不能为空 + 删除 + 拖动排序 + 未知地区 + + + 应用作用域 + 配置虚拟定位的作用应用与过滤规则 + 生效模式 + 全局 + 黑名单 + 白名单 + 整机所有应用均生效虚拟定位 + 黑名单中的应用保持真实定位,其余应用生效虚拟定位 + 仅白名单中的应用生效虚拟定位,其余应用保持真实定位 + 黑名单列表 + 白名单列表 + 已排除 %1$d 个应用 + 已生效 %1$d 个应用 + 搜索应用名称或包名… + 全选 + 全不选 + 显示系统应用 + 隐藏系统应用 + 系统 + 正在加载已安装应用… + 未找到匹配的应用 + 暂无可用应用 + 已选 %1$d / %2$d 项 + + + 防检测与真实度增强 + 位置自然微漂移 + 模拟真实卫星信号的高斯平滑游走,避免坐标绝对静止被风控拦截 + 全真多星座卫星仿真 + 模拟 GPS、北斗、GLONASS、Galileo 多星座卫星群,注入物理载噪比与全量 NMEA 报文 + 基站与 Wi-Fi 防反查 + 脱敏基站小区与 Wi-Fi BSSID,拦截运营商基站监听,杜绝云端指纹库反查真实物理地址 + 传感器手持生理拟真 + 向加速度计注入生物力学生理微颤,打破桌面绝对静止特征,满足步态与姿态校验 + 堆栈与模块自隐匿 + 过滤调用栈中的 Xposed 与 OpenLoc 栈帧,并对目标应用隐藏模块包名 + 开发者选项伪装 + 对目标应用伪装为未开启开发者模式、未开启 USB 调试与未开启模拟位置 + + + 当前版本 + v1.0.0 + 检查更新 + 当前已是最新版本 + + diff --git a/app/src/main/res/values-zh/strings.xml b/app/src/main/res/values-zh/strings.xml new file mode 100644 index 0000000..ca91b26 --- /dev/null +++ b/app/src/main/res/values-zh/strings.xml @@ -0,0 +1,176 @@ + + OpenLoc + OpenLoc 虚拟定位 Hook 模块 + + + 主页 + 定位 + 设置 + + + 模块状态 + 已激活 + 未激活 + + + 虚拟定位总开关 + 虚拟定位已开启,正在模拟位置 + 虚拟定位已关闭,使用真实位置 + 模块未激活,总开关已被禁用 + + + 语言设置 + 外观设置 + + + 应用语言 + 选择语言 + 跟随系统 + 简体中文 + English + + + 主题模式 + 选择主题模式 + 跟随系统 + 浅色模式 + 深色模式 + + 系统主题颜色 + 跟随系统壁纸动态提取主题色 (Android 12+) + + 主题颜色 + 选择主题颜色 + + 取消 + 确定 + + + 搜索地区 / 地名… + 选定位置 + 纬度: %1$.6f + 经度: %1$.6f + 复制坐标 + 已复制坐标到剪贴板 + 回到原位 + 已定位到当前真实位置 + 返回 + 清空 + 搜索历史 + 清空历史 + 未找到相关地点 + 输入地点名称或经纬度进行搜索 + 跳转至经纬度坐标 + + + 地图与搜索服务 + 搜索引擎提供商 + 选择搜索引擎提供商 + 高德地图 + 百度地图 + Photon + Nominatim + 需 Key + 完全免费 + + API Key + 无需配置 + 请输入 Key / AK + Key 不能为空 + 未知错误 + 经度: %1$.6f, 纬度: %2$.6f + 测试 + 正在测试... + 测试通过,Key 有效! + 测试失败: %1$s + + 配置高德 Key + 前往高德开放平台 (lbs.amap.com) 获取 Web服务 Key + 配置百度 AK + 前往百度地图开放平台 (lbsyun.baidu.com) 获取服务端 AK + 已配置 + 未配置 + 清空 + 保存 + + 未配置 %1$s Key + 当前搜索引擎需要 API Key,可前往配置或切换为免费引擎。 + 配置 Key + 切换搜索引擎 + %1$s Key 无效 + Key 验证失败(%1$s)。请检查平台类型或重新输入。 + 修改 Key + 网络连接失败,请检查网络后重试 + 折叠 + 展开 + + + 收藏夹 + 新增收藏地址 + 名称 + 例如:家 / 公司 + 地区名称 + 正在根据经纬度推导地区… + 纬度 (WGS-84) + 经度 (WGS-84) + 搜索收藏条目的名称、地区名称… + 暂无收藏地址,点击右上角 + 新增 + 未找到匹配的收藏条目 + 删除收藏 + 确定要删除收藏“%1$s”吗? + 已添加到收藏夹 + 已删除收藏 + 已选定定位:%1$s + 请输入有效的纬度(-90~90)与经度(-180~180) + 名称不能为空 + 删除 + 拖动排序 + 未知地区 + + + 应用作用域 + 配置虚拟定位的作用应用与过滤规则 + 生效模式 + 全局 + 黑名单 + 白名单 + 整机所有应用均生效虚拟定位 + 黑名单中的应用保持真实定位,其余应用生效虚拟定位 + 仅白名单中的应用生效虚拟定位,其余应用保持真实定位 + 黑名单列表 + 白名单列表 + 已排除 %1$d 个应用 + 已生效 %1$d 个应用 + 搜索应用名称或包名… + 全选 + 全不选 + 显示系统应用 + 隐藏系统应用 + 系统 + 正在加载已安装应用… + 未找到匹配的应用 + 暂无可用应用 + 已选 %1$d / %2$d 项 + + + 防检测与真实度增强 + 位置自然微漂移 + 模拟真实卫星信号的高斯平滑游走,避免坐标绝对静止被风控拦截 + 全真多星座卫星仿真 + 模拟 GPS、北斗、GLONASS、Galileo 多星座卫星群,注入物理载噪比与全量 NMEA 报文 + 基站与 Wi-Fi 防反查 + 脱敏基站小区与 Wi-Fi BSSID,拦截运营商基站监听,杜绝云端指纹库反查真实物理地址 + 传感器手持生理拟真 + 向加速度计注入生物力学生理微颤,打破桌面绝对静止特征,满足步态与姿态校验 + 堆栈与模块自隐匿 + 过滤调用栈中的 Xposed 与 OpenLoc 栈帧,并对目标应用隐藏模块包名 + 开发者选项伪装 + 对目标应用伪装为未开启开发者模式、未开启 USB 调试与未开启模拟位置 + + + 当前版本 + v1.0.0 + 检查更新 + 当前已是最新版本 + + diff --git a/app/src/main/res/values/arrays.xml b/app/src/main/res/values/arrays.xml new file mode 100644 index 0000000..6150dec --- /dev/null +++ b/app/src/main/res/values/arrays.xml @@ -0,0 +1,9 @@ + + + + + android + + com.lzxnone.openloc + + diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..f8c6127 --- /dev/null +++ b/app/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..8e66fb7 --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,175 @@ + + OpenLoc + OpenLoc virtual location hook module + + + Home + Location + Settings + + + Module Status + Activated + Inactive + + + Master Switch + Virtual location is running + Virtual location is paused + Module inactive, switch is disabled + + + Language + Appearance + + + App Language + Select Language + Follow System + 简体中文 (Chinese) + English + + + Theme Mode + Select Theme Mode + Follow System + Light Mode + Dark Mode + + System Theme Color + Follow system wallpaper dynamic colors (Android 12+) + + Theme Color + Choose Palette + + Cancel + Confirm + + + Search location / address… + Selected Location + Lat: %1$.6f + Lng: %1$.6f + Copy Coordinates + Coordinates copied to clipboard + Reset to current location + Located to current position + Back + Clear + Recent Searches + Clear History + No matching places found + Enter place name or coordinates to search + Jump to coordinates + + + Map & Search Service + Search Engine Provider + Select Search Provider + AMap + Baidu + Photon + Nominatim + Key Required + Free / No Key + + API Key + Not Required + Enter Key / AK + Key cannot be empty + Unknown error + Lng: %1$.6f, Lat: %2$.6f + Test + Testing... + Test passed! Key is valid. + Test failed: %1$s + + Configure AMap Key + Get Web Service Key from lbs.amap.com + Configure Baidu AK + Get Server AK from lbsyun.baidu.com + Configured + Not Configured + Clear + Save + + %1$s Key Not Configured + This engine requires an API Key. You can configure it or switch to a free engine. + Configure Key + Switch Provider + Invalid %1$s Key + Key verification failed (%1$s). Please check platform type or re-enter. + Edit Key + Network request failed, please check connection + Collapse + Expand + + + Favorites + Add Favorite Location + Name + e.g. Home / Company + Area / Address + Deriving area name… + Latitude (WGS-84) + Longitude (WGS-84) + Search name or area… + No favorites yet. Tap + to add. + No matching favorites found + Delete Favorite + Are you sure you want to delete \"%1$s\"? + Added to favorites + Favorite deleted + Moved to: %1$s + Please enter valid latitude (-90~90) and longitude (-180~180) + Name cannot be empty + Delete + Drag to reorder + Unknown address + + + App Scope Management + Configure target apps and mock rules + Mock Mode + Global + Blacklist + Whitelist + All applications on this device will receive mocked location. + Apps in the blacklist keep real location, while all other apps receive mocked location. + Only apps in the whitelist receive mocked location, while other apps keep real location. + Blacklist Apps + Whitelist Apps + %1$d apps excluded + %1$d apps enabled + Search app name or package… + Select All + Deselect All + Show system apps + Hide system apps + System + Loading installed applications… + No matching applications found + No applications found + %1$d / %2$d selected + + + Anti-Detection & Realism + Natural Location Drift + Simulate smooth Brownian motion / Gaussian GNSS noise to prevent static location detection + Full Constellation GNSS Simulation + Simulate realistic multi-constellation satellites (GPS, BeiDou, GLONASS, Galileo) with physical C/N0 noise and NMEA GSV/GSA sentences + Cell Tower & Wi-Fi Camouflage + Camouflage cell tower and Wi-Fi BSSID to prevent cloud reverse geolocation lookup + Handheld Motion Sensor Simulation + Inject subtle physiological micro-tremor into accelerometer readings to mimic active human hand-holding + Stack Trace & Module Stealth + Sanitize call stack traces (filter Xposed/OpenLoc frames) and hide module package from target apps + Developer Settings Camouflage + Disguise developer mode, USB debugging, and mock location as disabled for target apps + + + Current Version + v1.0.0 + Check for Updates + Already the latest version + \ No newline at end of file diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..1b00ddd --- /dev/null +++ b/app/src/main/res/values/themes.xml @@ -0,0 +1,5 @@ + + + +