├── .github
├── ISSUE_TEMPLATE
│ └── bug_report.md
└── workflows
│ ├── ci.yml
│ └── release.yml
├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── README.md
├── RELEASE.md
├── app
├── .gitignore
├── build.gradle.kts
├── images
│ └── icon.svg
├── proguard-rules.pro
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── chiller3
│ │ └── pixellight
│ │ ├── ExperimentalKeys.java
│ │ ├── MainActivity.java
│ │ ├── MainApplication.java
│ │ ├── Notifications.java
│ │ ├── Permissions.java
│ │ ├── Preferences.java
│ │ ├── ToggleActivity.java
│ │ ├── TorchError.java
│ │ ├── TorchService.java
│ │ ├── TorchSession.java
│ │ └── TorchTileService.java
│ └── res
│ ├── drawable
│ ├── ic_launcher_background.xml
│ ├── ic_launcher_foreground.xml
│ └── ic_notifications.xml
│ ├── layout
│ └── main_activity.xml
│ ├── menu
│ └── main_activity_options.xml
│ ├── mipmap-anydpi
│ ├── ic_launcher.xml
│ └── ic_launcher_round.xml
│ ├── values-notnight
│ └── bools.xml
│ └── values
│ ├── bools.xml
│ ├── strings.xml
│ ├── strings_notranslate.xml
│ └── themes.xml
├── build.gradle.kts
├── gradle.properties
├── gradle
├── libs.versions.toml
├── update_verification.py
├── verification-metadata.xml
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle.kts
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Report an issue with PixelLight's functionality
4 | ---
5 |
6 |
11 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | on:
2 | push:
3 | branches:
4 | - master
5 | pull_request:
6 | jobs:
7 | build:
8 | name: Build project
9 | runs-on: ubuntu-latest
10 | steps:
11 | - name: Check out repository
12 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
13 | with:
14 | fetch-depth: 0
15 |
16 | - name: Validate gradle wrapper checksum
17 | uses: gradle/actions/wrapper-validation@8379f6a1328ee0e06e2bb424dadb7b159856a326 # v4.4.0
18 |
19 | - name: Set up JDK 21
20 | uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
21 | with:
22 | distribution: 'temurin'
23 | java-version: 21
24 | cache: gradle
25 |
26 | - name: Build and test
27 | # Debug build only since release builds require a signing key
28 | run: ./gradlew --no-daemon build -x assembleRelease
29 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | on:
2 | push:
3 | # Uncomment to test against a branch
4 | #branches:
5 | # - ci
6 | tags:
7 | - 'v*'
8 | jobs:
9 | create_release:
10 | name: Create Github release
11 | runs-on: ubuntu-latest
12 | permissions:
13 | contents: write
14 | steps:
15 | - name: Get version from tag
16 | id: get_version
17 | run: |
18 | if [[ "${GITHUB_REF}" == refs/tags/* ]]; then
19 | version=${GITHUB_REF#refs/tags/v}
20 | else
21 | version=0.0.0.${GITHUB_REF#refs/heads/}
22 | fi
23 | echo "version=${version}" >> "${GITHUB_OUTPUT}"
24 |
25 | - name: Check out repository
26 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
27 |
28 | - name: Create release
29 | uses: softprops/action-gh-release@da05d552573ad5aba039eaac05058a918a7bf631 # v2.2.2
30 | with:
31 | token: ${{ secrets.GITHUB_TOKEN }}
32 | tag_name: v${{ steps.get_version.outputs.version }}
33 | name: Version ${{ steps.get_version.outputs.version }}
34 | body_path: RELEASE.md
35 | draft: true
36 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 | .cxx
10 | local.properties
11 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 |
9 |
10 | ### Version 2.3
11 |
12 | * Pretend to be a note-taking app ([Issue #12], [PR #15])
13 | * This is a better approach for toggling the flashlight via a lock screen shortcut. See [the documentation](./README.md#lock-screen-shortcut) for more details.
14 |
15 | ### Version 2.2
16 |
17 | * Avoid needing to unlock the device when turning the flashlight on while locked ([Issue #12], [PR #13])
18 | * Add support for toggling flashlight from other apps ([Issue #12], [PR #13])
19 | * See the [documentation](./README.md#external-control) for details on which intents are accepted.
20 | * This also allows [toggling the flashlight](./README.md#lock-screen-shortcut) via a lock screen shortcut.
21 | * Update build script dependencies ([PR #14])
22 |
23 | ### Version 2.1
24 |
25 | * Enable predictive back gestures ([PR #6])
26 | * Fix incorrect scale factor in icon and rebase off latest material flashlight icon ([PR #7], [PR #8])
27 | * Add new option to keep the foreground service alive ([Issue #9], [PR #10])
28 | * This is a partial bypass for Android 15's restrictions. When the option is enabled, the quick settings tile works on the lock screen again (without unlocking the device first) and the quick settings panel no longer auto-closes. However, this only works after the tile has been toggled once after each reboot.
29 | * Update build script dependencies ([PR #11])
30 |
31 | ### Version 2.0
32 |
33 | * Add support for (only) Android 15 ([Issue #3], [PR #4])
34 | * Due to new Android restrictions, the user experience for the quick settings tile is worse now. On the lock screen, the tile now requires unlocking the device. Tapping the tile will also always close the quick settings panel.
35 | * Support for Android 12-14 has been removed to simplify the code. Android 14, in particular, required some nasty workarounds to make the quick settings tile work well. For older Android versions, continue using PixelLight 1.0.
36 | * Update checksum for `tensorflow-lite-metadata-0.1.0-rc2.pom` dependency ([PR #1])
37 | * Target API 35 ([PR #2])
38 | * Update build script dependencies ([PR #5])
39 |
40 | ### Version 1.0
41 |
42 | * Initial release
43 |
44 |
45 | [Issue #3]: https://github.com/chenxiaolong/PixelLight/issues/3
46 | [Issue #9]: https://github.com/chenxiaolong/PixelLight/issues/9
47 | [Issue #12]: https://github.com/chenxiaolong/PixelLight/issues/12
48 | [PR #1]: https://github.com/chenxiaolong/PixelLight/pull/1
49 | [PR #2]: https://github.com/chenxiaolong/PixelLight/pull/2
50 | [PR #4]: https://github.com/chenxiaolong/PixelLight/pull/4
51 | [PR #5]: https://github.com/chenxiaolong/PixelLight/pull/5
52 | [PR #6]: https://github.com/chenxiaolong/PixelLight/pull/6
53 | [PR #7]: https://github.com/chenxiaolong/PixelLight/pull/7
54 | [PR #8]: https://github.com/chenxiaolong/PixelLight/pull/8
55 | [PR #10]: https://github.com/chenxiaolong/PixelLight/pull/10
56 | [PR #11]: https://github.com/chenxiaolong/PixelLight/pull/11
57 | [PR #13]: https://github.com/chenxiaolong/PixelLight/pull/13
58 | [PR #14]: https://github.com/chenxiaolong/PixelLight/pull/14
59 | [PR #15]: https://github.com/chenxiaolong/PixelLight/pull/15
60 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PixelLight
2 |
3 |
4 |
5 | 
6 | 
7 |
8 | PixelLight is a bare-bones flashlight app for Google Pixel devices that can access higher brightness levels than what is typically allowed by the standard Android 13+ torch APIs.
9 |
10 | It allows access to the same brightness levels as Google Magnifier, except without the excessive 200% CPU usage due to constant camera processing. However, due to how the Pixel private API works, avoiding camera processing entirely is not possible. The CPU usage while the flashlight is on will generally hover around 25%.
11 |
12 | ## Features
13 |
14 | * Supports entire brightness range
15 | * Quick settings tile
16 | * [Lock screen shortcut](#lock-screen-shortcut)
17 | * Tiny APK with no dependencies
18 |
19 | ## Limitations
20 |
21 | * Only supports Android 15+. For Android 12-14, use the old PixelLight 1.0 release, which has a better user experience due to fewer Android restrictions.
22 | * On Android 15, the quick settings panel will close when tapping the tile to turn on the flashlight. Additionally, on the lock screen, the background will turn black until the status bar is tapped. These issues are not fixable due to Android 15's new restrictions on starting foreground services.
23 |
24 | However, if the "Keep service alive" option is enabled, then these issues only happens the first time the tile is toggled after a reboot. This keeps the foreground service running indefinitely, but does not impact battery life because the service is completely idle and not executing any code. The mandatory notification can be disabled from Android's settings if desired.
25 |
26 | ## Permissions
27 |
28 | The `CAMERA` permission is required because Pixel's private API for high brightness modes is only accessible when using the camera as a camera, not when using the camera as a flashlight with the official Android 13+ APIs. Internally, PixelLight is taking a picture every time the flashlight is turned on or the brightness is changed. These exist only in memory and are never saved to disk.
29 |
30 | The `FOREGROUND_SERVICE` and `POST_NOTIFICATIONS` permissions are required to allow the flashlight to remain on while the app is in the background. They are also required for the quick settings tile to work.
31 |
32 | PixelLight does not and will never have the `INTERNET` permission.
33 |
34 | ## External control
35 |
36 | An external app can change the flashlight state by launching PixelLight's `ToggleActivity` via an intent. By default, this will toggle the flashlight state between on and off.
37 |
38 | This activity accepts an optional integer parameter named `brightness`:
39 |
40 | * If the value is -2, the flashlight is toggled between on (at the user's saved brightness) and off. This is the default behavior when the parameter is not specified.
41 | * If the value is -1, the flashlight is turned on at the user's saved brightness.
42 | * If the value is 0, the flashlight is turned off.
43 | * If the value is positive, the flashlight is turned on at the specified brightness. If the value is out of range, it is automatically clamped to the maximum brightness. This does not change the user's brightness preference.
44 | * If the value is anything else, the intent is ignored.
45 |
46 | ## Lock screen shortcut
47 |
48 | Android currently has no builtin way to set custom lock screen shortcuts. To use PixelLight with a lock screen shortcut, it's necessary to either set it as the default note taking app or override the QR code scanner shortcut. The note taking app approach is preferred since it doesn't result in janky animations or black screen issues.
49 |
50 | ### Set as default note taking app
51 |
52 | Android currently doesn't enable the note taking app role by default. It must first be enabled via the `Force enable Notes role` setting in Android's developer options (underneath the `Apps` heading).
53 |
54 | Then, reboot and set PixelLight as the default note taking app in Android's Settings -> Apps -> Default apps -> Notes app.
55 |
56 | The `Note-taking` lock screen shortcut will now launch PixelLight.
57 |
58 | ### Override QR code scanner
59 |
60 | Run:
61 |
62 | ```bash
63 | adb shell device_config override systemui default_qr_code_scanner com.chiller3.pixellight/.ToggleActivity
64 | ```
65 |
66 | After rebooting, the QR code scanner lock screen shortcut and quick settings tile will toggle the flashlight instead of launching the system QR code scanner app.
67 |
68 | To change this setting back to the default, run:
69 |
70 | ```bash
71 | adb shell device_config clear_override systemui default_qr_code_scanner
72 | ```
73 |
74 | and reboot.
75 |
76 | The current setting can be found with:
77 |
78 | ```bash
79 | adb shell device_config get systemui default_qr_code_scanner
80 | ```
81 |
82 | `null` means the QR code scanner is not overridden.
83 |
84 | ## Verifying digital signatures
85 |
86 | First, use `apksigner` to print the digests of the APK signing certificate:
87 |
88 | ```
89 | apksigner verify --print-certs PixelLight--release.apk
90 | ```
91 |
92 | Then, check that the SHA-256 digest of the APK signing certificate is:
93 |
94 | ```
95 | 03a9ed333be772cf612af84fc4bf2cc95428ff5a10c057d3b60d86b0f8fec2c3
96 | ```
97 |
98 | ## Building from source
99 |
100 | PixelLight can be built like most other Android apps using Android Studio or the gradle command line.
101 |
102 | To build the APK:
103 |
104 | ```bash
105 | ./gradlew assembleDebug
106 | ```
107 |
108 | The APK will be signed with the default autogenerated debug key.
109 |
110 | To create a release build with a specific signing key, set the following environment variables:
111 |
112 | ```bash
113 | export RELEASE_KEYSTORE=/path/to/keystore.jks
114 | export RELEASE_KEY_ALIAS=alias_name
115 |
116 | read -r -s RELEASE_KEYSTORE_PASSPHRASE
117 | read -r -s RELEASE_KEY_PASSPHRASE
118 | export RELEASE_KEYSTORE_PASSPHRASE
119 | export RELEASE_KEY_PASSPHRASE
120 | ```
121 |
122 | and then build the release APK:
123 |
124 | ```bash
125 | ./gradlew assembleRelease
126 | ```
127 |
128 | ## Contributing
129 |
130 | Bug fix and translation pull requests are welcome and much appreciated!
131 |
132 | However, aside from that, PixelLight will only ever support Google Pixel devices and is intentionally featureless. I am unlikely to implement any new features.
133 |
134 | ## License
135 |
136 | PixelLight is licensed under GPLv3. Please see [`LICENSE`](./LICENSE) for the full license text.
137 |
--------------------------------------------------------------------------------
/RELEASE.md:
--------------------------------------------------------------------------------
1 | The changelog can be found at: [`CHANGELOG.md`](./CHANGELOG.md).
2 |
3 | ---
4 |
5 | The downloads are digitally signed. Please consider [verifying the digital signatures](./README.md#verifying-digital-signatures) for the initial install.
6 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/app/build.gradle.kts:
--------------------------------------------------------------------------------
1 | /*
2 | * SPDX-FileCopyrightText: 2022-2024 Andrew Gunnerson
3 | * SPDX-License-Identifier: GPL-3.0-only
4 | */
5 |
6 | import org.eclipse.jgit.api.ArchiveCommand
7 | import org.eclipse.jgit.api.Git
8 | import org.eclipse.jgit.archive.TarFormat
9 | import org.eclipse.jgit.lib.ObjectId
10 |
11 | plugins {
12 | alias(libs.plugins.android.application)
13 | }
14 |
15 | java {
16 | toolchain {
17 | languageVersion.set(JavaLanguageVersion.of(21))
18 | }
19 | }
20 |
21 | buildscript {
22 | dependencies {
23 | classpath(libs.jgit)
24 | classpath(libs.jgit.archive)
25 | }
26 | }
27 |
28 | typealias VersionTriple = Triple
29 |
30 | fun describeVersion(git: Git): VersionTriple {
31 | // jgit doesn't provide a nice way to get strongly-typed objects from its `describe` command
32 | val describeStr = git.describe().setLong(true).call()
33 |
34 | return if (describeStr != null) {
35 | val pieces = describeStr.split('-').toMutableList()
36 | val commit = git.repository.resolve(pieces.removeLast().substring(1))
37 | val count = pieces.removeLast().toInt()
38 | val tag = pieces.joinToString("-")
39 |
40 | Triple(tag, count, commit)
41 | } else {
42 | val log = git.log().call().iterator()
43 | val head = log.next()
44 | var count = 1
45 |
46 | while (log.hasNext()) {
47 | log.next()
48 | ++count
49 | }
50 |
51 | Triple(null, count, head.id)
52 | }
53 | }
54 |
55 | fun getVersionCode(triple: VersionTriple): Int {
56 | val tag = triple.first
57 | val (major, minor) = if (tag != null) {
58 | if (!tag.startsWith('v')) {
59 | throw IllegalArgumentException("Tag does not begin with 'v': $tag")
60 | }
61 |
62 | val pieces = tag.substring(1).split('.')
63 | if (pieces.size != 2) {
64 | throw IllegalArgumentException("Tag is not in the form 'v.': $tag")
65 | }
66 |
67 | Pair(pieces[0].toInt(), pieces[1].toInt())
68 | } else {
69 | Pair(0, 0)
70 | }
71 |
72 | // 8 bits for major version, 8 bits for minor version, and 8 bits for git commit count
73 | assert(major in 0 until 1.shl(8))
74 | assert(minor in 0 until 1.shl(8))
75 | assert(triple.second in 0 until 1.shl(8))
76 |
77 | return major.shl(16) or minor.shl(8) or triple.second
78 | }
79 |
80 | fun getVersionName(git: Git, triple: VersionTriple): String {
81 | val tag = triple.first?.replace(Regex("^v"), "") ?: "NONE"
82 |
83 | return buildString {
84 | append(tag)
85 |
86 | if (triple.second > 0) {
87 | append(".r")
88 | append(triple.second)
89 |
90 | append(".g")
91 | git.repository.newObjectReader().use {
92 | append(it.abbreviate(triple.third).name())
93 | }
94 | }
95 | }
96 | }
97 |
98 | val git = Git.open(File(rootDir, ".git"))!!
99 | val gitVersionTriple = describeVersion(git)
100 | val gitVersionCode = getVersionCode(gitVersionTriple)
101 | val gitVersionName = getVersionName(git, gitVersionTriple)
102 |
103 | val projectUrl = "https://github.com/chenxiaolong/PixelLight"
104 |
105 | val extraDir = layout.buildDirectory.map { it.dir("extra") }
106 | val archiveDir = extraDir.map { it.dir("archive") }
107 |
108 | android {
109 | namespace = "com.chiller3.pixellight"
110 |
111 | compileSdk = 35
112 | buildToolsVersion = "35.0.0"
113 |
114 | defaultConfig {
115 | applicationId = "com.chiller3.pixellight"
116 | minSdk = 35
117 | targetSdk = 35
118 | versionCode = gitVersionCode
119 | versionName = gitVersionName
120 |
121 | base.archivesName.set("PixelLight-$versionName")
122 | }
123 | sourceSets {
124 | getByName("main") {
125 | assets {
126 | srcDir(archiveDir)
127 | }
128 | }
129 | }
130 | signingConfigs {
131 | create("release") {
132 | val keystore = System.getenv("RELEASE_KEYSTORE")
133 | storeFile = if (keystore != null) { File(keystore) } else { null }
134 | storePassword = System.getenv("RELEASE_KEYSTORE_PASSPHRASE")
135 | keyAlias = System.getenv("RELEASE_KEY_ALIAS")
136 | keyPassword = System.getenv("RELEASE_KEY_PASSPHRASE")
137 | }
138 | }
139 | buildTypes {
140 | getByName("debug") {
141 | applicationIdSuffix = ".debug"
142 | }
143 |
144 | getByName("release") {
145 | isMinifyEnabled = true
146 | isShrinkResources = true
147 | proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
148 |
149 | signingConfig = signingConfigs.getByName("release")
150 | }
151 | }
152 | compileOptions {
153 | // https://issuetracker.google.com/issues/382527248
154 | sourceCompatibility(JavaVersion.VERSION_17)
155 | targetCompatibility(JavaVersion.VERSION_17)
156 | }
157 | buildFeatures {
158 | viewBinding = true
159 | }
160 | }
161 |
162 | val archive = tasks.register("archive") {
163 | inputs.property("gitVersionTriple.third", gitVersionTriple.third)
164 |
165 | val outputFile = archiveDir.map { it.file("archive.tar") }
166 | outputs.file(outputFile)
167 |
168 | doLast {
169 | val format = "tar_for_task_$name"
170 |
171 | ArchiveCommand.registerFormat(format, TarFormat())
172 | try {
173 | outputFile.get().asFile.outputStream().use {
174 | git.archive()
175 | .setTree(git.repository.resolve(gitVersionTriple.third.name))
176 | .setFormat(format)
177 | .setOutputStream(it)
178 | .call()
179 | }
180 | } finally {
181 | ArchiveCommand.unregisterFormat(format)
182 | }
183 | }
184 | }
185 |
186 | android.applicationVariants.all {
187 | preBuildProvider.configure {
188 | dependsOn(archive)
189 | }
190 | }
191 |
192 | data class LinkRef(val type: String, val number: Int) : Comparable {
193 | override fun compareTo(other: LinkRef): Int = compareValuesBy(
194 | this,
195 | other,
196 | { it.type },
197 | { it.number },
198 | )
199 |
200 | override fun toString(): String = "[$type #$number]"
201 | }
202 |
203 | fun checkBrackets(line: String) {
204 | var expectOpening = true
205 |
206 | for (c in line) {
207 | if (c == '[' || c == ']') {
208 | if (c == '[' != expectOpening) {
209 | throw IllegalArgumentException("Mismatched brackets: $line")
210 | }
211 |
212 | expectOpening = !expectOpening
213 | }
214 | }
215 |
216 | if (!expectOpening) {
217 | throw IllegalArgumentException("Missing closing bracket: $line")
218 | }
219 | }
220 |
221 | fun updateChangelogLinks(baseUrl: String) {
222 | val file = File(rootDir, "CHANGELOG.md")
223 | val regexStandaloneLink = Regex("\\[([^\\]]+)\\](?![\\(\\[])")
224 | val regexAutoLink = Regex("(Issue|PR) #(\\d+)")
225 | val links = hashMapOf()
226 | var skipRemaining = false
227 | val changelog = mutableListOf()
228 |
229 | file.useLines { lines ->
230 | for (rawLine in lines) {
231 | val line = rawLine.trimEnd()
232 |
233 | if (!skipRemaining) {
234 | checkBrackets(line)
235 | val matches = regexStandaloneLink.findAll(line)
236 |
237 | for (linkMatch in matches) {
238 | val linkText = linkMatch.groupValues[1]
239 | val match = regexAutoLink.matchEntire(linkText)
240 | require(match != null) { "Invalid link format: $linkText" }
241 |
242 | val type = match.groupValues[1]
243 | val number = match.groupValues[2].toInt()
244 |
245 | val link = when (type) {
246 | "Issue" -> "$baseUrl/issues/$number"
247 | "PR" -> "$baseUrl/pull/$number"
248 | else -> throw IllegalArgumentException("Unknown link type: $type")
249 | }
250 |
251 | // #0 is used for examples only
252 | if (number != 0) {
253 | links[LinkRef(type, number)] = link
254 | }
255 | }
256 |
257 | if ("Do not manually edit the lines below" in line) {
258 | skipRemaining = true
259 | }
260 |
261 | changelog.add(line)
262 | }
263 | }
264 | }
265 |
266 | for ((ref, link) in links.entries.sortedBy { it.key }) {
267 | changelog.add("$ref: $link")
268 | }
269 |
270 | changelog.add("")
271 |
272 | file.writeText(changelog.joinToString("\n"))
273 | }
274 |
275 | fun updateChangelog(version: String?, replaceFirst: Boolean) {
276 | val file = File(rootDir, "CHANGELOG.md")
277 | val expected = if (version != null) { "### Version $version" } else { "### Unreleased" }
278 |
279 | val changelog = mutableListOf().apply {
280 | // This preserves a trailing newline, unlike File.readLines()
281 | addAll(file.readText().lineSequence())
282 | }
283 |
284 | val index = changelog.indexOfFirst { it.startsWith("### ") }
285 | if (index == -1) {
286 | changelog.addAll(0, listOf(expected, ""))
287 | } else if (changelog[index] != expected) {
288 | if (replaceFirst) {
289 | changelog[index] = expected
290 | } else {
291 | changelog.addAll(index, listOf(expected, ""))
292 | }
293 | }
294 |
295 | file.writeText(changelog.joinToString("\n"))
296 | }
297 |
298 | tasks.register("changelogUpdateLinks") {
299 | doLast {
300 | updateChangelogLinks(projectUrl)
301 | }
302 | }
303 |
304 | tasks.register("changelogPreRelease") {
305 | doLast {
306 | val version = project.property("releaseVersion")
307 |
308 | updateChangelog(version.toString(), true)
309 | }
310 | }
311 |
312 | tasks.register("changelogPostRelease") {
313 | doLast {
314 | updateChangelog(null, false)
315 | }
316 | }
317 |
318 | tasks.register("preRelease") {
319 | dependsOn("changelogUpdateLinks")
320 | dependsOn("changelogPreRelease")
321 | }
322 |
323 | tasks.register("postRelease") {
324 | dependsOn("changelogPostRelease")
325 | }
326 |
--------------------------------------------------------------------------------
/app/images/icon.svg:
--------------------------------------------------------------------------------
1 |
25 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.kts.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | -keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
23 | # Disable obfuscation completely for PixelLight. As an open source project,
24 | # shrinking is the only goal of minification.
25 | -dontobfuscate
26 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
25 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
52 |
53 |
60 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiller3/pixellight/ExperimentalKeys.java:
--------------------------------------------------------------------------------
1 | /*
2 | * SPDX-FileCopyrightText: 2024 Andrew Gunnerson
3 | * SPDX-License-Identifier: GPL-3.0-only
4 | */
5 |
6 | package com.chiller3.pixellight;
7 |
8 | import android.hardware.camera2.CameraCharacteristics;
9 | import android.hardware.camera2.CaptureRequest;
10 |
11 | /**
12 | * Private Pixel-specific camera2 keys. These keys are normally present in the
13 | * /vendor/framework/com.google.android.camera.experimental[suffix].jar library. It's possible to
14 | * reference the libraries in the manifest and use reflection to access the fields. However, this
15 | * puts a maintenance burden on this project because the name of the library changes with every new
16 | * Pixel device generation. On the other hand, the actual keys have not changed since their initial
17 | * introduction.
18 | */
19 | public final class ExperimentalKeys {
20 | private static final String NS_2020 = "com.google.pixel.experimental2020";
21 |
22 | public static final CaptureRequest.Key REQUEST_FLASHLIGHT_BRIGHTNESS =
23 | new CaptureRequest.Key<>(NS_2020 + ".flashlightBrightness", Integer.TYPE);
24 | public static final CaptureRequest.Key REQUEST_FLASHLIGHT_BRIGHTNESS_ENABLED =
25 | new CaptureRequest.Key<>(NS_2020 + ".flashlightBrightnessEnabled", Boolean.TYPE);
26 | public static final CameraCharacteristics.Key CHARACTERISTICS_FLASHLIGHT_BRIGHTNESS_LEVEL_MAX =
27 | new CameraCharacteristics.Key<>(NS_2020 + ".flashlightBrightnessLevelMax", Integer.TYPE);
28 | }
29 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiller3/pixellight/MainActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * SPDX-FileCopyrightText: 2024 Andrew Gunnerson
3 | * SPDX-License-Identifier: GPL-3.0-only
4 | */
5 |
6 | package com.chiller3.pixellight;
7 |
8 | import android.app.Activity;
9 | import android.content.ComponentName;
10 | import android.content.Context;
11 | import android.content.Intent;
12 | import android.content.ServiceConnection;
13 | import android.content.pm.PackageManager;
14 | import android.os.Bundle;
15 | import android.os.IBinder;
16 | import android.view.Menu;
17 | import android.view.MenuItem;
18 | import android.view.View;
19 | import android.widget.CompoundButton;
20 | import android.widget.SeekBar;
21 |
22 | import androidx.annotation.NonNull;
23 | import androidx.annotation.Nullable;
24 |
25 | import com.chiller3.pixellight.databinding.MainActivityBinding;
26 |
27 | import java.util.Arrays;
28 |
29 | public class MainActivity extends Activity implements ServiceConnection, TorchSession.Listener,
30 | SeekBar.OnSeekBarChangeListener, CompoundButton.OnCheckedChangeListener {
31 | private static final int REQUEST_PERMISSIONS = 1;
32 |
33 | private MainActivityBinding binding;
34 | private Preferences prefs;
35 | private TorchService.TorchBinder torchBinder;
36 | private boolean initialUpdate = true;
37 |
38 | @Override
39 | protected void onCreate(@Nullable Bundle savedInstanceState) {
40 | super.onCreate(savedInstanceState);
41 |
42 | binding = MainActivityBinding.inflate(getLayoutInflater());
43 | setContentView(binding.getRoot());
44 |
45 | prefs = new Preferences(this);
46 |
47 | binding.brightness.setEnabled(false);
48 | binding.brightness.setOnSeekBarChangeListener(this);
49 |
50 | binding.toggle.setEnabled(false);
51 | binding.toggle.setOnCheckedChangeListener(this);
52 |
53 | binding.requestPermissions.setOnClickListener(v ->
54 | requestPermissions(Permissions.REQUIRED, REQUEST_PERMISSIONS));
55 | }
56 |
57 | @Override
58 | public boolean onCreateOptionsMenu(Menu menu) {
59 | getMenuInflater().inflate(R.menu.main_activity_options, menu);
60 |
61 | menu.findItem(R.id.keep_service_alive).setChecked(prefs.getKeepServiceAlive());
62 |
63 | return super.onCreateOptionsMenu(menu);
64 | }
65 |
66 | @Override
67 | public boolean onOptionsItemSelected(@NonNull MenuItem item) {
68 | if (item.getItemId() == R.id.keep_service_alive) {
69 | item.setChecked(!item.isChecked());
70 | prefs.setKeepServiceAlive(item.isChecked());
71 |
72 | if (!item.isChecked() && torchBinder != null) {
73 | // Try to shut down the service so that the user doesn't have to manually turn the
74 | // torch on and off for the change to take effect.
75 | torchBinder.tryStopService();
76 | }
77 |
78 | return true;
79 | } else {
80 | return super.onOptionsItemSelected(item);
81 | }
82 | }
83 |
84 | @Override
85 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
86 | @NonNull int[] grantResults) {
87 | if (requestCode == REQUEST_PERMISSIONS) {
88 | if (Arrays.stream(grantResults).allMatch(r -> r == PackageManager.PERMISSION_GRANTED)) {
89 | refreshUiGroups();
90 | refreshCameras();
91 | } else if (!Permissions.canRequestRequired(this)) {
92 | startActivity(Permissions.getAppInfoIntent(this));
93 | }
94 | }
95 | }
96 |
97 | private void refreshUiGroups() {
98 | final var haveRequired = Permissions.haveRequired(this);
99 | binding.torchGroup.setVisibility(haveRequired ? View.VISIBLE : View.GONE);
100 | binding.permissionGroup.setVisibility(haveRequired ? View.GONE : View.VISIBLE);
101 | }
102 |
103 | private void refreshCameras() {
104 | if (torchBinder != null) {
105 | initialUpdate = true;
106 | torchBinder.refreshCameras();
107 | }
108 | }
109 |
110 | @Override
111 | protected void onStart() {
112 | super.onStart();
113 |
114 | refreshUiGroups();
115 |
116 | final var intent = new Intent(this, TorchService.class);
117 | bindService(intent, this, Context.BIND_AUTO_CREATE);
118 | }
119 |
120 | @Override
121 | protected void onStop() {
122 | super.onStop();
123 |
124 | onBinderGone();
125 | unbindService(this);
126 | }
127 |
128 | @Override
129 | public void onServiceConnected(ComponentName name, IBinder service) {
130 | torchBinder = (TorchService.TorchBinder) service;
131 | torchBinder.registerTorchListener(this);
132 | }
133 |
134 | @Override
135 | public void onServiceDisconnected(ComponentName name) {
136 | onBinderGone();
137 | }
138 |
139 | private void onBinderGone() {
140 | if (torchBinder != null) {
141 | torchBinder.unregisterTorchListener(this);
142 | }
143 |
144 | torchBinder = null;
145 | }
146 |
147 | @Override
148 | public void onTorchStateChanged(int curBrightness, int maxBrightness) {
149 | if (initialUpdate) {
150 | binding.brightness.setMin(1);
151 | binding.brightness.setMax(maxBrightness);
152 | binding.brightness.setProgress(prefs.getBrightness(maxBrightness));
153 | initialUpdate = false;
154 | }
155 |
156 | if (curBrightness == 0) {
157 | binding.brightness.setEnabled(false);
158 | } else {
159 | binding.brightness.setProgress(curBrightness);
160 | binding.brightness.setEnabled(true);
161 | }
162 |
163 | binding.toggle.setEnabled(true);
164 | binding.toggle.setChecked(curBrightness != 0);
165 |
166 | binding.label.setText(curBrightness + " / " + maxBrightness);
167 | }
168 |
169 | @Override
170 | public void onTorchError(@NonNull TorchError error) {
171 | // Retry if async ordering didn't allow onRequestPermissionsResult() to do the refresh.
172 | if (error == TorchError.NO_PERMISSION && Permissions.haveRequired(this)) {
173 | refreshCameras();
174 | }
175 | }
176 |
177 | @Override
178 | public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
179 | if (seekBar == binding.brightness && fromUser) {
180 | torchBinder.setTorchBrightness(progress);
181 | prefs.setBrightness(progress);
182 | }
183 | }
184 |
185 | @Override
186 | public void onStartTrackingTouch(SeekBar seekBar) {}
187 |
188 | @Override
189 | public void onStopTrackingTouch(SeekBar seekBar) {}
190 |
191 | @Override
192 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
193 | // On configuration change, this may be invoked before the service is bound.
194 | if (buttonView == binding.toggle && torchBinder != null) {
195 | if (isChecked) {
196 | torchBinder.setTorchBrightness(binding.brightness.getProgress());
197 | } else {
198 | torchBinder.setTorchBrightness(0);
199 | }
200 | }
201 | }
202 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/chiller3/pixellight/MainApplication.java:
--------------------------------------------------------------------------------
1 | /*
2 | * SPDX-FileCopyrightText: 2024 Andrew Gunnerson
3 | * SPDX-License-Identifier: GPL-3.0-only
4 | */
5 |
6 | package com.chiller3.pixellight;
7 |
8 | import android.app.Application;
9 |
10 | public class MainApplication extends Application {
11 | @Override
12 | public void onCreate() {
13 | super.onCreate();
14 |
15 | new Notifications(this).updateChannels();
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiller3/pixellight/Notifications.java:
--------------------------------------------------------------------------------
1 | /*
2 | * SPDX-FileCopyrightText: 2022-2024 Andrew Gunnerson
3 | * SPDX-License-Identifier: GPL-3.0-only
4 | */
5 |
6 | package com.chiller3.pixellight;
7 |
8 | import android.app.Notification;
9 | import android.app.NotificationChannel;
10 | import android.app.NotificationManager;
11 | import android.app.PendingIntent;
12 | import android.content.Context;
13 | import android.content.Intent;
14 | import android.util.Pair;
15 |
16 | import androidx.annotation.NonNull;
17 | import androidx.annotation.StringRes;
18 |
19 | import java.util.Arrays;
20 | import java.util.List;
21 |
22 | public class Notifications {
23 | public static final String CHANNEL_ID_PERSISTENT = "persistent";
24 | public static final String CHANNEL_ID_ERROR = "error";
25 | public static final int ID_PERSISTENT = 1;
26 | public static final int ID_ERROR = 2;
27 |
28 | private final Context context;
29 | private final NotificationManager notificationManager;
30 |
31 | public Notifications(@NonNull Context context) {
32 | this.context = context;
33 | notificationManager = context.getSystemService(NotificationManager.class);
34 | }
35 |
36 | private NotificationChannel createPersistentChannel() {
37 | final var channel = new NotificationChannel(CHANNEL_ID_PERSISTENT,
38 | context.getString(R.string.notification_channel_persistent_name),
39 | NotificationManager.IMPORTANCE_LOW);
40 | channel.setDescription(context.getString(R.string.notification_channel_persistent_desc));
41 | return channel;
42 | }
43 |
44 | private NotificationChannel createErrorChannel() {
45 | final var channel = new NotificationChannel(CHANNEL_ID_ERROR,
46 | context.getString(R.string.notification_channel_error_name),
47 | NotificationManager.IMPORTANCE_HIGH);
48 | channel.setDescription(context.getString(R.string.notification_channel_error_desc));
49 | return channel;
50 | }
51 |
52 | public void updateChannels() {
53 | notificationManager.createNotificationChannels(Arrays.asList(
54 | createPersistentChannel(),
55 | createErrorChannel()
56 | ));
57 | }
58 |
59 | public Notification createPersistentNotification(@StringRes int titleResId,
60 | List> actions) {
61 | final var notificationIntent = new Intent(context, MainActivity.class);
62 | final var pendingIntent = PendingIntent.getActivity(
63 | context, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
64 |
65 | final var builder = new Notification.Builder(context, CHANNEL_ID_PERSISTENT);
66 | builder.setContentTitle(context.getText(titleResId));
67 | builder.setSmallIcon(R.drawable.ic_notifications);
68 | builder.setContentIntent(pendingIntent);
69 | builder.setOngoing(true);
70 | builder.setOnlyAlertOnce(true);
71 |
72 | for (final var pair : actions) {
73 | final var actionPendingIntent = PendingIntent.getService(context, 0, pair.second,
74 | PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
75 | | PendingIntent.FLAG_ONE_SHOT);
76 | builder.addAction(new Notification.Action.Builder(
77 | null, context.getString(pair.first), actionPendingIntent).build());
78 | }
79 |
80 | // Inhibit 10-second delay when showing persistent notification.
81 | builder.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE);
82 |
83 | return builder.build();
84 | }
85 |
86 | public void sendErrorNotification(@NonNull TorchError error) {
87 | final var builder = new Notification.Builder(context, CHANNEL_ID_ERROR);
88 | builder.setContentTitle(context.getString(error.toUiString()));
89 | builder.setSmallIcon(R.drawable.ic_notifications);
90 |
91 | notificationManager.notify(ID_ERROR, builder.build());
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiller3/pixellight/Permissions.java:
--------------------------------------------------------------------------------
1 | /*
2 | * SPDX-FileCopyrightText: 2024 Andrew Gunnerson
3 | * SPDX-License-Identifier: GPL-3.0-only
4 | */
5 |
6 | package com.chiller3.pixellight;
7 |
8 | import android.Manifest;
9 | import android.app.Activity;
10 | import android.content.Context;
11 | import android.content.Intent;
12 | import android.content.pm.PackageManager;
13 | import android.net.Uri;
14 | import android.provider.Settings;
15 |
16 | import androidx.annotation.NonNull;
17 |
18 | import java.util.Arrays;
19 |
20 | public class Permissions {
21 | public static final String[] REQUIRED = new String[] {
22 | Manifest.permission.CAMERA,
23 | Manifest.permission.POST_NOTIFICATIONS,
24 | };
25 |
26 | private Permissions() {}
27 |
28 | public static boolean haveRequired(@NonNull Context context) {
29 | return Arrays.stream(REQUIRED).allMatch(p ->
30 | context.checkSelfPermission(p) == PackageManager.PERMISSION_GRANTED);
31 | }
32 |
33 | public static boolean canRequestRequired(@NonNull Activity activity) {
34 | return Arrays.stream(REQUIRED).allMatch(activity::shouldShowRequestPermissionRationale);
35 | }
36 |
37 | public static @NonNull Intent getAppInfoIntent(@NonNull Context context) {
38 | final var uri = Uri.fromParts("package", context.getPackageName(), null);
39 | return new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, uri);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiller3/pixellight/Preferences.java:
--------------------------------------------------------------------------------
1 | /*
2 | * SPDX-FileCopyrightText: 2024 Andrew Gunnerson
3 | * SPDX-License-Identifier: GPL-3.0-only
4 | */
5 |
6 | package com.chiller3.pixellight;
7 |
8 | import android.content.Context;
9 | import android.content.SharedPreferences;
10 | import android.preference.PreferenceManager;
11 |
12 | import androidx.annotation.NonNull;
13 |
14 | public class Preferences {
15 | private static final String PREF_BRIGHTNESS = "brightness";
16 | private static final String PREF_KEEP_SERVICE_ALIVE = "keep_service_alive";
17 |
18 | private final SharedPreferences prefs;
19 |
20 | public Preferences(@NonNull Context context) {
21 | prefs = PreferenceManager.getDefaultSharedPreferences(context);
22 | }
23 |
24 | public int getBrightness(int defaultValue) {
25 | return prefs.getInt(PREF_BRIGHTNESS, defaultValue);
26 | }
27 |
28 | public void setBrightness(int value) {
29 | prefs.edit().putInt(PREF_BRIGHTNESS, value).apply();
30 | }
31 |
32 | public boolean getKeepServiceAlive() {
33 | return prefs.getBoolean(PREF_KEEP_SERVICE_ALIVE, false);
34 | }
35 |
36 | public void setKeepServiceAlive(boolean keep) {
37 | prefs.edit().putBoolean(PREF_KEEP_SERVICE_ALIVE, keep).apply();
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiller3/pixellight/ToggleActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * SPDX-FileCopyrightText: 2024-2025 Andrew Gunnerson
3 | * SPDX-License-Identifier: GPL-3.0-only
4 | */
5 |
6 | package com.chiller3.pixellight;
7 |
8 | import android.app.Activity;
9 | import android.content.Context;
10 | import android.content.Intent;
11 | import android.os.Bundle;
12 |
13 | import androidx.annotation.NonNull;
14 | import androidx.annotation.Nullable;
15 |
16 | /**
17 | * This is an exported activity for toggling the torch state or changing the brightness. This also
18 | * allows the quick settings tile to launch the while-in-use foreground service, which is no longer
19 | * possible from the tile's context in Android 15.
20 | */
21 | public class ToggleActivity extends Activity {
22 | /** This is exported. Do not rename. */
23 | private static final String EXTRA_BRIGHTNESS = "brightness";
24 |
25 | public static @NonNull Intent createIntent(@NonNull Context context, int brightness) {
26 | final var intent = new Intent(context, ToggleActivity.class);
27 | intent.putExtra(EXTRA_BRIGHTNESS, brightness);
28 | return intent;
29 | }
30 |
31 | @Override
32 | protected void onCreate(@Nullable Bundle savedInstanceState) {
33 | super.onCreate(savedInstanceState);
34 |
35 | final var brightness = getIntent().getIntExtra(EXTRA_BRIGHTNESS, TorchSession.BRIGHTNESS_TOGGLE);
36 | final var serviceIntent = TorchService.createSetBrightnessIntent(this, brightness);
37 | startForegroundService(serviceIntent);
38 |
39 | finish();
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiller3/pixellight/TorchError.java:
--------------------------------------------------------------------------------
1 | /*
2 | * SPDX-FileCopyrightText: 2024 Andrew Gunnerson
3 | * SPDX-License-Identifier: GPL-3.0-only
4 | */
5 |
6 | package com.chiller3.pixellight;
7 |
8 | import android.hardware.camera2.CameraAccessException;
9 |
10 | import androidx.annotation.NonNull;
11 | import androidx.annotation.StringRes;
12 |
13 | public enum TorchError {
14 | NO_PERMISSION,
15 | BLOCKED_BY_POLICY,
16 | DISCONNECTED,
17 | DEVICE_ERROR,
18 | SERVICE_ERROR,
19 | SESSION_ERROR,
20 | IN_USE,
21 | MAXIMUM_IN_USE,
22 | NO_VALID_CAMERA,
23 | UNKNOWN;
24 |
25 | public @StringRes int toUiString() {
26 | return switch (this) {
27 | case NO_PERMISSION -> R.string.notification_error_no_permission;
28 | case BLOCKED_BY_POLICY -> R.string.notification_error_blocked_by_policy;
29 | case DISCONNECTED -> R.string.notification_error_disconnected;
30 | case DEVICE_ERROR -> R.string.notification_error_device_error;
31 | case SERVICE_ERROR -> R.string.notification_error_service_error;
32 | case SESSION_ERROR -> R.string.notification_error_session_error;
33 | case IN_USE -> R.string.notification_error_in_use;
34 | case MAXIMUM_IN_USE -> R.string.notification_error_maximum_in_use;
35 | case NO_VALID_CAMERA -> R.string.notification_error_no_valid_camera;
36 | case UNKNOWN -> R.string.notification_error_unknown;
37 | };
38 | }
39 |
40 | public static TorchError fromException(@NonNull CameraAccessException exception) {
41 | return switch (exception.getReason()) {
42 | case CameraAccessException.CAMERA_DISABLED -> BLOCKED_BY_POLICY;
43 | case CameraAccessException.CAMERA_DISCONNECTED -> DISCONNECTED;
44 | case CameraAccessException.CAMERA_ERROR -> DEVICE_ERROR;
45 | case CameraAccessException.CAMERA_IN_USE -> IN_USE;
46 | case CameraAccessException.MAX_CAMERAS_IN_USE -> MAXIMUM_IN_USE;
47 | default -> UNKNOWN;
48 | };
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiller3/pixellight/TorchService.java:
--------------------------------------------------------------------------------
1 | /*
2 | * SPDX-FileCopyrightText: 2024-2025 Andrew Gunnerson
3 | * SPDX-License-Identifier: GPL-3.0-only
4 | */
5 |
6 | package com.chiller3.pixellight;
7 |
8 | import android.app.Service;
9 | import android.content.Context;
10 | import android.content.Intent;
11 | import android.content.pm.ServiceInfo;
12 | import android.net.Uri;
13 | import android.os.Binder;
14 | import android.os.IBinder;
15 | import android.util.Log;
16 | import android.util.Pair;
17 |
18 | import androidx.annotation.MainThread;
19 | import androidx.annotation.NonNull;
20 | import androidx.annotation.Nullable;
21 |
22 | import java.util.Collections;
23 |
24 | /** Service for managing the torch state that can be bound. */
25 | public class TorchService extends Service implements TorchSession.ServiceOwner, TorchSession.Listener {
26 | private static final String TAG = TorchService.class.getSimpleName();
27 |
28 | private static final String ACTION_SET_BRIGHTNESS =
29 | TorchService.class.getCanonicalName() + ".set_brightness";
30 | private static final String ACTION_PERSIST =
31 | TorchService.class.getCanonicalName() + ".persist";
32 |
33 | private static final String EXTRA_BRIGHTNESS = "brightness";
34 |
35 | private TorchSession session;
36 | private Preferences prefs;
37 | private Notifications notifications;
38 | private int curBrightness = -1;
39 | private boolean initialUpdate = true;
40 | private boolean foreground = false;
41 |
42 | public static @NonNull Intent createSetBrightnessIntent(
43 | @NonNull Context context, int brightness) {
44 | final var intent = new Intent(context, TorchService.class);
45 | intent.setAction(ACTION_SET_BRIGHTNESS);
46 | // This is unused, but necessary to ensure that intents for different brightnesses are
47 | // treated as unique when used with PendingIntent.
48 | intent.setData(Uri.fromParts(EXTRA_BRIGHTNESS, Integer.toString(brightness), null));
49 | intent.putExtra(EXTRA_BRIGHTNESS, brightness);
50 | return intent;
51 | }
52 |
53 | private static @NonNull Intent createPersistIntent(@NonNull Context context) {
54 | final var intent = new Intent(context, TorchService.class);
55 | intent.setAction(ACTION_PERSIST);
56 | return intent;
57 | }
58 |
59 | @Override
60 | @Nullable
61 | public IBinder onBind(Intent intent) {
62 | return new TorchBinder();
63 | }
64 |
65 | @Override
66 | public void onCreate() {
67 | super.onCreate();
68 | Log.d(TAG, "Creating service");
69 |
70 | session = new TorchSession(this, this);
71 | prefs = new Preferences(this);
72 | notifications = new Notifications(this);
73 |
74 | session.registerTorchListener(this);
75 | }
76 |
77 | @Override
78 | public void onDestroy() {
79 | super.onDestroy();
80 | Log.d(TAG, "Destroying service");
81 |
82 | session.unregisterTorchListener(this);
83 |
84 | if (session.isOwnerNeeded()) {
85 | throw new IllegalStateException("Service destroyed while session still requires it");
86 | }
87 | }
88 |
89 | @Override
90 | public int onStartCommand(Intent intent, int flags, int startId) {
91 | Log.d(TAG, "Received intent: " + intent);
92 |
93 | final var action = intent != null ? intent.getAction() : null;
94 |
95 | if (ACTION_SET_BRIGHTNESS.equals(action)) {
96 | final var brightness = intent.getIntExtra(EXTRA_BRIGHTNESS, TorchSession.BRIGHTNESS_TOGGLE);
97 | session.setTorchBrightness(brightness);
98 | } else if (ACTION_PERSIST.equals(action)) {
99 | Log.d(TAG, "Keeping service alive");
100 | } else {
101 | Log.w(TAG, "Invalid intent: " + intent);
102 | tryStopService();
103 | }
104 |
105 | return START_NOT_STICKY;
106 | }
107 |
108 | private void updateForegroundNotification() {
109 | // If we're here, then we're the service owner. Thus, if we don't have the initial state
110 | // yet, we can still assume that the torch is off.
111 | final var message = curBrightness > 0
112 | ? R.string.notification_persistent_torch_on
113 | : R.string.notification_persistent_torch_off;
114 | final var actionText = curBrightness > 0
115 | ? R.string.notification_action_turn_off
116 | : R.string.notification_action_turn_on;
117 | final var actionBrightness = curBrightness > 0 ? 0 : TorchSession.BRIGHTNESS_PERSISTED;
118 | final var actionIntent = createSetBrightnessIntent(this, actionBrightness);
119 | final var notification = notifications.createPersistentNotification(
120 | message, Collections.singletonList(new Pair<>(actionText, actionIntent)));
121 | final var type = ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA;
122 | startForeground(Notifications.ID_PERSISTENT, notification, type);
123 |
124 | foreground = true;
125 | }
126 |
127 | public void tryStopService() {
128 | final var ownerNeeded = session.isOwnerNeeded();
129 | Log.d(TAG, "Attempting to stop service: ownerNeeded=" + ownerNeeded);
130 |
131 | if (prefs.getKeepServiceAlive()) {
132 | Log.d(TAG, "Keeping service alive indefinitely");
133 | } else if (!ownerNeeded) {
134 | Log.d(TAG, "Stopping foreground service");
135 | stopForeground(Service.STOP_FOREGROUND_REMOVE);
136 |
137 | foreground = false;
138 |
139 | Log.d(TAG, "Stopping service");
140 | stopSelf();
141 | } else {
142 | Log.d(TAG, "Cannot stop service yet");
143 | }
144 | }
145 |
146 | @Override
147 | public void onTorchOwnerNeeded(boolean needService, boolean needForeground) {
148 | if (needService) {
149 | Log.d(TAG, "Starting service to keep it alive");
150 | startService(createPersistIntent(this));
151 |
152 | if (needForeground) {
153 | Log.d(TAG, "Moving service to foreground for camera access");
154 | updateForegroundNotification();
155 | }
156 | } else {
157 | tryStopService();
158 | }
159 | }
160 |
161 | @Override
162 | public void onTorchStateChanged(int curBrightness, int maxBrightness) {
163 | this.curBrightness = curBrightness;
164 |
165 | if (initialUpdate) {
166 | initialUpdate = false;
167 | } else {
168 | updateForegroundNotification();
169 | }
170 | }
171 |
172 | @Override
173 | public void onTorchError(@NonNull TorchError error) {
174 | notifications.sendErrorNotification(error);
175 | }
176 |
177 | public class TorchBinder extends Binder {
178 | @MainThread
179 | public void registerTorchListener(@NonNull TorchSession.Listener listener) {
180 | session.registerTorchListener(listener);
181 | }
182 |
183 | @MainThread
184 | public void unregisterTorchListener(@NonNull TorchSession.Listener listener) {
185 | session.unregisterTorchListener(listener);
186 | }
187 |
188 | @MainThread
189 | public void setTorchBrightness(int brightness) {
190 | session.setTorchBrightness(brightness);
191 | }
192 |
193 | @MainThread
194 | public void refreshCameras() {
195 | session.refreshCameras();
196 | }
197 |
198 | @MainThread
199 | public boolean isInForeground() {
200 | return foreground;
201 | }
202 |
203 | @MainThread
204 | public void tryStopService() {
205 | TorchService.this.tryStopService();
206 | }
207 | }
208 | }
209 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiller3/pixellight/TorchSession.java:
--------------------------------------------------------------------------------
1 | /*
2 | * SPDX-FileCopyrightText: 2024 Andrew Gunnerson
3 | * SPDX-License-Identifier: GPL-3.0-only
4 | */
5 |
6 | package com.chiller3.pixellight;
7 |
8 | import android.content.Context;
9 | import android.graphics.SurfaceTexture;
10 | import android.hardware.camera2.CameraAccessException;
11 | import android.hardware.camera2.CameraCaptureSession;
12 | import android.hardware.camera2.CameraDevice;
13 | import android.hardware.camera2.CameraManager;
14 | import android.hardware.camera2.CameraMetadata;
15 | import android.hardware.camera2.CaptureRequest;
16 | import android.hardware.camera2.params.OutputConfiguration;
17 | import android.hardware.camera2.params.SessionConfiguration;
18 | import android.os.Handler;
19 | import android.os.HandlerThread;
20 | import android.os.Looper;
21 | import android.util.Log;
22 | import android.view.Surface;
23 |
24 | import androidx.annotation.MainThread;
25 | import androidx.annotation.NonNull;
26 |
27 | import java.util.Collections;
28 | import java.util.HashSet;
29 | import java.util.concurrent.Executor;
30 | import java.util.concurrent.RejectedExecutionException;
31 |
32 | /**
33 | * A type to manage the lifecycle of the torch. The lifecycle begins when the torch is turned on and
34 | * ends when it turns off.
35 | */
36 | public class TorchSession {
37 | private enum State {
38 | OFF,
39 | ACTIVATING,
40 | ON,
41 | }
42 |
43 | private static final String TAG = TorchSession.class.getSimpleName();
44 |
45 | public static final int BRIGHTNESS_TOGGLE = -2;
46 | public static final int BRIGHTNESS_PERSISTED = -1;
47 |
48 | // Things following the object lifecycle.
49 | private final Handler mainHandler = new Handler(Looper.getMainLooper());
50 | private final HashSet listeners = new HashSet<>();
51 | private final ServiceOwner serviceOwner;
52 | private final CameraManager cameraManager;
53 | private final HandlerThread cameraThread = new HandlerThread("CameraThread");
54 | private final Handler cameraHandler;
55 | private final Executor cameraExecutor = new Executor() {
56 | @Override
57 | public void execute(Runnable command) {
58 | if (!cameraHandler.post(command)) {
59 | throw new RejectedExecutionException("Failed to queue runnable: " + command);
60 | }
61 | }
62 | };
63 | private final SurfaceTexture surfaceTexture = new SurfaceTexture(0);
64 | private final Surface surface = new Surface(surfaceTexture);
65 | private final Preferences prefs;
66 |
67 | // Things following the torch lifecycle.
68 | private State state = State.OFF;
69 | private String cameraId;
70 | private int maxBrightness = -1;
71 | private int curBrightness = 0;
72 | private int desiredBrightness = 0;
73 | private CameraDevice camera;
74 | private CameraCaptureSession session;
75 |
76 | // Callbacks.
77 | private final CameraDevice.StateCallback cameraCallback = new CameraDevice.StateCallback() {
78 | @Override
79 | public void onOpened(@NonNull CameraDevice camera) {
80 | mainHandler.post(() -> onCameraOpened(camera));
81 | }
82 |
83 | @Override
84 | public void onDisconnected(@NonNull CameraDevice camera) {
85 | mainHandler.post(() -> onCameraClosed(camera));
86 | }
87 |
88 | @Override
89 | public void onError(@NonNull CameraDevice camera, int error) {
90 | mainHandler.post(() -> onCameraError(camera, error));
91 | }
92 | };
93 | private final CameraCaptureSession.StateCallback sessionCallback =
94 | new CameraCaptureSession.StateCallback() {
95 | @Override
96 | public void onConfigured(@NonNull CameraCaptureSession session) {
97 | mainHandler.post(() -> onSessionConfigured(session));
98 | }
99 |
100 | @Override
101 | public void onConfigureFailed(@NonNull CameraCaptureSession session) {
102 | mainHandler.post(() -> onSessionConfigureFailed(session));
103 | }
104 | };
105 |
106 | public TorchSession(@NonNull Context context, @NonNull ServiceOwner owner) {
107 | serviceOwner = owner;
108 |
109 | cameraThread.start();
110 | cameraHandler = new Handler(cameraThread.getLooper());
111 |
112 | cameraManager = context.getSystemService(CameraManager.class);
113 |
114 | prefs = new Preferences(context);
115 | }
116 |
117 | @Override
118 | protected void finalize() throws Throwable {
119 | super.finalize();
120 |
121 | cameraThread.quitSafely();
122 |
123 | surface.release();
124 | surfaceTexture.release();
125 | }
126 |
127 | @MainThread
128 | public void registerTorchListener(@NonNull Listener listener) {
129 | Log.d(TAG, "Registering listener: " + listener);
130 |
131 | if (!listeners.add(listener)) {
132 | Log.w(TAG, "Listener was already registered: " + listener);
133 | }
134 |
135 | if (updateCameraDetails()) {
136 | listener.onTorchStateChanged(curBrightness, maxBrightness);
137 | }
138 | }
139 |
140 | @MainThread
141 | public void unregisterTorchListener(@NonNull Listener listener) {
142 | Log.d(TAG, "Unregistering listener: " + listener);
143 |
144 | if (!listeners.remove(listener)) {
145 | Log.w(TAG, "Listener was never registered: " + listener);
146 | }
147 | }
148 |
149 | public boolean isOwnerNeeded() {
150 | return state != State.OFF;
151 | }
152 |
153 | private void notifyOwnerNeeded() {
154 | Log.d(TAG, "Notifying primary owner that foreground mode is needed");
155 | serviceOwner.onTorchOwnerNeeded(true, state != State.OFF);
156 | }
157 |
158 | private void tryNotifyOwnerNotNeeded() {
159 | if (isOwnerNeeded()) {
160 | Log.d(TAG, "Foreground mode is still needed: state=" + state);
161 | } else {
162 | Log.d(TAG, "Notifying primary owner that foreground mode is not needed");
163 | serviceOwner.onTorchOwnerNeeded(false, false);
164 | }
165 | }
166 |
167 | @MainThread
168 | private boolean updateCameraDetails() {
169 | if (cameraId != null) {
170 | return true;
171 | }
172 |
173 | try {
174 | for (final var cameraId : cameraManager.getCameraIdList()) {
175 | final var characteristics = cameraManager.getCameraCharacteristics(cameraId);
176 | final var maxBrightness = characteristics.get(
177 | ExperimentalKeys.CHARACTERISTICS_FLASHLIGHT_BRIGHTNESS_LEVEL_MAX);
178 | if (maxBrightness == null) {
179 | continue;
180 | }
181 |
182 | this.cameraId = cameraId;
183 | this.maxBrightness = maxBrightness;
184 | this.curBrightness = 0;
185 |
186 | Log.d(TAG, "Found camera " + cameraId + " with max brightness " + maxBrightness);
187 |
188 | return true;
189 | }
190 |
191 | Log.e(TAG, "Failed to find suitable camera");
192 | onError(TorchError.NO_VALID_CAMERA);
193 | } catch (CameraAccessException e) {
194 | Log.e(TAG, "Failed to query for suitable cameras", e);
195 | onError(TorchError.fromException(e));
196 | }
197 |
198 | return false;
199 | }
200 |
201 | @MainThread
202 | public void refreshCameras() {
203 | if (updateCameraDetails()) {
204 | for (final var listener : listeners) {
205 | listener.onTorchStateChanged(curBrightness, maxBrightness);
206 | }
207 | }
208 | }
209 |
210 | @MainThread
211 | public void setTorchBrightness(int brightness) {
212 | Log.d(TAG, "User requesting brightness of " + brightness);
213 |
214 | if (brightness >= 0) {
215 | desiredBrightness = brightness;
216 | } else if (brightness == BRIGHTNESS_PERSISTED) {
217 | desiredBrightness = prefs.getBrightness(maxBrightness);
218 | } else if (brightness == BRIGHTNESS_TOGGLE) {
219 | switch (state) {
220 | case OFF:
221 | desiredBrightness = prefs.getBrightness(maxBrightness);
222 | break;
223 | case ACTIVATING, ON:
224 | desiredBrightness = 0;
225 | break;
226 | }
227 | } else {
228 | Log.w(TAG, "Ignoring invalid brightness value: " + brightness);
229 | return;
230 | }
231 |
232 | desiredBrightness = Math.min(desiredBrightness, maxBrightness);
233 |
234 | if (desiredBrightness == 0) {
235 | closeCamera();
236 | return;
237 | }
238 |
239 | switch (state) {
240 | case OFF -> openCamera();
241 | // Session is not ready yet. It'll pick up the new value when it is ready.
242 | case ACTIVATING -> {}
243 | // Session is already active. Change the brightness with a new capture request.
244 | case ON -> performCapture();
245 | }
246 | }
247 |
248 | @MainThread
249 | private void onError(@NonNull TorchError error) {
250 | Log.w(TAG, "Camera lifecycle exiting due to error: " + error);
251 |
252 | notifyTorchError(error);
253 |
254 | if (state != State.OFF) {
255 | closeCamera();
256 | }
257 | }
258 |
259 | @MainThread
260 | private void openCamera() {
261 | assert state == State.OFF;
262 | state = State.ACTIVATING;
263 |
264 | notifyOwnerNeeded();
265 |
266 | try {
267 | cameraManager.openCamera(cameraId, cameraCallback, cameraHandler);
268 | } catch (CameraAccessException e) {
269 | Log.e(TAG, "Failed to open camera: " + cameraId, e);
270 | onError(TorchError.fromException(e));
271 | } catch (SecurityException e) {
272 | Log.e(TAG, "Permission denied when opening camera: " + cameraId, e);
273 | onError(TorchError.NO_PERMISSION);
274 | }
275 | }
276 |
277 | @MainThread
278 | private void closeCamera() {
279 | // We don't need to close the session. Closing the camera device is sufficient.
280 | session = null;
281 |
282 | if (camera != null) {
283 | camera.close();
284 | camera = null;
285 | }
286 |
287 | final var notifyOwner = state != State.OFF;
288 | state = State.OFF;
289 | curBrightness = 0;
290 |
291 | notifyTorchState();
292 |
293 | // Only notify if the torch was turned on. The service would not have been running in the
294 | // foreground otherwise.
295 | if (notifyOwner) {
296 | tryNotifyOwnerNotNeeded();
297 | }
298 | }
299 |
300 | @MainThread
301 | private void onCameraOpened(@NonNull CameraDevice camera) {
302 | Log.d(TAG, "Camera " + camera.getId() + " opened");
303 |
304 | this.camera = camera;
305 |
306 | final var output = Collections.singletonList(new OutputConfiguration(surface));
307 | final var sessionConfiguration = new SessionConfiguration(
308 | SessionConfiguration.SESSION_REGULAR, output, cameraExecutor, sessionCallback);
309 |
310 | try {
311 | camera.createCaptureSession(sessionConfiguration);
312 | } catch (CameraAccessException e) {
313 | Log.e(TAG, "Failed to create capture session", e);
314 | onError(TorchError.fromException(e));
315 | }
316 | }
317 |
318 | @MainThread
319 | private void onCameraClosed(@NonNull CameraDevice camera) {
320 | Log.e(TAG, "Camera " + camera.getId() + " disconnected");
321 |
322 | onError(TorchError.DISCONNECTED);
323 | }
324 |
325 | @MainThread
326 | private void onCameraError(@NonNull CameraDevice camera, int error) {
327 | Log.e(TAG, "Camera " + camera.getId() + " failed with error: " + error);
328 |
329 | final var torchError = switch (error) {
330 | case CameraDevice.StateCallback.ERROR_CAMERA_IN_USE -> TorchError.IN_USE;
331 | case CameraDevice.StateCallback.ERROR_MAX_CAMERAS_IN_USE -> TorchError.MAXIMUM_IN_USE;
332 | case CameraDevice.StateCallback.ERROR_CAMERA_DISABLED -> TorchError.BLOCKED_BY_POLICY;
333 | case CameraDevice.StateCallback.ERROR_CAMERA_DEVICE -> TorchError.DEVICE_ERROR;
334 | case CameraDevice.StateCallback.ERROR_CAMERA_SERVICE -> TorchError.SERVICE_ERROR;
335 | default -> TorchError.UNKNOWN;
336 | };
337 |
338 | onError(torchError);
339 | }
340 |
341 | @MainThread
342 | private void onSessionConfigured(@NonNull CameraCaptureSession session) {
343 | Log.d(TAG, "Camera session configured: " + session);
344 |
345 | this.session = session;
346 |
347 | performCapture();
348 | }
349 |
350 | @MainThread
351 | private void onSessionConfigureFailed(@NonNull CameraCaptureSession session) {
352 | Log.e(TAG, "Failed to configure session: " + session);
353 |
354 | onError(TorchError.SESSION_ERROR);
355 | }
356 |
357 | @MainThread
358 | private void performCapture() {
359 | try {
360 | assert state == State.ACTIVATING || state == State.ON;
361 | state = State.ON;
362 |
363 | if (curBrightness != desiredBrightness) {
364 | Log.d(TAG, "Performing capture because current brightness (" + curBrightness +
365 | ") != desired brightness (" + desiredBrightness + ")");
366 | curBrightness = desiredBrightness;
367 |
368 | final var captureRequest = session.getDevice()
369 | .createCaptureRequest(CameraDevice.TEMPLATE_MANUAL);
370 | captureRequest.addTarget(surface);
371 | captureRequest.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_TORCH);
372 | captureRequest.set(ExperimentalKeys.REQUEST_FLASHLIGHT_BRIGHTNESS_ENABLED, true);
373 | captureRequest.set(ExperimentalKeys.REQUEST_FLASHLIGHT_BRIGHTNESS, curBrightness);
374 |
375 | session.capture(captureRequest.build(), null, cameraHandler);
376 |
377 | notifyTorchState();
378 | }
379 | } catch (CameraAccessException e) {
380 | Log.e(TAG, "Failed to perform capture", e);
381 | onError(TorchError.fromException(e));
382 | }
383 | }
384 |
385 | private void notifyTorchState() {
386 | if (cameraId != null) {
387 | for (final var listener : listeners) {
388 | listener.onTorchStateChanged(curBrightness, maxBrightness);
389 | }
390 | }
391 | }
392 |
393 | private void notifyTorchError(@NonNull TorchError error) {
394 | for (final var listener : listeners) {
395 | listener.onTorchError(error);
396 | }
397 | }
398 |
399 | public interface Listener {
400 | @MainThread
401 | void onTorchStateChanged(int curBrightness, int maxBrightness);
402 |
403 | @MainThread
404 | void onTorchError(@NonNull TorchError error);
405 | }
406 |
407 | public interface ServiceOwner {
408 | @MainThread
409 | void onTorchOwnerNeeded(boolean needService, boolean needForeground);
410 | }
411 | }
412 |
--------------------------------------------------------------------------------
/app/src/main/java/com/chiller3/pixellight/TorchTileService.java:
--------------------------------------------------------------------------------
1 | /*
2 | * SPDX-FileCopyrightText: 2024-2025 Andrew Gunnerson
3 | * SPDX-License-Identifier: GPL-3.0-only
4 | */
5 |
6 | package com.chiller3.pixellight;
7 |
8 | import android.app.PendingIntent;
9 | import android.content.ComponentName;
10 | import android.content.Context;
11 | import android.content.Intent;
12 | import android.content.ServiceConnection;
13 | import android.os.IBinder;
14 | import android.service.quicksettings.Tile;
15 | import android.service.quicksettings.TileService;
16 | import android.util.Log;
17 |
18 | import androidx.annotation.NonNull;
19 |
20 | /** Quick settings tile for toggling the torch status. The last selected brightness is used. */
21 | public class TorchTileService extends TileService implements ServiceConnection, TorchSession.Listener {
22 | private static final String TAG = TorchTileService.class.getSimpleName();
23 |
24 | private TorchService.TorchBinder torchBinder;
25 | private int curBrightness = -1;
26 |
27 | @Override
28 | public void onStartListening() {
29 | super.onStartListening();
30 | Log.d(TAG, "Tile is listening");
31 |
32 | final var intent = new Intent(this, TorchService.class);
33 | bindService(intent, this, Context.BIND_AUTO_CREATE);
34 |
35 | refreshTileState();
36 | }
37 |
38 | @Override
39 | public void onStopListening() {
40 | super.onStopListening();
41 | Log.d(TAG, "Tile is no longer listening");
42 |
43 | onBinderGone();
44 | unbindService(this);
45 | }
46 |
47 | @Override
48 | public void onServiceConnected(ComponentName name, IBinder service) {
49 | torchBinder = (TorchService.TorchBinder) service;
50 | torchBinder.registerTorchListener(this);
51 | }
52 |
53 | @Override
54 | public void onServiceDisconnected(ComponentName name) {
55 | onBinderGone();
56 | }
57 |
58 | private void onBinderGone() {
59 | if (torchBinder != null) {
60 | torchBinder.unregisterTorchListener(this);
61 | }
62 |
63 | torchBinder = null;
64 | }
65 |
66 | @Override
67 | public void onClick() {
68 | super.onClick();
69 |
70 | // With Android 15, it is no longer process to start a foreground service that relies on
71 | // while-in-use permissions, regardless if that's another service or the TileService itself.
72 | // We have no choice but to provide a worse experience and perform the operation through an
73 | // activity.
74 |
75 | final int newBrightness;
76 |
77 | if (curBrightness == -1) {
78 | Log.w(TAG, "onClick was reachable before camera session was ready");
79 | return;
80 | } else if (curBrightness == 0) {
81 | Log.d(TAG, "Toggling torch on");
82 | newBrightness = TorchSession.BRIGHTNESS_PERSISTED;
83 | } else {
84 | Log.d(TAG, "Toggling torch off");
85 | newBrightness = 0;
86 | }
87 |
88 | if (torchBinder.isInForeground()) {
89 | // With Android 15, we can't start a camera foreground service from a tile service
90 | // anymore, but we can connect to a previously started instance just fine.
91 | torchBinder.setTorchBrightness(newBrightness);
92 | } else {
93 | final var intent = ToggleActivity.createIntent(this, newBrightness);
94 |
95 | startActivityAndCollapse(PendingIntent.getActivity(
96 | this, 0, intent,
97 | PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT));
98 | }
99 |
100 | // The tile state will be changed when onTorchStateChanged() is called.
101 | }
102 |
103 | private void refreshTileState() {
104 | final var tile = getQsTile();
105 | if (tile == null) {
106 | Log.w(TAG, "Tile was null during refreshTileState");
107 | return;
108 | }
109 |
110 | if (curBrightness < 0) {
111 | tile.setState(Tile.STATE_UNAVAILABLE);
112 | } else if (curBrightness == 0) {
113 | tile.setState(Tile.STATE_INACTIVE);
114 | } else {
115 | tile.setState(Tile.STATE_ACTIVE);
116 | }
117 |
118 | tile.updateTile();
119 | }
120 |
121 | @Override
122 | public void onTorchStateChanged(int curBrightness, int maxBrightness) {
123 | Log.d(TAG, "New torch state: current=" + curBrightness + ", max=" + maxBrightness);
124 | this.curBrightness = curBrightness;
125 | refreshTileState();
126 | }
127 |
128 | @Override
129 | public void onTorchError(@NonNull TorchError error) {
130 | if (error == TorchError.NO_PERMISSION) {
131 | final var intent = new Intent(this, MainActivity.class);
132 | intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
133 |
134 | startActivityAndCollapse(PendingIntent.getActivity(
135 | this, 0, intent, PendingIntent.FLAG_IMMUTABLE));
136 | }
137 | }
138 | }
139 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
11 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
13 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_notifications.xml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/main_activity.xml:
--------------------------------------------------------------------------------
1 |
5 |
12 |
13 |
19 |
20 |
25 |
26 |
31 |
32 |
37 |
38 |
39 |
45 |
46 |
51 |
52 |
58 |
59 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/main_activity_options.xml:
--------------------------------------------------------------------------------
1 |
5 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/app/src/main/res/values-notnight/bools.xml:
--------------------------------------------------------------------------------
1 |
5 |
6 | true
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/bools.xml:
--------------------------------------------------------------------------------
1 |
5 |
6 | false
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
5 |
6 | Request permissions
7 | The camera permission is required to access the private Google Pixel API for using the full brightness range. The notification permission is required to keep the flashlight on in the background.
8 |
9 | Keep service alive
10 |
11 | Background services
12 | Persistent notification required for running in the background
13 | Errors
14 | Alerts shown when errors occur
15 | Flashlight is on
16 | Flashlight is off
17 | Turn on
18 | Turn off
19 | Camera permission is required
20 | Camera access is blocked by device policy
21 | Camera disconnected
22 | Camera device failed with fatal error
23 | Android camera service failed with fatal error
24 | Android camera session failed with fatal error
25 | Camera is currently in use by another app
26 | Maximum number of cameras are already in use
27 | No camera device with suitable flash found
28 | Camera failed with unknown error
29 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings_notranslate.xml:
--------------------------------------------------------------------------------
1 |
5 |
6 | PixelLight
7 |
8 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
5 |
6 |
11 |
12 |
--------------------------------------------------------------------------------
/build.gradle.kts:
--------------------------------------------------------------------------------
1 | /*
2 | * SPDX-FileCopyrightText: 2024 Andrew Gunnerson
3 | * SPDX-License-Identifier: GPL-3.0-only
4 | */
5 |
6 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
7 | plugins {
8 | alias(libs.plugins.android.application) apply false
9 | }
10 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Kotlin code style for this project: "official" or "obsolete":
19 | kotlin.code.style=official
20 |
--------------------------------------------------------------------------------
/gradle/libs.versions.toml:
--------------------------------------------------------------------------------
1 | [versions]
2 | android-gradle-plugin = "8.10.0"
3 | jgit = "7.2.1.202505142326-r"
4 |
5 | [libraries]
6 | jgit = { group = "org.eclipse.jgit", name = "org.eclipse.jgit", version.ref = "jgit" }
7 | jgit-archive = { group = "org.eclipse.jgit", name = "org.eclipse.jgit.archive", version.ref = "jgit" }
8 |
9 | [plugins]
10 | android-application = { id = "com.android.application", version.ref = "android-gradle-plugin" }
11 |
--------------------------------------------------------------------------------
/gradle/update_verification.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | # SPDX-FileCopyrightText: 2023-2024 Andrew Gunnerson
4 | # SPDX-License-Identifier: GPL-3.0-only
5 |
6 | import hashlib
7 | import io
8 | import os
9 | import subprocess
10 | import sys
11 | import tempfile
12 | import urllib.request
13 | import xml.etree.ElementTree as ET
14 |
15 |
16 | GOOGLE_MAVEN_REPO = 'https://dl.google.com/android/maven2'
17 |
18 |
19 | def add_source_exclusions(ns, root):
20 | configuration = root.find(f'{{{ns}}}configuration')
21 | trusted_artifacts = ET.SubElement(
22 | configuration, f'{{{ns}}}trusted-artifacts')
23 |
24 | for regex in [
25 | r'.*-javadoc[.]jar',
26 | r'.*-sources[.]jar',
27 | r'.*-src[.]zip',
28 | ]:
29 | ET.SubElement(trusted_artifacts, f'{{{ns}}}trust', attrib={
30 | 'file': regex,
31 | 'regex': 'true',
32 | })
33 |
34 |
35 | def add_missing_aapt2_platforms(ns, root):
36 | components = root.find(f'{{{ns}}}components')
37 | aapt2 = components.find(f'{{{ns}}}component[@name="aapt2"]')
38 |
39 | for platform in ['linux', 'osx', 'windows']:
40 | group = aapt2.attrib['group']
41 | name = aapt2.attrib['name']
42 | version = aapt2.attrib['version']
43 | filename = f'{name}-{version}-{platform}.jar'
44 |
45 | if aapt2.find(f'{{{ns}}}artifact[@name="{filename}"]') is not None:
46 | continue
47 |
48 | path = f'{group.replace(".", "/")}/{name}/{version}/{filename}'
49 | url = f'{GOOGLE_MAVEN_REPO}/{path}'
50 |
51 | with urllib.request.urlopen(url) as r:
52 | if r.status != 200:
53 | raise Exception(f'{url} returned HTTP {r.status}')
54 |
55 | digest = hashlib.file_digest(r, 'sha512')
56 |
57 | artifact = ET.SubElement(aapt2, f'{{{ns}}}artifact',
58 | attrib={'name': filename})
59 |
60 | ET.SubElement(artifact, f'{{{ns}}}sha512', attrib={
61 | 'value': digest.hexdigest(),
62 | 'origin': 'Generated by Gradle',
63 | })
64 |
65 | aapt2[:] = sorted(aapt2, key=lambda child: child.attrib['name'])
66 |
67 |
68 | def patch_xml(path):
69 | tree = ET.parse(path)
70 | root = tree.getroot()
71 |
72 | ns = 'https://schema.gradle.org/dependency-verification'
73 | ET.register_namespace('', ns)
74 |
75 | # Add exclusions to allow Android Studio to download sources.
76 | add_source_exclusions(ns, root)
77 |
78 | # Gradle only adds the aapt2 entry for the host OS. We have to manually add
79 | # the checksums for the other major desktop OSs.
80 | add_missing_aapt2_platforms(ns, root)
81 |
82 | # Match gradle's formatting exactly.
83 | ET.indent(tree, ' ')
84 | root.tail = '\n'
85 |
86 | with io.BytesIO() as f:
87 | # etree's xml_declaration=True uses single quotes in the header.
88 | f.write(b'\n')
89 | tree.write(f)
90 | serialized = f.getvalue().replace(b' />', b'/>')
91 |
92 | with open(path, 'wb') as f:
93 | f.write(serialized)
94 |
95 |
96 | def main():
97 | root_dir = os.path.join(sys.path[0], '..')
98 | xml_file = os.path.join(sys.path[0], 'verification-metadata.xml')
99 |
100 | try:
101 | os.remove(xml_file)
102 | except FileNotFoundError:
103 | pass
104 |
105 | # Gradle will sometimes fail to add verification entries for artifacts that
106 | # are already cached.
107 | with tempfile.TemporaryDirectory() as temp_dir:
108 | env = os.environ | {'GRADLE_USER_HOME': temp_dir}
109 |
110 | subprocess.check_call(
111 | [
112 | './gradlew' + ('.bat' if os.name == 'nt' else ''),
113 | '--write-verification-metadata', 'sha512',
114 | '--no-daemon',
115 | 'build',
116 | 'connectedDebugAndroidTest',
117 | # Requires signing.
118 | '-x', 'assembleRelease',
119 | ],
120 | env=env,
121 | cwd=root_dir,
122 | )
123 |
124 | patch_xml(xml_file)
125 |
126 |
127 | if __name__ == '__main__':
128 | main()
129 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chenxiaolong/PixelLight/8e3ede5f9e85c2692fad6c3b6cf158ddd4a7254a/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionSha256Sum=845952a9d6afa783db70bb3b0effaae45ae5542ca2bb7929619e8af49cb634cf
4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.1-bin.zip
5 | networkTimeout=10000
6 | validateDistributionUrl=true
7 | zipStoreBase=GRADLE_USER_HOME
8 | zipStorePath=wrapper/dists
9 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 | # SPDX-License-Identifier: Apache-2.0
19 | #
20 |
21 | ##############################################################################
22 | #
23 | # Gradle start up script for POSIX generated by Gradle.
24 | #
25 | # Important for running:
26 | #
27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
28 | # noncompliant, but you have some other compliant shell such as ksh or
29 | # bash, then to run this script, type that shell name before the whole
30 | # command line, like:
31 | #
32 | # ksh Gradle
33 | #
34 | # Busybox and similar reduced shells will NOT work, because this script
35 | # requires all of these POSIX shell features:
36 | # * functions;
37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
39 | # * compound commands having a testable exit status, especially «case»;
40 | # * various built-in commands including «command», «set», and «ulimit».
41 | #
42 | # Important for patching:
43 | #
44 | # (2) This script targets any POSIX shell, so it avoids extensions provided
45 | # by Bash, Ksh, etc; in particular arrays are avoided.
46 | #
47 | # The "traditional" practice of packing multiple parameters into a
48 | # space-separated string is a well documented source of bugs and security
49 | # problems, so this is (mostly) avoided, by progressively accumulating
50 | # options in "$@", and eventually passing that to Java.
51 | #
52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
54 | # see the in-line comments for details.
55 | #
56 | # There are tweaks for specific operating systems such as AIX, CygWin,
57 | # Darwin, MinGW, and NonStop.
58 | #
59 | # (3) This script is generated from the Groovy template
60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
61 | # within the Gradle project.
62 | #
63 | # You can find Gradle at https://github.com/gradle/gradle/.
64 | #
65 | ##############################################################################
66 |
67 | # Attempt to set APP_HOME
68 |
69 | # Resolve links: $0 may be a link
70 | app_path=$0
71 |
72 | # Need this for daisy-chained symlinks.
73 | while
74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
75 | [ -h "$app_path" ]
76 | do
77 | ls=$( ls -ld "$app_path" )
78 | link=${ls#*' -> '}
79 | case $link in #(
80 | /*) app_path=$link ;; #(
81 | *) app_path=$APP_HOME$link ;;
82 | esac
83 | done
84 |
85 | # This is normally unused
86 | # shellcheck disable=SC2034
87 | APP_BASE_NAME=${0##*/}
88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH="\\\"\\\""
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | if ! command -v java >/dev/null 2>&1
137 | then
138 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
139 |
140 | Please set the JAVA_HOME variable in your environment to match the
141 | location of your Java installation."
142 | fi
143 | fi
144 |
145 | # Increase the maximum file descriptors if we can.
146 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
147 | case $MAX_FD in #(
148 | max*)
149 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
150 | # shellcheck disable=SC2039,SC3045
151 | MAX_FD=$( ulimit -H -n ) ||
152 | warn "Could not query maximum file descriptor limit"
153 | esac
154 | case $MAX_FD in #(
155 | '' | soft) :;; #(
156 | *)
157 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
158 | # shellcheck disable=SC2039,SC3045
159 | ulimit -n "$MAX_FD" ||
160 | warn "Could not set maximum file descriptor limit to $MAX_FD"
161 | esac
162 | fi
163 |
164 | # Collect all arguments for the java command, stacking in reverse order:
165 | # * args from the command line
166 | # * the main class name
167 | # * -classpath
168 | # * -D...appname settings
169 | # * --module-path (only if needed)
170 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
171 |
172 | # For Cygwin or MSYS, switch paths to Windows format before running java
173 | if "$cygwin" || "$msys" ; then
174 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
175 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
176 |
177 | JAVACMD=$( cygpath --unix "$JAVACMD" )
178 |
179 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
180 | for arg do
181 | if
182 | case $arg in #(
183 | -*) false ;; # don't mess with options #(
184 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
185 | [ -e "$t" ] ;; #(
186 | *) false ;;
187 | esac
188 | then
189 | arg=$( cygpath --path --ignore --mixed "$arg" )
190 | fi
191 | # Roll the args list around exactly as many times as the number of
192 | # args, so each arg winds up back in the position where it started, but
193 | # possibly modified.
194 | #
195 | # NB: a `for` loop captures its iteration list before it begins, so
196 | # changing the positional parameters here affects neither the number of
197 | # iterations, nor the values presented in `arg`.
198 | shift # remove old arg
199 | set -- "$@" "$arg" # push replacement arg
200 | done
201 | fi
202 |
203 |
204 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
205 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
206 |
207 | # Collect all arguments for the java command:
208 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
209 | # and any embedded shellness will be escaped.
210 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
211 | # treated as '${Hostname}' itself on the command line.
212 |
213 | set -- \
214 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
215 | -classpath "$CLASSPATH" \
216 | -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
217 | "$@"
218 |
219 | # Stop when "xargs" is not available.
220 | if ! command -v xargs >/dev/null 2>&1
221 | then
222 | die "xargs is not available"
223 | fi
224 |
225 | # Use "xargs" to parse quoted args.
226 | #
227 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
228 | #
229 | # In Bash we could simply go:
230 | #
231 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
232 | # set -- "${ARGS[@]}" "$@"
233 | #
234 | # but POSIX shell has neither arrays nor command substitution, so instead we
235 | # post-process each arg (as a line of input to sed) to backslash-escape any
236 | # character that might be a shell metacharacter, then use eval to reverse
237 | # that process (while maintaining the separation between arguments), and wrap
238 | # the whole thing up as a single "set" statement.
239 | #
240 | # This will of course break if any of these variables contains a newline or
241 | # an unmatched quote.
242 | #
243 |
244 | eval "set -- $(
245 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
246 | xargs -n1 |
247 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
248 | tr '\n' ' '
249 | )" '"$@"'
250 |
251 | exec "$JAVACMD" "$@"
252 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 | @rem SPDX-License-Identifier: Apache-2.0
17 | @rem
18 |
19 | @if "%DEBUG%"=="" @echo off
20 | @rem ##########################################################################
21 | @rem
22 | @rem Gradle startup script for Windows
23 | @rem
24 | @rem ##########################################################################
25 |
26 | @rem Set local scope for the variables with windows NT shell
27 | if "%OS%"=="Windows_NT" setlocal
28 |
29 | set DIRNAME=%~dp0
30 | if "%DIRNAME%"=="" set DIRNAME=.
31 | @rem This is normally unused
32 | set APP_BASE_NAME=%~n0
33 | set APP_HOME=%DIRNAME%
34 |
35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
37 |
38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
40 |
41 | @rem Find java.exe
42 | if defined JAVA_HOME goto findJavaFromJavaHome
43 |
44 | set JAVA_EXE=java.exe
45 | %JAVA_EXE% -version >NUL 2>&1
46 | if %ERRORLEVEL% equ 0 goto execute
47 |
48 | echo. 1>&2
49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
50 | echo. 1>&2
51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2
52 | echo location of your Java installation. 1>&2
53 |
54 | goto fail
55 |
56 | :findJavaFromJavaHome
57 | set JAVA_HOME=%JAVA_HOME:"=%
58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
59 |
60 | if exist "%JAVA_EXE%" goto execute
61 |
62 | echo. 1>&2
63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
64 | echo. 1>&2
65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2
66 | echo location of your Java installation. 1>&2
67 |
68 | goto fail
69 |
70 | :execute
71 | @rem Setup the command line
72 |
73 | set CLASSPATH=
74 |
75 |
76 | @rem Execute Gradle
77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
78 |
79 | :end
80 | @rem End local scope for the variables with windows NT shell
81 | if %ERRORLEVEL% equ 0 goto mainEnd
82 |
83 | :fail
84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
85 | rem the _cmd.exe /c_ return code!
86 | set EXIT_CODE=%ERRORLEVEL%
87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
89 | exit /b %EXIT_CODE%
90 |
91 | :mainEnd
92 | if "%OS%"=="Windows_NT" endlocal
93 |
94 | :omega
95 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | /*
2 | * SPDX-FileCopyrightText: 2024 Andrew Gunnerson
3 | * SPDX-License-Identifier: GPL-3.0-only
4 | */
5 |
6 | pluginManagement {
7 | repositories {
8 | gradlePluginPortal()
9 | google()
10 | mavenCentral()
11 | }
12 | }
13 | dependencyResolutionManagement {
14 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
15 | repositories {
16 | google()
17 | mavenCentral()
18 | }
19 | }
20 | rootProject.name = "PixelLight"
21 | include(":app")
22 |
--------------------------------------------------------------------------------