Compare commits

...
84 Commits
Author SHA1 Message Date
TMC 4710171559 Release 1.0.7 2026-11-18 14:47:45 +01:00
TMCandClaude Opus 5.5 29ffb83e66 release.ps1: start-up check on the Flexera emulator, not just the first one
Step 4 installed the APK on the first emulator adb listed. Another
project's emulator (a Pixel_9a AVD) runs beside this one at times, and
was running when 1.0.7 was about to be built: had it come first, the
release would have been installed and started there. The step now picks
the emulator named Flexera_Launcher_A17, or the only emulator running,
and stops when there are several and none has that name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:47:34 +01:00
TMCandClaude Opus 5.5 6e88f7c81b Grid and margins: draw the margins in the preview; fit them to the rows
The owner reported that the preview did not show the top and bottom
margins. On the emulator it did, but little: the rows share the height
the margins leave, so a first row moves by less than the margin, and
at about 40% of real size a 16 dp margin moves it some 6 dp. On a page
with few icons that is hard to see. At large values it also went wrong
the other way: a phone's grid (not scalable) does not shrink its icons
to fit shorter rows, so with labels on, 120 dp top and bottom cut off
the last row's labels (cell height 201 px, rows got 179 px).

Now:
- The preview draws the margins: tinted bands along the sides and
  above and below the rows, as wide as they are laid out, and a dashed
  outline around the rows (HomeMargins.Guides, through a new overlay
  slot in GridOverridesPreview). They show however empty the page is.
- Top and bottom margins take only the height the rows can spare
  beyond their icons and labels, cut in proportion
  (HomeMargins.fitTopBottom, in DeviceProfile.updateWorkspacePadding);
  DeviceProfile keeps what it laid out (flexeraTopMarginPx,
  flexeraBottomMarginPx) for the guides.
- When the grid has room for less than the sliders ask, a note under
  them says so and that fewer rows or columns leave more room.
- The class comment no longer claims that rows too short get smaller
  icons; that was wrong for these grids.

Tested on the emulator: guides on a 5x5 and a 4x9 grid line up with
the rows and columns; on 5x5 with labels 120/120 fits whole and no
label is cut; on 4x9 with labels the bands shrink to what fits and the
note shows; 8, 0, 0 leaves the layout as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 14:44:33 +01:00
TMCandClaude Opus 5.5 b092105ed9 Website: version 1.0.6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:18:16 +01:00
TMC 2cdb779dac Release 1.0.6 2026-11-18 13:12:01 +01:00
TMCandClaude Opus 5.5 be15483e34 Home screen margins: on the grid page, with its live preview
The side, top and bottom margins move from the Home screen settings to
the grid page, renamed "Grid and margins", under its preview of the
home screen. The preview shows the margins being chosen together with
the columns, rows and dock icons, and nothing changes on the home
screen until Apply.

The preview builds its own InvariantDeviceProfile from
PreviewOverrides, as it does for a foldable's dock icons; the overrides
now carry the three margins, the IDP keeps them for the device profiles
it makes (set before initGrid, which makes them), and DeviceProfile
uses them in place of the kept preferences. Apply writes them with the
grid. HomeScreenGridPreferences keeps a little more room for the
settings under the preview (0.46 of the height instead of 0.40), as its
own comment asks when preferences are added.

Tested on the emulator: the page shows the preview; 40, 48, 48 dp moved
the preview's columns in and rows down while the launcher still
reported 8 dp and 0; after Apply the home screen matched the preview;
8, 0, 0 and Apply restored it. The Home screen page lists "Grid and
margins" and no longer has the sliders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:57:28 +01:00
TMCandClaude Opus 5.5 0306c1d2ce Website: version 1.0.5
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:43:19 +01:00
TMC 06e90a1479 Release 1.0.5 2026-11-18 12:36:12 +01:00
TMCandClaude Opus 5.5 ec5b36c482 Home screen: side, top and bottom margins in dp
Settings, Home screen, Layout had Horizontal padding and Vertical
padding, as percentages from 0 to 200. They scaled the grid's own
margins, which on a phone are 8 dp at the sides and nothing at the top
and bottom (measured on the emulator: desiredWorkspaceHorizontalMarginPx
21 px, workspace top and bottom padding 0). So the whole horizontal
range moved the outer icons by a few dp and the vertical one did
nothing at all, and the settings seemed broken.

They are replaced by three sliders in dp (app.flexera.home.HomeMargins):
Side margins (0 to 48, default 8, the grid's own), Top margin and
Bottom margin (0 to 120, default 0, added to the grid's own). Rows and
columns share the room that is left, so larger margins also bring the
icons closer together. Rows that become too short get smaller icons, as
Launcher3 already does; side margins are capped so that every column
stays wider than what is seen of its icon plus 4 dp. The old factors
are read as 1 from now on, so a value set with the old sliders no
longer applies.

Hooks: DeviceProfile (side margin where the grid's margin is set, top
and bottom where the workspace padding is), PreferenceManager2 (three
int preferences that reload the grid), HomeScreenPreferences (the
sliders), each marked "Flexera Launcher:".

Tested on the emulator: at the defaults the home screen is pixel for
pixel as before (apart from clocks showing the time); 40, 48, 48 moves
the columns in and the rows down and closer, with no overlap; back to
8, 0, 0 restores the layout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:27:09 +01:00
TMCandClaude Opus 5.5 f0b728199a Website: version 1.0.4
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 10:55:20 +01:00
TMC 3b4c42f80d Release 1.0.4 2026-11-18 10:47:25 +01:00
TMCandClaude Opus 5.5 305be7512d Updates: ask to allow notifications when an update is found
The daily check posts "Flexera Launcher x.y.z is available" when it
finds a newer version, but only if the app may post notifications. On
Android 13 and newer that is off until the app asks, and nothing asked:
on the emulator both the release and the debug build had
POST_NOTIFICATIONS never granted and never requested, so no update
notification could appear after a fresh install unless the owner found
the "Notify me about updates" row in About.

Now, when an automatic check finds an update and the permission is not
granted, the updater asks for it from the home screen or settings,
whichever is in front, at most twice (as often as Android itself lets
an app ask). The notification waits and is posted on the next resume
once notifications are allowed, from the prompt or later from Android's
settings. Notifications the owner turned off in Android's settings stay
off, since the permission is granted then and nothing is asked.

Tested with a debug build temporarily set to 1.0.2 with the updater
switched on (both reverted): the check found 1.0.3, the prompt
appeared over the home screen, and after Allow the notification
"Flexera Launcher 1.0.3 is available" was in the shade.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:50:46 +01:00
TMCandClaude Opus 5.5 acc25baaff Clock widget: weather icon, size slider with preview, fonts, tap apps
Weather icon. The weather line now starts with a picture of the sky,
drawn by the launcher (WeatherIcon): sun, moon, clouds, fog, drizzle,
rain, freezing rain, snow, showers and thunder, with the moon from
sunset to sunrise. The forecast request also asks for today's sunrise
and sunset at the place, so the picture turns to night on time between
two requests; readings kept by 1.0.3 still load. Color uses warm and
blue tones, brighter beside light text and deeper beside dark text;
Plain draws it in the text colour; None leaves it out. A ray of the sun
that a cloud would clip is left out whole instead of leaving a stub.

Size slider with a preview. The three sizes become a slider, from 0.4
to 1.6 icon heights; a clock set to Small, Medium or Large keeps that
size. The options sheet starts with a preview of the clock as it is on
the home screen: the widget's own view at the widget's size and text
colour, on the wallpaper's colours, scaled to fit. It stays in view
while the options scroll under it. The slider ends where the widget
has no more room, with a note to make the widget bigger.

Fonts. The figures can be in the phone's font, Google Sans Flex at
three widths (Flex, Narrow, Wide; the variable font Lawnchair already
carries, read from a cache copy so its axes apply), Serif or Mono. The
cards in the picker draw their samples with the clock's own code.

Taps. A "Tap to open" section picks the app for a tap on the time and
date (the clock app until one is picked) and for a tap on the weather
line (the same as the time until one is picked), from the launcher's
own Pick app list, each with Reset. On the widget the part under the
finger dims while pressed, and the app opens out of that part. A picked
app that is gone gives the "isn't installed" message Quick launch uses.
TalkBack: the double tap names the app it opens, and a separately
chosen weather app is one more action.

Tested on the emulator (Android 17): every sky by day and night, both
taps, Reset, the slider on two-row and one-row widgets, each font, the
keyboard over the sheet, and the migration of a 1.0.3 "large" clock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 09:40:54 +01:00
TMCandClaude Fable 5.2 46864e98a6 Website: Plausible visit counter, and the site's address for link previews
The page loads the owner's Plausible script from plausible.mariosem.es. The
link-preview picture, og:url and the canonical link now name
https://flexera.mariosem.es/, where the site is served.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 18:58:44 +01:00
TMCandClaude Fable 5.2 752ad2c806 Website: version 1.0.3
The page shows the version released today, in script.js and in the
fallback under Install.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 17:12:46 +01:00
TMC b6047a5881 Release 1.0.3 2026-11-16 17:00:03 +01:00
TMCandClaude Fable 5.2 7b4e939d9e Website: a new look, a three-phone lineup, motion, and what it takes to put it online
The look follows UI8's SimpleList landing kit: a near-black canvas, one
typeface (Outfit, the launcher's own), white pill buttons, large cards.

The top shows three stills side by side instead of one phone in a card:
the home screen's edge, the list scrubbed to F (in front, with the
icon's sweep on its rim) and quick launch, each with a one-sentence
caption. Under 700 px the list has a row to itself.

Motion: an entrance when the page shows (the headline word by word, the
phones rising, the thumb coming down and the wave going out), sections
that rise into place when scrolled to, a bar that turns to glass, light
that follows the scroll position and the pointer. None of it for reduced
motion, and nothing is hidden without JavaScript.

The footer credits NOMNOM Inc., with an egg on the name, and no longer
carries the version line. The head has a title and description of search
length, the link-preview tags with the card's size, and a
SoftwareApplication record. The card, assets/og.jpg, is remade from the
site by flexera/website/make-og.mjs. og:image is still relative: the
site's address was not known, and README.md says where it goes.

The page said version 1.0.0; it says 1.0.2. On a phone, the story's text
is no longer dimmed and three tap targets are 44 px.

flexera/website/make-production.mjs copies what the page loads into
WEBSITE/PRODUCTION, the folder to upload; docker-compose.yml and
nginx.conf serve that folder.

Checked in Chrome over its DevTools port, in real time: 360 to 1440 px
wide, touch on the playground, reduced motion, print, no JavaScript, and
the production folder over HTTP and in the nginx container. Not checked
on a real phone or in another browser.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 16:57:53 +01:00
TMCandClaude Fable 5.2 38e93c3889 Folders: real icons for every app, and a fade in place when full screen
A folder opened soon after the launcher started could show blank spots
where some of its apps should be. Apps in a folder, other than those in
its icon's preview, were loaded as placeholders, and their icons were
fetched when the folder opened, on the model thread, which is busy with
the rest of the load for a while after every start and reload. With
labels off and no panel behind a full-screen folder, the placeholders
looked like missing apps. Reported from the owner's phone on 2026-11-16
(a nine-app folder showing its first row only, until some time later).
Seen on the emulator with the 1.0.2 release by restarting the launcher
and opening a folder three seconds later: two of its seven apps were
placeholder discs for about a quarter of a second. Every app in a folder
now gets its icon with the home screen's own (WorkspaceItemProcessor).

A full-screen folder fades in and out where it is
(FolderSpringAnimatorSet.buildInPlace). Its apps are at the bottom of
the screen, not at its icon, and the floating folder's animation, which
moves and scales every app between the icon's preview and its place,
looked over that distance like the apps rearranging themselves. The
folder's icon stays as it is behind the dimmed home screen. A folder
that a drag opens still floats and animates as before.

App views taken from the cache for a folder start at rest (alpha,
translation, scale, locked to the grid), in case an animation that was
cut short left one otherwise.

Checked on the emulator with a debug build: a folder opened about three
seconds after a restart shows every icon from its first frame; opening
and closing is a fade with nothing moving; six fast open, close and
reopen sequences over five folders drew every app, with no crash. Not
checked: a folder opened by dragging an app onto it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 16:57:34 +01:00
TMC 7a814db436 Release 1.0.2 2026-11-15 15:54:12 +01:00
TMCandClaude Opus 5.5 e64675d7e4 RSS reader: cards like a news feed, and articles read in the reader
The posts are cards now, as in the feeds of the phone makers' launchers:
the picture across the top, the title, then the feed's icon (its own
picture, the site's icon, or its first letter on a coloured patch),
name and the post's age in short ("3h"), and a share button. A post
without a picture shows three lines of its text instead.

A tap no longer goes to the site. The post slides in over the list, in
the reader itself: its picture, title, feed, date and author, then its
text, at first what the feed carries (kept per post when the feed is
fetched), then the whole article as soon as it has come. Where the feed
has only the start, the post's page is fetched and the article found
in it, as reading modes do: the element whose paragraphs hold the most
text, joined with the blocks beside it that a page splits an article
into; menus, sharing, related stories and the like taken out; the
page's own title, subtitle, byline, author box and commission notices
removed, so that the article starts at its first real paragraph and
ends at its last. Where that comes to little, the page's structured
data (articleBody) is used. The text is cleaned with jsoup's safelist
and shown by a WebView with no JavaScript and no file access; links
open in the browser. "Visit article" stays at the bottom for the site.
Back, the arrow, or a swipe towards the side it came from takes the
article away; the list beneath blurs as it comes and is hidden while
it is open. A sideways swipe the wrong way on the list no longer opens
the post under it.

Tried on The Verge, Ars Technica and BBC News. Adds jsoup 1.23.2 (MIT).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 15:53:17 +01:00
TMC 8b4089a69c Release 1.0.1 2026-11-15 14:42:35 +01:00
TMCandClaude Opus 5.5 9e8fd59e18 Add an RSS reader that a gesture brings in
"Open RSS reader" is a new gesture action. Set for a swipe past the
first or the last home screen page, it comes in with the finger as
quick launch's app page does: the home screen moves aside and blurs,
and the reader's page follows from that edge. Any other gesture brings
it in on its own. The page has the app drawer's backdrop and white text:
a heading with refresh and settings buttons, then every feed's posts
together, the newest first, each with its feed, its age, two lines of
text and a picture. A tap opens a post in the browser and dims it; a
long press shares the link; pulling the list down refreshes.

It leaves by a swipe back towards the home screen, Back (with the back
preview), Home, the home gesture and any change of launcher state. The
page lies over the drag layer, so a stand-in floating view of a new
type (TYPE_FLEXERA_READER) is in the drag layer while it is in, and
Launcher3 closing it closes the page. The type is rebind-safe, so an
opened post and Back from it leave the reader as it was.

Feeds are added under Settings, Gestures, RSS reader (also reached from
the page) by a feed's or a site's address; a site's feed is found from
its page or at the usual places. RSS 2.0, Atom and RSS 1.0 are read.
Feeds are kept with the other settings, so a backup carries them; the
posts and which were opened are in files/flexera_rss.json. Fetching is
HTTPS only, with conditional requests, when the page opens and the last
fetch is over 15 minutes old, on refresh, and when a feed is added. A
feed on the phone's own network on Android 17 offers the local network
permission, as the updater does.

Quick launch now drives either page through QuickLaunch.EdgePage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 14:36:34 +01:00
TMCandClaude Opus 5.5 5f4e1367ec Full-screen folders: a column count of their own
Settings, Folders, Grid now has a Columns slider for full-screen folders
(2 to 6, or up to the home screen's count when that is higher), next to
the rows. Until it is moved it shows and uses the home screen's columns,
so folders look as before. Fewer columns spread the apps over the home
screen grid's width; more bring them closer together, never more than
fit with a whole icon in each. The floating folder's own column slider
is shown again when full-screen folders are switched off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 14:36:20 +01:00
TMCandClaude Opus 5.5 397b0ac1f7 Website: dark look after the owner's style reference
The page now follows the dark style reference the owner chose, in
Flexera's own colours:

- One near-black canvas with barely raised surfaces, hairline borders
  and inset highlights instead of drop shadows. A frosted floating bar.
  The main actions are light grey buttons; none is coloured.
- Inter for the page, regular weight at large sizes. JetBrains Mono
  for technical text: control labels, table heads, version numbers,
  user agents, the phones' measurements and the strip at the foot.
  Both are served from fonts/ with their licences; nothing loads from
  another server and no font is preloaded.
- Colour comes from the app icon and is rationed: an indigo wash and
  the icon's sweep (cyan to magenta) behind the top figure, magenta
  only on the "New in" badge, cyan only on the phones' marks.
- The phones' made-up wallpaper and themed icons are muted shades of
  the icon's indigo instead of the green of the light design.
- The link-preview image is remade in the new look.

Also fixed on the way: the timed test's grid showed white glyphs on
its icons (Authenticator was a blank square), because the label rule
also hit the icon; the label has its own class now. Start brings the
phone into view clear of the bar. Forced colours show the switch's
state, and the page prints as dark text on white.

Copy is unchanged apart from <code> around the two user agents and a
footer strip with the version, Android 8.0 or newer, and "Free APK,
no ads".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:14:03 +01:00
TMCandClaude Opus 5.5 26a2c0098b Website: version 1.0.0
The page shows 1.0.0, full-screen folders read "New in 1.0.0", and the
weather row says only that its requests name FlexeraLauncher, which is
true from 1.0.0 on. The playground's folder lines no longer point at a
coming version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 21:15:06 +01:00
TMC 57bc4d8cf8 Release 1.0.0 2026-11-14 21:14:20 +01:00
TMCandClaude Opus 5.5 7dfc8f24ea Mark every Flexera edit to Lawnchair and Launcher3 files
Comments only: git grep "Flexera Launcher:" now finds every behaviour
change Flexera made to an upstream file, so that upstream merges stay
easy. A reviewer rebuilt the files as they were before this pass and
found every code token unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 18:50:52 +01:00
TMCandClaude Opus 5.5 f5df10b4cc Release script, manifest and build: fixes from the pre-release audit
release.ps1:
- The release is created as a draft, both APKs are uploaded, then it is
  published, so /releases/latest (and the QR code) never points at a
  release without its APK; a draft left by an interrupted run is cleaned
  up or resumed.
- Before publishing, the APK's signing certificate is compared with the
  release keystore's, so an APK signed with another key is never
  published.
- With -SkipBuild, an APK not built from the commit being tagged is
  refused.

flexera/AndroidManifest.xml: the home screen's database provider is no
longer exported. Lawnchair's manifest removes the definitions of its
READ_SETTINGS and WRITE_SETTINGS permissions, so any app could have
defined them and read or erased the home screen; the launcher itself
never goes through the provider.

build.gradle: github, the channel that is released, is the default
flavour, and Flexera's folders are wired into the nightly and play
variants too, so assembleDebug, lint and Android Studio's default
variant build; the lines Flexera changed carry markers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 18:50:51 +01:00
TMCandClaude Opus 5.5 a800a54592 Blur: no stuck zoom or blur with the depth effect off
With the wallpaper depth effect switched off, opening and closing a
folder no longer brings in the launcher state's zoom and blur, which
could stay on the home screen afterwards: the base depth controller
leaves the state's depth out when the effect is off, while the folder's
and quick launch's own blur still pass through.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 18:50:51 +01:00
TMCandClaude Opus 5.5 e72260e167 Smart Launcher import: fixes from the pre-release audit
- Unpacking has limits: the database 64 MiB, at most 8 preference files
  of 1 MiB, each photo 32 MiB, and 256 MiB for one backup in all.
- The preview says when importing changes the home screen label
  setting, lists work-profile and unusable widgets correctly, and no
  import is offered that would empty the home screens.
- With At a Glance on, items in the first row of the first screen are
  listed as left out instead of being deleted at the next load.
- Progress shows while importing, and the launcher reloads even when the
  owner leaves through Recents.
- Other apps cannot open the import screen with a crafted route, and a
  malformed route no longer crashes the launcher.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 18:50:51 +01:00
TMCandClaude Opus 5.5 e382c1b2dd Updater: fixes from the pre-release audit
- Reopening About during a download no longer deletes the partial APK;
  restoring a finished download only looks at finished files, keeps the
  newest version and deletes older ones.
- A download runs the Android 17 local-network check as a check does; on
  a block it offers "Allow access" for the download too, and retries the
  download afterwards.
- A 404 or other server error is a failed check, never "You have the
  latest version", and deletes nothing.
- TalkBack hears the results of a check and a download; during a
  download the card keeps a disabled button, so focus does not jump.

These take effect from the update after 0.16.0: 0.15.0's own updater
downloads 0.16.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 18:50:50 +01:00
TMCandClaude Opus 5.5 42f728fd82 Widgets: fixes from the pre-release audit
Clock:
- Weather requests send only "FlexeraLauncher" as their user agent, no
  longer Android's, which names the phone model and build.
- Celsius or Fahrenheit follows Android's own temperature setting where
  there is one (Android 14 and newer), else the locale.
- Failed weather requests back off (5, 10, 20, 40, then 45 minutes)
  instead of retrying every time the home screen returns.
- The options sheet's segments switch to a list at large font sizes and
  read left to right for alignment in right-to-left languages; the spoken
  time says AM or PM in 12-hour mode.

Pictures, and both widgets' data:
- When Android restores widgets, the pictures and the clock's options
  move to the new ids instead of being deleted.
- The setup screen survives being recreated while photos are copied;
  photos staged for a widget that never got set up are cleared after the
  home screens load.
- Slides are decoded at about the frame's size, let go of in the
  background, and the slideshow pauses while the widget cannot be seen.
- No "Tap to choose pictures" over the sample while a photo loads; the
  empty widget's hint stays readable at large font sizes, off the sun.
- Canvas-drawn text follows Android's Bold text setting.

The drop animation of another app's widget lands at the size the widget
will have (the icon-aligned inset was added instead of taken off).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 18:50:50 +01:00
TMCandClaude Opus 5.5 ec7d3bc004 Quick launch: fixes from the pre-release audit
- The static map of pages no longer keeps every launcher it was used in
  alive after the launcher is recreated (a memory leak since 0.15.0).
- A chosen app that was uninstalled or disabled gets no page; a short
  message says so.
- While the page slides back, taps land where the icons are drawn.
- Going home right after a quick launch brings the home screen back at
  once instead of leaving it black and untouchable for up to 1.5 s
  (emulator: a folder opened 0.3 s after Home).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 18:50:50 +01:00
TMCandClaude Opus 5.5 4efe37ef9c App list: fixes from the pre-release audit
- Scrub from home works right after the launcher starts. The home edge
  band was measured from the alphabet's own view, which has no size
  until the app list has been shown once (emulator: it now opens at a
  letter straight after an install). It no longer takes over per-icon
  swipe gestures on icons at the edge.
- Holding to scrub no longer undoes "Remember position", and the
  remembered place is saved and restored in the same unit.
- Notification previews: no text Android itself would hide (secret
  notifications, and work-profile ones the ranking redacts); right after
  changes made while the launcher was in the background; also for rows
  held in the list's view cache; only redrawn when the line changed;
  read by TalkBack; set through BubbleTextView's own label handling.
- Light theme: search results, the empty state and the search field are
  readable on the always-dark backdrop (emulator).
- Hide app is not offered for Private Space apps, where it could not
  work, and Private Space adds no blank stop to the alphabet.
- Canvas-drawn letters follow Android's Bold text setting.
- TalkBack list positions ignore the letter headers; the one-column list
  stays one column on foldables in two-panel mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 18:50:49 +01:00
TMCandClaude Opus 5.5 f79b503ffb Full-screen folders: fixes from the pre-release audit
The audit of 2026-11-14 found these in the new full-screen folders, all
confirmed by independent reviewers and checked on the emulator where
marked:
- A folder that a drag opens (hovering an app over its icon) opens as a
  floating folder around its icon again, so the drop lands in it
  (emulator: the app went into the folder). The page for that drag is
  worked out with the grid the folder actually opens with.
- A tap beside the apps or beside the name closes the folder; only the
  name's text starts renaming (emulator). Swipes between pages still
  work from the grid's empty cells.
- Rows are capped to what fits above the folder's bottom margin; extra
  apps go to the next page instead of being cut off.
- A folder that finishes closing no longer resets the backdrop, blur,
  scale and status bar of a folder that has just opened; one still
  closing is finished at once when another opens. A folder animating
  closed also lets a new touch through, so a tap on another folder right
  after closing one opens it (emulator, 0.25 s apart).
- Status bar icons are light over a full-screen folder (a new
  SystemUiController state), and the page dots are white on its backdrop.

flexera_strings.xml carries the new strings of this whole round of
fixes, so that each of the following commits finds them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 18:50:49 +01:00
TMCandClaude Opus 5.5 ea4e823df7 Website: about what Flexera adds, in a hand-made look
The owner asked for two things: stop selling what every launcher has
(Lawnchair's home screen, dock, folders, icon packs, gestures) and sell
what Flexera adds, the wave alphabet app list and swiping past the last
page for an app; and make the page look made by a person rather than by
an AI.

The page is now written in the maker's voice as field notes: a serif on
light paper, the app's own colours, the phones drawn to the app's
measurements with notes in the margin on why things are the way they
are. "The wave alphabet" tells the list and its alphabet chapter by
chapter; "Past the last page" is the one black section, because quick
launch is a black page, and says it needs Android 12 and is off until an
app is chosen. "Smaller things I added" lists full-screen folders
(marked "Coming in 0.16.0", which turns into "New in 0.16.0" once
VERSION reaches it), the left-handed mode and the two widgets. The
playground and a shorter timed test stay; "What goes online" is a table
that says exactly what each request sends, including the clock weather's
user agent before and after 0.16.0; installing and the FAQ close the
page.

Gone: the gradient headlines, bracketed section numbers, marquees, the
rotating badge, stickers, the stats row, the card grid, ghost words, the
neon palette, the tilted phone, magnetic buttons, the custom cursor,
reveal-on-scroll and the Unbounded, Space Grotesk and JetBrains Mono
fonts (their files are deleted; the serif is a system font stack, and
Outfit stays for the phones). The phone model's alphabet is a keyboard
and screen-reader slider. Still no build step and nothing loaded from
any other server; the version shown is 0.15.0.

Made by a workflow of three proposals, two judges, a spec, a builder,
two critics (AI tells; QA and truth against the app's code) and a fix
pass, then checked in headless Chrome at phone and desktop sizes: no
horizontal scroll, no console errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:58:36 +01:00
TMCandClaude Opus 5.5 2a14ae11e0 Full-screen folders: apps at the bottom in the home screen's grid
At the user's request, a folder on the home screen or in the dock opens
over the whole screen instead of as a floating panel. Settings, Folders,
"Full screen folders", on by default; switched off, folders float as
before. Folders in the app list are unchanged.

- No panel. The home screen behind is darkened and blurred as behind the
  app drawer: black at 78% (FlexeraDrawer.BACKDROP_COLOR) and the largest
  blur radius, which the drawer's depth comes to.
- The apps sit at the bottom of the screen, centred, just above the
  navigation bar, with white labels and the folder's name below them,
  wherever the folder's icon is.
- They are laid out like the home screen's icons: its column count,
  filled row by row (FolderGridOrganizer.createFullScreenFolderGridOrganizer),
  in cells the size of the home screen's cells as a page lays them out
  (larger than the device profile's cell size, which the page stretches),
  so that the columns line up with the home screen's. A row is never lower
  than one app with its label needs. The folder icon's preview keeps the
  folder grid.

While a full-screen folder is open, state changes leave the scrim alone
(WorkspaceStateTransitionAnimation.setScrim), so that dragging an app
inside the folder no longer lightens its backdrop; the folder hands the
scrim back as it closes. The depth controller's folder blur now carries
its own strength (FolderBlur.strength); quick launch scales its blur by
FolderBlur.STRENGTH itself and looks as before. While full-screen folders
are on, Settings hides the panel's opacity and the folder column count,
which do not apply to them.

Checked on the emulator (Android 17, 4-column test grid): open, tap an
app, tap outside, Back, rename with the keyboard (the folder lifts above
it), reorder inside the folder (the backdrop holds), drag an app out to
the home screen, the setting off and on again (the floating folder comes
back with its panel, 3 columns and dark labels), and columns and rows
259 and 243 px apart, as on the home screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:01:25 +01:00
TMCandClaude Opus 5.5 a79962e5c4 Keep a floating folder on the screen when its page area is wrong
On the Pixel on 2026-11-14 a folder opened in the top left corner of the
screen, with its apps out of reach; 15 minutes later folders opened
normally again. Launcher3 bounds a folder to the area of the workspace
page it finds with getNextPage(). When that area is empty, the branch for
a folder taller than its bounds centres the folder on the area and skips
the later clamp to the screen, which puts the folder at
(-width/2, -height/2): centred on the top left corner, mostly off the
screen. What made the area empty that morning is not known; the phone's
log of that time is gone.

getFolderBoundingBox now falls back to the screen's area for folders when
the page area is empty or not on the screen, and logs the page indices,
the drag layer's size and the launcher state when it does (tag Launcher),
to find the cause next time. updateOpenFolderPosition keeps the folder
within the drag layer whatever the bounds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:01:25 +01:00
TMC 9026a8ec7a Release 0.15.0 2026-11-13 12:26:22 +01:00
TMCandClaude Opus 5.5 f5d7cf07ed Line up every widget with the icons, as the Pictures widget does
Widgets of other apps used to fill their cells minus Launcher3's widget
padding, which is a few pixels wider than the icons' edges and reaches down
into the room kept for icon labels; on the owner's phone they hung about
13 px past the icons sideways and 40 px below. Now the room a widget keeps in
its cells is the distance from the cell edges to the icon edges, worked out
as IconFrame does for the launcher's own widgets, so every widget's edges
meet the edges of the icons around it.

The one function (FlexeraWidgets.appWidgetPadding) is used for the layout,
for the size the app is told, for the drop animation and through
WidgetSizes for previews. The cells a widget needs are still worked out
with Launcher3's padding, so no widget changes its cell count. A new switch
under Settings, Home screen, Widgets ("Line up with icons", on by default)
turns it off; Lawnchair's Widget padding slider shows only then.

Checked on the emulator against lines drawn at the icon edges: Google
Calendar's widgets meet them within 2 px; Google Clock's sits about 20 px
inside, because it draws an empty margin of its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 12:19:33 +01:00
TMCandClaude Opus 5.5 0dbb146c75 Quick launch: start the app as the finger lifts, with no opening animation
The app used to be started only once the black page had settled, and then
came in with Android's zoom. Now it is started the moment the swipe is
decided, while the page is still settling, with FLAG_ACTIVITY_NO_ANIMATION
and the same intent as its icon, so it appears on the page at full size as
soon as it has a frame. An app still in memory shows its last screen at
once. Apps of another profile still go through LauncherApps, which takes no
flags, and open with the usual animation.

On the emulator, lift to first app frame went from 646 ms to 140 ms
(Camera in memory), 684 ms to 248 ms (Camera closed), and 249 ms for Clock
in memory, which came up on its last screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 12:04:50 +01:00
TMCandClaude Opus 5.5 900071ccac Quick launch: an app opens on a page of its own, with the home screen blurring away
When a swipe past the first or the last home screen page is set to open an
app, the home screen no longer stretches. It moves aside with the finger, as
for a real page, an empty black page comes in from that edge, and the home
screen (icons and wallpaper) blurs and darkens the further it goes. Let go
past 40% of the width, or flick, and the page settles over the whole screen
and the app comes up on it; let go earlier and the home screen comes back.
Swipes set to other actions keep the stretch.

The home screen is moved with the drag layer's animation matrix, which does
not move touch coordinates, so the pages keep reading the same touch. The
blur is a second index on the folder blur's property in the depth controller.
The status bar icons turn light over the black page. Once the app is in
front the launcher stops and the page resets; if nothing comes within 1.5 s
the home screen slides back.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 11:02:10 +01:00
TMCandClaude Opus 5.5 0fbefd2ca6 Website: chapter 8 labels on the layers' corners, one layer at a time; phone centred
Labels: each layer's pin now sits on its outer rounded corner, the
layer's rightmost point, so a tag straight across from it is joined by
a short line that crosses nothing; the stack moves left by just enough
for the tags to fit, and the open stack is a little smaller so it keeps
clear of the chapter's heading. While the stack is open, scrolling walks
through the layers from the glass to the wallpaper: the one looked at
stays bright and its tag lights up cyan, the others dim (where the tags
are shown). Chapter 8 is three screens long for it.

Centring: the labels' list sat in the stage's grid flow, so the grid
split its height into two rows and the story phone was centred in the
top one (about 100 px high on a 1146 px window). It is out of the flow
now; measured equal gaps above and below at 2000 x 1146, 1440 x 900
and 1280 x 720.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 22:20:10 +01:00
TMCandClaude Opus 5.5 058fecd27f Website: the story phone comes apart as its eighth chapter
The separate Under the glass section is gone; its exploded phone is now
chapter 8 of How it works, so the pinned story phone carries straight
into it. After Out of sight the list closes, the drawn phone is swapped
for its layered double (the same home screen closed; measured at about
1-2% of pixels apart, from anti-aliasing), which tilts and comes apart,
holds, and goes back together before the section ends. The chapter is
two screens long and its text stays put meanwhile.

Labels redone: a column of numbered solid tags beside the stack, evenly
spaced, each joined by an elbow line to a dot on its layer's edge; the
stack moves left as it opens to make room. The glass sheen and the frame
now match the drawn phone, so the swap is not seen.

Also fixed: the layered phone sat at its full 414 px until first used,
which made the page wider than a phone and zoomed it out; it is scaled
from the start, and on phones the story stage clips. The story now
counts its progress in chapter heights rather than window heights,
which drifted apart on phones when the address bar hides. The long
chapter's height lost to the general chapter rule; it now wins.

Section numbers close up (Details 02 to Get it 06); the page alphabet's
U leads to the new chapter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 22:11:53 +01:00
TMCandClaude Opus 5.5 6c68cb1369 Website: remove the living wallpaper behind the hero
The flowing bands of light on a canvas behind the hero are gone (markup,
styles, code and the README line); the hero keeps its dark background
with the grid and the two soft glows. The link-preview image is retaken
without them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:59:18 +01:00
TMCandClaude Opus 5.5 f1fa44b086 Website: wave headline, page alphabet, exploded phone, race and more
- Wave headline: the hero's letters swell from weight 560 to 900 around
  the mouse (a wave rolls through on its own without one).
- Page alphabet: one letter per section on the right edge, like the
  launcher's; hover shows the wave and a bubble, drag jumps between
  sections, tap scrolls there; on phones it appears while scrolling.
  Blended so it reads on dark, cyan and violet sections.
- Detail cards are switches now: left-handed alphabet, compact/comfy
  rows and four icon shapes, applied to every phone on the page.
- Under the glass: a new section where the phone pulls apart into its
  layers (wallpaper, widgets, icons, app list, glass) with labels.
- Race: a new section; find an app in a shuffled grid of 40, then in the
  list with the wave alphabet, timed. The list phone reuses the
  playground controller, locked to the list. The phone comes on screen
  before the clock starts.
- Living wallpaper: light bands on a canvas behind the hero.
- Magnetic buttons and a finger cursor over the phones (desktop only).
- Easter eggs: scrub to F in the playground, or type "flexera".
- A vibration tick per letter while scrubbing, on phones that have it.
- 40 generic apps instead of 29; the alphabet now sits from the bottom.
- Fixed: the alphabet's magnifier had no size, so its 300 px svg box
  covered the list once the alphabet moved to the left and took taps.

Reduced motion stops everything that moves on its own. Checked in
Chrome at 1440 x 900 and 390 x 844: no console errors or sideways
scrolling, every playground gesture, the camera chapter without flash,
each switch, both eggs, a full race, and the QR code as drawn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:57:01 +01:00
TMC c93bb1df9c Release 0.14.0 2026-11-12 21:46:11 +01:00
TMCandClaude Opus 5.5 bfb70cab63 Make the update buttons stand out; install right after the download
The Updates section of About is now a card with the status on top and
the next step as a full-width filled button: Check for updates, Download
and install, Install now, or Try again. Before, each step was a plain
settings row that looked like every other row.

Download and install hands the APK to Android's installer as soon as the
download is done, without another tap. If Android first wants this app
to be allowed to install apps, its setting opens, and the installer
follows by itself when the owner comes back having allowed it. The
request is kept on disk for 30 minutes, so it survives Android ending
the process in between but does not pop an installer up hours later.

Tested on the emulator with a release build numbered 0.12.9: check,
download with progress, the Install unknown apps setting, the installer
opening by itself on return, and the update to 0.13.0 from the server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:45:01 +01:00
TMCandClaude Opus 5.5 4746d194f4 Website: no white lines between sections
The sections now meet with a plain change of colour: the white rule at
the bottom of the hero, story, details, privacy, playground and download
sections is gone, as is the white edge of the marquee bands (the tilted
pink band keeps a dark edge where it crosses the cyan one) and the white
line under the menu bar once the page scrolls. Lines inside sections
(cards, stats, FAQ) stay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:31:13 +01:00
TMCandClaude Opus 5.5 12ec415e48 Website: fill the big background words instead of outlining them
Unbounded is a variable font whose letters are built from overlapping
shapes; an outline (text-stroke) traces every overlap, which drew stray
lines inside the hero's giant FLEXERA and the story's chapter number.
Both are now a faint solid fill (the hero's with a cyan-to-violet tint).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:28:07 +01:00
TMCandClaude Opus 5.5 89fa6ef6ca Website: quick launch slides the camera in; no white flash
The camera now behaves as the page to the left of the first one: a swipe
right pushes the home screen (wallpaper included) to the right while the
camera follows the finger in from the left edge, and finishes the slide
when the finger lets go. Before, the home screen rubber-banded and the
camera was revealed by a clip from the edge. Same in the scroll story,
the playground gesture and its demo button; in the playground a short
swipe springs back, and a swipe left slides the camera out again.

The white flash at the end of the camera chapter was a shutter flash
over the whole screen; it read as a glitch while scrolling into the next
chapter. The shutter button now presses in instead.

Checked in Chrome: the camera chapters stepped through in 0.02 steps
show no brightness spike; the playground swipe in, swipe back, short
swipe and demo button; no console errors or sideways scrolling at
1440 x 900 and 390 x 844.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:25:36 +01:00
TMCandClaude Opus 5.5 d273543070 Add the landing page in WEBSITE
One page, English, plain HTML/CSS/JS with no build step and no third-party
requests: the four fonts (OFL) are served from the folder.

Brutal layout in the icon's colours (cyan, electric blue, violet, pink on
near black): hard 2px lines, solid slabs, offset shadows, marquee bands.
The centrepiece is a phone drawn in HTML at 390 x 844, used three times:
a looping teaser in the hero; a scroll-driven story of seven chapters
(home, swipe up, wave-alphabet scrub, folder blur, quick launch, clock
options, hide app) where the scroll position maps to a state, so it plays
both ways; and a playground that answers to touch and mouse (swipe up,
scrub, hold to hide with Undo, folder, quick launch, clock options, page
two, edge swipe home) plus buttons that run each demo.

Also: privacy section ("goes online for exactly two things"), download
with a QR code for the fixed-name latest APK, install steps, FAQ, link
preview image. Reduced motion shows each chapter's finished picture.
Checked in Chrome at 1440 x 900 and 390 x 844: no console errors, no
sideways scrolling, every playground gesture, and the QR as drawn scans.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:13:33 +01:00
TMC c8da9f301c Release 0.13.0 2026-11-12 20:22:17 +01:00
TMCandClaude Fable 5.2 77278a11e0 Hide app from the app list's long-press menu; stop the restart on the first preference write
Hide app: a new entry in the menu a long press on an app opens in the app
list. It adds the app to Lawnchair's hidden list (hidden_apps), which the
list and its search already leave out and which Settings > App drawer >
Hidden apps already shows, so that page is where an app is brought back.
A message with Undo follows. The entry is offered in the app list only
(not for home screen icons, which hiding does not touch) and not while
the home screen is locked.

Preference collectors: five collectors in PreferenceManager2 (icon shape,
dock mode, dock on/off, dock search provider, labels in the dock) had
drop(1) before distinctUntilChanged. The first emission after the dropped
one then always passed, so the first write of any preference after the
launcher started reloaded the model, rebuilt the grid three times and
recreated the launcher. Hiding an app is such a write, made while the
launcher is on screen: the list went blank for a moment and the Undo
message was lost with the old activity. The operators are swapped, so
only a changed value passes.

Checked on the emulator: both menu layouts (labelled rows and the icon
row), hiding right after a fresh start (no relaunch in the log, message
stays), Undo, and unticking the apps under Hidden apps.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 20:21:59 +01:00
TMC 81c5c8914a Release 0.12.0 2026-11-12 18:05:19 +01:00
TMCandClaude Fable 5.2 3b7388c473 Blur behind open folders; hide the icons of a switched-off dock
Folder blur: while a folder is open on the home screen, what is behind it
is blurred, icons and widgets through a RenderEffect and the wallpaper
through the launcher surface's background blur. It is a new input of the
depth controller (folderBlur, 0 to 1), because that controller already
owns both kinds of blur and cleared anything set past it on every frame
of the folder's wallpaper zoom. The folder's spring animation drives it in
step with the dimming, and the places that reset the dimming reset it too.
It works with the wallpaper depth effect switched off, without bringing
the folder's wallpaper zoom along. Setting: Folders > Blur behind open
folders, on by default (flexera_folder_blur). Folders in the app list are
left as they were.

Dock: with the dock switched off the hotseat has no height, but its icons
were still drawn just below the screen edge, and the 97.5% zoom-out behind
an open folder brought their tops into view. One more alpha channel on
the icons hides them.

Checked on the emulator (Android 17 image, window blur available): open,
close by tap outside, Back and Home, an app started from the folder, sleep
and wake, the setting off, and the depth effect off.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 18:01:33 +01:00
TMC 4f687957fb Release 0.11.0 2026-11-12 16:34:02 +01:00
TMCandClaude Fable 5.2 b79579a8dd Clock widget: weather line, font weight, and centring in the widget's own frame
Weather: a clock for which the owner picks a place shows a third line, the
temperature and a word for the sky there. The place is looked up by name in the
clock's options; the data comes from Open-Meteo, which needs no account. It is
off until a place is picked, asks at most every 45 minutes while a clock with
weather is in view, sends only the place's coordinates rounded to about a
kilometre, and needs no location permission. The About screen's note on what
goes online says so.

Font weight: thin, light (as before), regular or bold figures.

Centring: the text stood in the middle of the icons' box, which lies in the
upper part of the widget's cells, so it looked too high inside the outline shown
while editing. It now stands in the middle of the widget's own cells, measured
on what is seen of the text.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 16:33:49 +01:00
TMC 516c4efc56 Release 0.10.0 2026-11-12 15:58:08 +01:00
TMCandClaude Fable 5.2 8e6b737894 Clock widget: smaller by default, with a choice of alignment and size
The first version filled its widget with the figures, which the owner found
huge. The figures are now measured against the icons: small is half an icon
tall, medium (the default) most of an icon, large taller than an icon, with the
widget's own height and width as the limit.

The owner chooses left, center or right and the size from the widget's edit
button. The options are a sheet over the home screen, kept per widget, and each
choice shows on the widget at once.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 15:57:55 +01:00
TMCandClaude Fable 5.2 31ab0d52e1 Add the Clock widget; the QR code leads to the newest APK
Clock is a second widget that comes with the launcher: the time in large light
figures and the date under it, written onto the wallpaper in the colour of the
icon labels. It follows the phone's 12 or 24 hour setting, updates with the
minute, and a tap opens the phone's clock app. Like Pictures it is drawn by the
launcher itself and keeps to the box of the icons in its cells.

What Pictures and Clock share moved into two places: IconFrame works out that
box, and FlexeraWidgets is where Launcher3's widget code asks about the
launcher's own widgets.

The QR code on the About screen now holds the address of the newest APK, so
that scanning it starts the download; the release page's address stays under it
for typing. For that address to work, the release script uploads each APK a
second time under a name that does not change.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 15:42:52 +01:00
TMCandClaude Fable 5.2 04e78205dd Release script: do not take Android's own crash during an APK swap for the app's
When the release build is the emulator's home app, Android restarts it while
the files are still being replaced, and that start can fail inside
ActivityThread.handleBindApplication. The start-up check now waits for the swap
to settle, stops the app, and judges a fresh start.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 14:57:49 +01:00
TMC cef6929a41 Release 0.9.0 2026-11-12 14:36:21 +01:00
TMCandClaude Fable 5.2 fba65e091f Add quick launch: a swipe past the first or last home page opens a chosen app
Swiping on from the first home screen page, towards the page that is not
there, now does what the owner chose under Settings, Gestures, Quick launch:
open an app, or any other of the launcher's gesture actions. The last page has
a choice of its own.

The stretch the pages already show at either end is an edge effect; quick
launch replaces it with one that also counts how far the finger has pulled.
Lifting the finger after a pull of about a seventh of the screen, or after a
flick, does the action; a short pull or one that is taken back does nothing.
An app opens out of the screen edge the finger pulled from.

From Android 12, where the stretch is Android's own. Infinite scrolling takes
those swipes for itself, so the two do not combine.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 14:36:03 +01:00
TMC b696a376b2 Release 0.8.1 2026-11-12 13:52:28 +01:00
TMCandClaude Fable 5.2 bfc2a0ea36 Ask for local network access when the update server is on the phone's own network
On Android 17 an app that targets it may not connect to devices on the local
network without the new ACCESS_LOCAL_NETWORK permission; a blocked connection is
dropped and ends as a timeout. At the owner's home the update server's name
leads to its address on the home network, so the check for updates failed there
with "did not answer" while the same server answered every other device.

The updater now recognises this case before it connects (Android 17, permission
not granted, server address inside one of the phone's own network ranges) and
says so at once. A tap on that message asks for the permission and runs the
check again; a refusal that Android no longer asks about leads to the app's
page in the phone's settings.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 13:52:16 +01:00
TMC fd1c8b195e Release 0.8.0 2026-11-12 13:04:44 +01:00
TMCandClaude Fable 5.2 5c4a6c346d Add the Pictures widget and carry Smart Launcher's photo widget over
Pictures is a widget that comes with the launcher: one picture, or several that
take turns every 10 seconds with a cross-fade (a tap shows the next at once).
Android knows it as an ordinary app widget, so it is added, moved, resized and
removed like any other, but the launcher draws it itself. That lets its frame
sit exactly on the outer edges of the icons of the cells it covers and take the
corners of the icon shape in use.

Pictures are chosen with Android's photo picker and copied, scaled down, into
the launcher's own storage, one folder per widget, so no gallery permission is
needed. The widget's edit button opens the picker again; removing the widget
deletes its copies.

Launcher3's widget host view shows the launcher's own view for this provider
and skips the views Android would send, and the cell container gives the widget
its cells without the usual inset.

The Smart Launcher import now turns that launcher's photo widget into a
Pictures widget in the same place. Its photo is taken from the backup and
handed to the widget when the owner taps it to set it up.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 13:04:34 +01:00
TMCandClaude Fable 5.2 d5a62cc6f5 Redraw every open copy of the launcher when a setting changes
Opening the launcher like an app (the installer's "Open") and then making it
the home app leaves two launcher activities in one process. A changed setting
recreated whichever one LawnchairApp.launcher returned, which could be the one
in the background, so the home screen kept its old look until a restart.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 13:04:33 +01:00
TMC 8cfa2fdc84 Release 0.7.0 2026-11-12 12:09:20 +01:00
TMCandClaude Fable 5.2 d0d1c031d0 Add a row size setting and give the screen edge back to Android's Back swipe
Row size (Settings, App drawer, Style): Compact is the list as it was, Comfy
has taller rows, larger icons and slightly larger names and letter headers.

In the open drawer the alphabet no longer reserves the screen edge. Its letters
rest 30dp from the edge, clear of the strip where Android starts Back. A touch
that starts on that strip becomes a scrub once it moves up or down or rests for
a moment; a sideways swipe is left to Android and goes back. The band that
starts a scrub from the home screen is narrower than the one in the drawer.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 12:09:11 +01:00
TMC 494364ffa2 Release 0.6.1 2026-11-12 10:43:09 +01:00
TMCandClaude Fable 5.2 80a56c01c9 Say why a check for updates failed
The owner's phone answered a manual check with "Couldn't reach the update server" while
the same published version found the update on the emulator and the server answered from
the PC. The message gave no way to tell a missing network permission from a VPN, a name
that does not resolve, or a server error.

- A failed check now carries what kind of failure it was (no network permission, server
  not found, no answer, no secure connection, server error, unreadable answer) and the
  error's own words. The About screen says the kind in plain words with what to try, and
  shows the words under it as "Details".
- The no-permission case is told apart before any request is made; some Android systems
  let the owner switch the network off per app.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 10:43:07 +01:00
TMC 043e1e0c4a Release 0.6.0 2026-11-12 10:13:49 +01:00
TMCandClaude Fable 5.2 d82d488189 Import home screens from a Smart Launcher backup; survive a grid reload with unset widgets
Asked for by the owner on 12 November 2026, with one of their own backups to work from.

Import (Settings > Backup and restore > Import from Smart Launcher)
- A .slbk file is a zip of Smart Launcher's files. The importer reads its database
  (HomeItem, Launchable, Action, Widget) and the grid from its preferences, and writes the
  home screens as a Launcher3 database that Launcher3's restore code takes in, the way
  Lawnchair's Nova import does. The format is not documented; this follows one real
  backup of data version 64 and refuses a file without those tables.
- One to one, by the owner's decision: every icon, folder and widget in the cell it had, on
  a grid of the same size, and the dock switched off because Smart Launcher has none.
  Home screen labels follow the backup.
- Widgets arrive as "tap to set up". Android has each launcher ask for its own widgets and
  keeps a widget's settings with the launcher that made it.
- Left out, and said so on the screen before the owner agrees: Smart Launcher's own widgets,
  items of other profiles, anything without a usable target or free cells. Icons of apps
  that are not installed are dropped by Launcher3 when it loads the layout.
- Settings are changed only after Launcher3 has accepted the layout, so a failed import
  changes nothing.
- Entry names in the zip are not trusted: only the database and the preference files are
  unpacked, each under a fixed name, with a size limit.

Fix in Launcher3 (WidgetSizeHandler)
- A widget waiting for "tap to set up" has an id Android has reserved but not bound.
  Android 17 answers a size update for such an id with a NullPointerException, which ended
  the launcher whenever the grid reloaded with such a widget on a home screen. Found
  because the import first changed a setting that reloads the grid while the previous
  layout still had unset widgets. The answer is now logged and dropped.

Checked on the Android 17 emulator: the owner's backup itself (two apps of it exist there
and land in their cells), a copy of its layout pointed at apps the emulator has (all 7
icons, 6 folders and 4 widgets in place, one widget set up through Android's dialog), and
two grid reloads with unset widgets on screen.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 10:13:41 +01:00
TMC 8894271daa Release 0.5.0 2026-11-12 09:25:56 +01:00
TMCandClaude Fable 5.2 3cb262617c Search field scrolls with the list; magnifier on the alphabet; a chosen letter's group goes to the middle
Three more requests from the owner on 12 November 2026.

Search field
- The field scrolls away with the list and comes back at the list's top, so the list has
  the whole height once it is scrolled. The field is not turned into a list row. The list
  now starts at the top of the drawer instead of under the field and keeps the field's room
  as top padding (ActivityAllAppsContainerView.replaceAppsRVContainer and
  AdapterHolder.applyPadding); FlexeraDrawer.moveSearchFieldWithList shifts the field by as
  much as the list has scrolled, measured from the first row, and cuts it at the same line
  the rows are cut at, the lower edge of the status bar.
- With work tabs, a hidden or a floating search field, and during a search, nothing changes.

Alphabet
- A magnifier above the letters stands for the search field. Scrubbing to it jumps the list
  to its top; the bubble shows the magnifier. The stretch of edge kept for the strip grows
  by one place for it.
- The strip measures its room from where the list's rows start, not from the list's top.

Chosen letter
- A scrub brings the letter's group to the middle of the screen, where the thumb is,
  instead of to the top: the group's middle on the list's middle, a long group's header no
  higher than 22% of the height. At either end of the list the list stops at its end, so
  the first groups stay at the top and the last ones rest at the bottom.

Checked on the Android 17 emulator: scrolling by hand, scrubs to a middle letter, the last
letter and the magnifier, typing a search and leaving it, reopening after a scrub, the hold
and edge gestures, and a row's long-press menu.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 09:25:48 +01:00
TMC 0959f36587 Release 0.4.0 2026-11-12 09:00:30 +01:00
TMCandClaude Fable 5.2 8aba905d9c Thumb-friendly drawer: compact list, Niagara-style alphabet, dark backdrop; QR code on About
Requests from the owner on 12 November 2026, after using 0.3.1 on the Pixel 9a, with a
photo of Niagara Launcher's alphabet as the reference.

Drawer list
- Rows are 50dp with 34dp icons and 15sp names (were 64dp, 46dp, 17sp); letter headers are
  34dp. A row grows with a large system font so a notification preview still fits.

Alphabet
- Letters sit 20dp apart at most (was 30dp). The strip keeps a stretch of edge as tall as
  26 letters, low on the edge with its end 40dp above the navigation bar, and centres the
  letters that exist in it. It used to spread over the whole edge, which put "A" out of a
  thumb's reach.
- The wave follows Niagara's: letters keep their size, the wave is wide (104dp) so about
  five letters on each side of the finger curve around the thumb, and the selected letter
  is shown large in a light bubble just beyond the wave's peak. This replaces the enlarged
  letter on a dark spot from 0.3.1, which collided with its neighbours at this spacing.
- The list dims a little during any scrub, more where the wave lies over it.

Backdrop
- The drawer's scrim is black at 78% in every theme (AllAppsState). Lawnchair's grey at 40%
  left a light grey behind white names over a light wallpaper. LawnchairScrimView judges the
  status bar icons by the scrim's own colour again, since that colour is now always dark.

Scrub from the home screen (PRD AD-10)
- On by default, the owner's decision; this closes the PRD's open question.
- It opens the drawer in 120 ms instead of the state manager's 600 ms, like swipe up and hold.
- A touch that lifts within 200 ms was a flick and opens the plain list.

Fix: undoing a scrub that was not meant
- 0.3.1 put the list back to "where it was", read from the list's rows. A closed drawer has
  been told to return to the top but lays its rows out only when it opens, so the rows
  still reported the place the drawer was last left at, and a quick swipe reopened it
  there. The list now goes where a plainly opened drawer stands.

About
- A QR code for the release page, generated on the phone with ZXing core (new dependency),
  black on white in every theme, with the address under it.

Checked on the Android 17 emulator with timed touches, a thumb-sized shape over the
screenshots, a 1.6 font scale, and by decoding the QR code from a screenshot.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 09:00:22 +01:00
TMCandClaude Fable 5.2 60d00afcfd release.ps1: keep Gradle's warnings from stopping a piped run
Gradle prints compiler warnings on its error stream. When the script's output was piped or
sent to a file, PowerShell 5.1 took the first such line for an error and stopped the build
at step 2 (seen on the first 0.3.1 attempt). The streams are now merged inside cmd, and
only the exit code decides whether the build failed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 08:07:30 +01:00
TMC 74becdd355 Release 0.3.1 2026-11-12 08:02:33 +01:00
TMCandClaude Fable 5.2 4771d2928a Start the alphabet scrub the moment a hold is noticed; keep the selected letter clear of the thumb
Two reports from first use on the Pixel 9a (PRD AD-5, AD-6, AD-17).

Swipe up and hold was slow to hand over to the alphabet:
- After the hold was noticed, the drawer was sent to its open state through the state
  manager, which takes 600 ms, and the alphabet took the finger only after that, and then
  only on the next touch movement. A finger held perfectly still never started it.
- Now the alphabet takes the finger's position in the same call that notices the hold, and
  the drawer finishes opening under it by playing the swipe's own animation to its end in
  120 ms.
- A still finger counts as holding after 150 ms instead of 300 (MotionPauseDetector gains
  setForcePauseTimeout, reset by clear()), and the swipe has to travel 32dp instead of 72dp
  before a hold counts.
- Because the list now jumps at once, a finger that lifts within 200 ms of the hold being
  noticed is treated as an ordinary swipe that slowed down at its end: the scrub is undone
  and the list stays where it was.

The selected letter sat under the thumb:
- The wave's peak was 52dp beyond the finger, about 8 mm, and a thumb hides about 11 mm to
  each side of where it touches. It is now 104dp, and at least 96dp out from the edge.
- The peak may travel to within 36dp of the far edge (was 70% of the width), so the gap
  holds when the finger is in the middle of the screen.
- A taller wave is wider (a third of its reach), so the neighbouring letters bend around
  the thumb instead of vanishing under it.
- A soft dark spot behind the selected letter keeps it readable where it lands on an app
  name or a light wallpaper.

Checked on the Android 17 emulator with touches injected at millisecond timing (a monkey
script) and a thumb-sized shape drawn over the screenshots.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 08:02:20 +01:00
TMC 1f9116d666 Release 0.3.0 2026-11-12 00:05:16 +01:00
TMCandClaude Fable 5.2 4e48615b5a Show an app's latest notification under its name in the drawer list
PRD AD-11, the last buildable row of M4.

- FlexeraNotificationPreview keeps the text of the notifications that currently show a
  dot, fed by Launcher3's NotificationListener on its worker thread, and sets a second,
  smaller and dimmer line on a drawer row whenever the row's dot state is applied.
- It uses what the dots already use: the same notification access and the same filter
  for which notifications count. Without notification access nothing changes.
- PopupDataProvider now refreshes an app's icons on every posted notification, so a
  notification updated in place brings its new text to the row.
- Only rows of the drawer list take the second line (marked with a view tag); search
  result icons share the "all apps" display type but stay as they were.
- New setting under Settings > App drawer: Notification previews, on by default.

Checked on the Android 17 emulator (debug build): a test SMS showed under Messages,
a second one replaced it while the drawer was open, removing the notification put the
plain name back, and the setting switches the line off and on.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-12 00:05:08 +01:00
137 changed files with 17969 additions and 384 deletions

No files matched your search

+211
View File
@@ -0,0 +1,211 @@
# Flexera Launcher website
A one-page site for Flexera Launcher. Plain HTML, CSS and JavaScript: no build step and no
libraries. The one thing loaded from another server is the visit counter (see "Putting it online").
| File | What it is |
| --- | --- |
| `index.html` | The page and all its copy |
| `styles.css` | Layout, colours and the phone's look |
| `script.js` | The phone model, the scroll story, the playground and the timed test |
| `assets/` | App icon (WebP and PNG favicons), QR code, link-preview image (`og.jpg`) |
| `fonts/` | Inter and JetBrains Mono, the page's faces, and Outfit, the face inside the phones, each with its licence |
## Look at it
Open `index.html` in a browser. To see it as a server would serve it:
```sh
cd WEBSITE
python -m http.server 8080
```
and open <http://localhost:8080>.
## After a release
- Change `VERSION` at the top of `script.js`. The page fills every version number from it,
including the update check's user agent under "What goes online". `index.html` carries the
same number as a fallback for browsers without JavaScript (under Install); replace it there too.
- Elements with `data-since="x.y.z"` read "Coming in x.y.z" until `VERSION` reaches that
version and "New in x.y.z" after it. Full-screen folders carry `data-since="1.0.0"`.
- The download buttons and the QR code point at
`.../releases/download/latest/FlexeraLauncher.apk`, the fixed-name copy that every release
uploads, so they never need changing.
- If the headline or the look of the top of the page changes, remake `assets/og.jpg`, the
1200 x 630 card that chats and social sites show for a link: run
`node flexera/website/make-og.mjs` from the project root (Chrome and Node 22 or newer, nothing
to install). It reads the headline from `index.html` and draws the icon and name, the headline,
one line under it and two phones (the home screen's edge and the list scrubbed to F) with the
site's own script and styles.
- If the app's numbers in the table below change, change the model to match.
## Putting it online
- Upload what is in `PRODUCTION/`, and nothing else from this folder. It is a copy made by
`node flexera/website/make-production.mjs` (run from the project root): the page, its
stylesheet and script, and only the pictures and fonts those three load, each font with its
licence. The script empties and refills the folder, so run it again after any change to the
website, and never edit the copy.
- With Docker: `docker compose up -d` in this folder serves `PRODUCTION/` with nginx at
<http://localhost:8080> (`docker-compose.yml`, `nginx.conf`; `FLEXERA_PORT=9000` picks another
port). On a server, put those two files and `PRODUCTION/` in one directory. It answers plain
HTTP: HTTPS belongs to the proxy in front of it. The page, stylesheet and script are sent with
`no-cache`, so a new version shows at once; pictures and the font are kept for a week.
- The site lives at <https://flexera.mariosem.es/>. Link previews need full addresses, so the
head of `index.html` names that address three times: `og:image` (the full address of
`assets/og.jpg`), `og:url` and `<link rel="canonical">`. If the site moves, change all three; a
relative `og:image` shows no picture in most chats.
- The head also carries the page's title and description, the card's size and description, and a
short `SoftwareApplication` record for search engines; none of them holds the version number.
- Visits are counted by Plausible, on the owner's own server: the last two `<script>` tags in the
head of `index.html`, pasted as Plausible gives them. It sets no cookies, and it does not count
the page opened from a file or from `localhost`. If a `Content-Security-Policy` header is ever
added, it must allow `https://plausible.mariosem.es` for scripts and for connections.
## The look
The page is dark throughout, after a style reference the owner chose (inspiration only): one
near-black canvas, `#040506`, with surfaces barely above it (`#07080a` for cards, `#111214` for
wells and keys, `#1b1c1e` for badges), 1 px hairlines in `#363739`, and depth from inset
highlights rather than drop shadows. The main actions (Download, Start) are light grey buttons,
`#e6e6e6` with `#454647` text, lifted by a soft shadow; none is coloured. The playground's buttons
are dark keys with the 'key' shadow, a faint ring and an inner top highlight, which the install
steps' numbers borrow; a setting that is on there, the chosen row size or the left-edge switch,
turns light grey. Text is Inter: headings in white at regular weight (medium for the small ones)
and never tracked tighter, body `#dcdcdd` and secondary `#9c9c9d`. JetBrains Mono sets what is
technical: control labels, table heads, version numbers, user agents, the timed test's times, the
labels of the phones' measurements and the strip at the foot.
Colour comes from the app icon and is rationed. The top of the page is the one place it is spent:
a deep indigo wash, and behind the big phone the icon's sweep as soft diagonal bands (cyan
`#19dff8` and sky `#0899f4`, royal `#0a4cc5` and indigo `#2815b7`, violet `#5e19da` and purple
`#a420f5`, magenta `#dc29f8`). On a phone's screen the sweep hangs from the big phone's top
instead (`.fig::before`), so that it starts just under the download wherever the text above ends.
Below it, magenta marks only the 'New in' badge, on its own dark tint `#240c2a`, and cyan only the
phones' measurements and the leader to the top figure's note.
Sections sit in a 1200 px column with a hairline between them. Past the last page is the
exception: the one band of true black, `#000`, edge to edge between full-width hairlines, the
page quick launch brings in. The bar at the top floats, frosted, from 700 px up; on a phone it
scrolls away, because the story's phone holds the top of the screen there.
## The phone
The phone is drawn in HTML at 390 x 844, one pixel per dp, and scaled to fit, six times over:
three stills in the top figure (`edgeState()`, the home screen with a thumb on the band along its
edge, `heroState()`, the list scrubbed to F, and `quickState()`, quick launch just past its
line), the one the scroll position drives through six chapters
(`storyState()`), the playground (`setupPlay()`), and the list phone of the timed test (the
playground's controller, locked to the app list). All of them render the state described in
`blank()`. The 40 apps on it are made-up stand-ins. The page shows it as a product shot: a light
ring around the frame and a soft shadow.
Its wallpaper is a plain abstract one in muted shades of the icon's indigo (flat shapes, so the
blur has edges to soften), and its icons are drawn the way Android 13 and Lawnchair theme them,
tinted from the wallpaper, with a few apps left in their own colours (`THEMED` and `ODD` in
`script.js`). The picture frame's photos are the sea, mountains and lemons on a checked cloth;
the camera that quick launch opens looks at a desk.
Its numbers are the app's:
| What | Value | From |
| --- | --- | --- |
| Rows, compact and comfy | 50 and 58 dp; icons 34 and 40; gaps 16 and 18; names 15 and 16 sp | `flexera/res/values/flexera_dimens.xml` |
| Letter headers | 34 and 38 dp, 12 and 13 sp, white at 80% | same, `flexera_colors.xml` |
| Row padding | 24 dp, 56 dp on the alphabet's side | `flexera_dimens.xml` |
| Notification line | 78% of the name's size, white at 70% | `FlexeraNotificationPreview.kt` |
| Backdrop | black at 78% over the blurred wallpaper; the list fully visible at 60% of its opening | `FlexeraDrawer.kt` |
| Letters | 12 sp, 20 dp apart, 30 dp from the edge, white at 70%; the strip is sized for 26 letters and ends 40 + 16 dp above the navigation bar | `flexera_dimens.xml`, `WaveAlphabetView.computeLayout` |
| Wave | peak 104 dp beyond the finger, at least 96; spread max(104, 0.36 x reach); chosen letter bold and 25% larger; press 110 ms in, 220 ms out | `WaveAlphabetView.onDraw` |
| Bubble | 40 dp disc `#f1f1f4`, 22 sp letter `#17181c`, 38 dp beyond the peak | same |
| Scrub dim | black, 55% x how far the wave lies over the list (35% of that at the right edge) | same |
| Landing | the group's middle on the list's middle, its header no higher than 22% | `WaveAlphabetView.scrollListTo` |
| Bands | 60 dp in the open list, 40 dp on the home screen; Android's Back strip about 24 dp | `flexera_dimens.xml` |
| Scrub from home, swipe up and hold | the list opens in 120 ms; under 200 ms is a flick; a hold is 150 ms still after 32 dp | `FlexeraEdgeScrubController.kt`, `FlexeraDrawer.kt`, `NoButtonNavbarToOverviewTouchController.java` |
| Quick launch | opens past 40% or on a flick; the home screen dimmed 35% and blurred by 1 - (1 - p)^2; settles in 150 to 300 ms; the app appears with no animation | `QuickLaunchPage.kt`, `QuickLaunch.kt` |
| Full-screen folders (1.0.0) | the home screen's columns and cells, 16 dp above the navigation bar, the list's backdrop | `FullScreenFolders.kt` |
| Clock sizes | small and large figures 0.625 and 1.25 times medium (0.5, 0.8 and 1.25 icon heights) | `ClockWidgetView.kt` |
| Picture widget | next picture every 10 s, 600 ms fade | `PictureWidgetView.kt` |
The blur is never animated: the phone fades between sharp and pre-blurred copies of the wallpaper
and the home screen.
Other moving parts, all in `script.js`:
- **Measurement marks** (`Phone.drawMarks()`): dimension lines and labels drawn in cyan
`#19dff8`, the labels in JetBrains Mono, on the phone's screen in an SVG layer, in the story
chapters whose text gives the number.
- **The top figure** (`setupHero()`, `.fig` in `styles.css`): a lineup of three stills straight
on the page, standing on one line, each with a one-sentence caption under it. The list is in
front and larger, with the icon's sweep on its rim (`.fig__phone::before` and `::after`); the
home screen's edge and quick launch stand either side of it, smaller and dimmed. Under 700 px
the list has a row to itself and the other two share the row below. The two side captions are
the same length on purpose, so they always break into the same number of lines.
- **The two settings** (`setupLook()`): the alphabet's side and the row size, applied to every
phone on the page.
- **A keyboard slider** over the playground's alphabet, like the single slider the app gives
TalkBack: Tab to it, then the arrow keys, Home and End.
- **Tap to try** (`opts.armable` in `setupPlay()`): on a touch screen the playground phone lets
the page scroll over it until it is tapped, and lets go again once it is off the screen. The
timed test's list phone takes the touch only during round two.
- **The timed test** (`setupRace()`): find an app in a grid drawer of the 40 apps, sorted A to Z
as Lawnchair's is, then in the list. Escape stops a round. Start brings the phone into view with
the app's name clear of the bar.
- **Motion** (the Motion block in `styles.css`; `setupHero().play`, `setupReveal()`,
`setupGlint()` and the scroll handler in `boot()`):
- The entrance, once, when the fonts are in: the headline word by word (a small script after
the `h1` wraps the words, so the headline stays plain text in the HTML), the copy and the
button, then the three phones. On the same clock the stills play their own part: the thumb
comes down on F, the wave goes out and the list goes to F; the edge band and the swipe follow.
- Sections rise into place the first time they are scrolled to (`REVEAL` lists them); the
headings among them also come out of a blur. Things that arrive together follow one another
80 ms apart, and anything jumped over is simply there.
- With the scroll position: the bar is clear at the top and turns to glass once the page moves
under it; the light on the front phone's rim travels round as the hero scrolls by; in the
story, the chapter the phone is playing is lit and the others are dimmed.
- With the pointer: a light on the rim of the two cards (the timed test and Install) follows
the mouse, and buttons lift a pixel. Where the browser can, the answers under "Before you
install" open and close at their own height.
- **The egg** (`setupNom()`): point at or tap NOMNOM Inc. in the footer and a small creature, one
of the launcher's icons with a jaw, comes in from the right and eats the name.
On its own the page moves once, for the entrance; after that only a picture widget's photo
changes, every 10 seconds, and everything else answers a scroll, a pointer or a tap. Visitors who
ask their system for reduced motion get none of it: the page is at rest from the start, and the
story shows one still frame per chapter. Visitors who ask for reduced transparency get a
solid bar and solid cards. Without JavaScript the page shows its text and the download, and
leaves out the drawings, the playground and the coloured sweep they stand on. Printed, it is dark
text on white, without the drawings, the playground or the bar.
## Checking it
Headless Chrome takes screenshots without anything else installed:
```sh
"C:\Program Files\Google\Chrome\Application\chrome.exe" --headless=new --disable-gpu --hide-scrollbars --user-data-dir=<an empty folder> --virtual-time-budget=6000 --window-size=1440,900 --screenshot=<a .png path> file:///<path to>/WEBSITE/index.html
```
The command returns before the file is written; wait for the PNG. CSS animations do not advance
under `--virtual-time-budget`, so a screenshot taken this way catches the entrance on its first
frame, an almost empty page: add `--force-prefers-reduced-motion` to see the page at rest, and to
see the motion itself drive Chrome over its DevTools port in real time (`Page.captureScreenshot`
at set moments after loading or scrolling). Each story chapter has an id
(`#one-column`, `#slide`, `#lands`, `#from-home`, `#no-page`, `#no-animation`): open the page at
that fragment to see the chapter's phone. Chrome won't lay a page out narrower than about 500 px
from the command line, so for a phone's width either screenshot a scratch page outside this
folder that holds a 390 px wide iframe of `index.html`, or drive Chrome over its DevTools port
with `Emulation.setDeviceMetricsOverride`. Add `--force-prefers-reduced-motion` to see the still
frames. For the page without JavaScript, printed, or with reduced motion, transparency, more
contrast or forced colours, drive Chrome over its DevTools port with
`Emulation.setScriptExecutionDisabled` and `Emulation.setEmulatedMedia`.
## Fonts
Three faces, served from `fonts/`, all under the SIL Open Font License 1.1: Inter 4.001
(`inter.woff2`, variable weight, Latin; `inter-OFL.txt`) for the page; JetBrains Mono 2.211
(`jetbrains-mono.woff2`, weights 400 to 800, Latin; `jetbrains-mono-OFL.txt`) for technical
labels; Outfit (`outfit.woff2`, `outfit-OFL.txt`, downloaded from Google Fonts) only inside the
phones. The Inter file has no `liga` or `ss03`, so none are set. No font is preloaded: a font
preload needs CORS, which fails when the page is opened as a file.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="41" height="41" class="segno"><path class="qrline" stroke="currentColor" d="M0 0.5h7m2 0h2m1 0h1m2 0h2m2 0h3m1 0h1m4 0h1m2 0h2m1 0h7m-41 1h1m5 0h1m2 0h1m1 0h3m2 0h1m1 0h1m1 0h2m3 0h1m1 0h1m2 0h1m1 0h1m1 0h1m5 0h1m-41 1h1m1 0h3m1 0h1m1 0h1m1 0h1m1 0h3m6 0h3m2 0h3m5 0h1m1 0h3m1 0h1m-41 1h1m1 0h3m1 0h1m1 0h3m2 0h1m4 0h1m3 0h6m6 0h1m1 0h3m1 0h1m-41 1h1m1 0h3m1 0h1m1 0h1m3 0h1m1 0h4m1 0h5m4 0h1m1 0h3m1 0h1m1 0h3m1 0h1m-41 1h1m5 0h1m1 0h1m1 0h4m2 0h2m2 0h3m1 0h1m2 0h1m1 0h1m4 0h1m5 0h1m-41 1h7m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h7m-33 1h1m1 0h2m3 0h1m4 0h3m1 0h1m1 0h3m-29 1h1m1 0h5m2 0h1m3 0h1m2 0h2m4 0h5m2 0h1m1 0h1m2 0h5m-38 1h1m1 0h1m4 0h1m1 0h1m1 0h1m1 0h1m1 0h4m1 0h1m1 0h1m2 0h1m1 0h1m1 0h7m1 0h3m-40 1h1m1 0h2m1 0h2m1 0h1m3 0h2m5 0h3m4 0h2m3 0h1m6 0h1m-39 1h3m4 0h1m2 0h1m3 0h2m1 0h2m1 0h4m1 0h3m2 0h2m3 0h2m1 0h1m-39 1h2m2 0h4m2 0h1m2 0h1m1 0h2m4 0h1m1 0h3m2 0h1m1 0h1m4 0h3m-38 1h1m1 0h1m1 0h1m1 0h10m1 0h1m1 0h4m1 0h2m1 0h1m2 0h2m1 0h7m-40 1h1m1 0h1m2 0h1m4 0h4m4 0h1m1 0h1m2 0h4m1 0h2m2 0h1m1 0h1m1 0h1m-37 1h1m5 0h3m2 0h1m1 0h1m3 0h6m2 0h1m1 0h1m2 0h1m2 0h2m1 0h1m2 0h1m-40 1h1m3 0h3m1 0h1m1 0h3m1 0h3m1 0h1m2 0h5m2 0h1m3 0h1m1 0h1m2 0h2m-40 1h4m1 0h1m2 0h1m4 0h3m1 0h5m1 0h1m1 0h2m1 0h5m1 0h4m1 0h2m-41 1h3m2 0h2m2 0h1m3 0h1m3 0h1m3 0h1m2 0h1m2 0h2m3 0h1m3 0h2m-37 1h1m1 0h1m4 0h1m1 0h3m2 0h4m1 0h2m6 0h1m1 0h1m1 0h3m1 0h2m-34 1h4m1 0h1m1 0h1m3 0h2m2 0h1m2 0h5m2 0h1m2 0h1m4 0h2m-39 1h1m1 0h1m5 0h1m5 0h7m2 0h1m3 0h14m-38 1h5m1 0h2m3 0h1m6 0h2m2 0h1m1 0h2m1 0h1m1 0h1m3 0h3m-37 1h2m1 0h1m7 0h1m1 0h2m2 0h1m1 0h4m2 0h2m3 0h1m2 0h1m1 0h1m-36 1h1m2 0h4m8 0h1m2 0h1m4 0h2m2 0h1m5 0h1m-35 1h1m2 0h2m2 0h1m2 0h2m2 0h1m3 0h3m1 0h1m4 0h1m2 0h1m1 0h5m2 0h1m-39 1h1m2 0h2m1 0h1m1 0h1m3 0h1m1 0h1m3 0h1m5 0h2m1 0h2m1 0h4m-36 1h2m1 0h1m1 0h1m1 0h2m2 0h1m1 0h4m3 0h2m1 0h1m2 0h1m1 0h1m1 0h4m1 0h1m1 0h1m2 0h1m-40 1h1m3 0h3m5 0h2m2 0h1m5 0h4m2 0h1m1 0h2m4 0h3m-40 1h1m3 0h2m4 0h4m4 0h1m2 0h1m1 0h2m3 0h1m1 0h5m1 0h2m2 0h1m-41 1h1m1 0h1m1 0h1m1 0h1m7 0h1m1 0h1m4 0h2m1 0h5m3 0h4m1 0h1m-38 1h1m3 0h2m4 0h2m2 0h2m5 0h1m1 0h2m1 0h3m3 0h3m1 0h2m-38 1h1m1 0h2m2 0h5m6 0h1m6 0h4m1 0h1m2 0h8m-32 1h2m3 0h2m4 0h2m2 0h1m8 0h1m3 0h1m2 0h2m-41 1h7m3 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m3 0h1m1 0h3m1 0h3m1 0h1m1 0h3m-39 1h1m5 0h1m1 0h1m1 0h2m1 0h1m1 0h2m2 0h5m2 0h1m4 0h2m3 0h1m3 0h1m-41 1h1m1 0h3m1 0h1m1 0h3m1 0h1m3 0h1m1 0h4m1 0h5m1 0h1m2 0h5m1 0h2m-40 1h1m1 0h3m1 0h1m1 0h2m1 0h2m1 0h1m2 0h1m2 0h1m2 0h1m1 0h2m6 0h1m1 0h1m1 0h1m1 0h2m-41 1h1m1 0h3m1 0h1m1 0h1m1 0h1m3 0h5m1 0h1m1 0h1m1 0h1m2 0h2m2 0h6m1 0h1m-39 1h1m5 0h1m2 0h3m2 0h3m1 0h1m1 0h2m1 0h1m2 0h2m2 0h1m1 0h1m1 0h1m1 0h2m1 0h1m-40 1h7m1 0h1m1 0h1m2 0h2m2 0h1m1 0h1m2 0h6m1 0h3m1 0h1m1 0h2m1 0h1"/></svg>

After

Width:  |  Height:  |  Size: 2.7 KiB

+18
View File
@@ -0,0 +1,18 @@
# Serves the website with nginx: the PRODUCTION folder beside this file, read-only.
#
# docker compose up -d start it, then open http://localhost:8080
# docker compose down stop it
#
# Another port: FLEXERA_PORT=9000 docker compose up -d (or change 8080 below)
# On a server, copy this file, nginx.conf and the PRODUCTION folder into one directory.
# After the site changes, replace PRODUCTION; nginx serves the new files at once, no restart.
services:
web:
image: nginx:stable-alpine
container_name: flexera-website
restart: unless-stopped
ports:
- "${FLEXERA_PORT:-8080}:80"
volumes:
- ./PRODUCTION:/usr/share/nginx/html:ro
- ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
+93
View File
@@ -0,0 +1,93 @@
Copyright 2020 The Inter Project Authors (https://github.com/rsms/inter)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
+93
View File
@@ -0,0 +1,93 @@
Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at: https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
+93
View File
@@ -0,0 +1,93 @@
Copyright 2021 The Outfit Project Authors (https://github.com/Outfitio/Outfit-Fonts)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
+352
View File
@@ -0,0 +1,352 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Flexera Launcher: an Android app list built for your thumb</title>
<meta name="description" content="Flexera is a free Android launcher. Every app sits in one list, A to Z, with the alphabet on the edge of the screen, where your thumb already is.">
<meta name="color-scheme" content="dark">
<meta name="theme-color" content="#0d0d0f">
<!-- Link previews. og:image, og:url and the canonical link must be full addresses: when the site's
address changes, change it in these three places. The card itself is made by flexera/website/make-og.mjs. -->
<link rel="canonical" href="https://flexera.mariosem.es/">
<meta property="og:url" content="https://flexera.mariosem.es/">
<meta property="og:type" content="website">
<meta property="og:site_name" content="Flexera Launcher">
<meta property="og:locale" content="en_GB">
<meta property="og:title" content="Flexera Launcher: an app list for the thumb that’s holding the phone">
<meta property="og:description" content="A free Android launcher. Slide your thumb along the alphabet on the edge of the screen to reach any app, or swipe past your last home screen page to open one you picked.">
<meta property="og:image" content="https://flexera.mariosem.es/assets/og.jpg">
<meta property="og:image:type" content="image/jpeg">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="The headline “An app list for the thumb that’s holding the phone” beside two drawings of Flexera Launcher: a home screen, and the app list with its alphabet curving out around a thumb on the right edge.">
<meta name="twitter:card" content="summary_large_image">
<script type="application/ld+json">{"@context":"https://schema.org","@type":"SoftwareApplication","name":"Flexera Launcher","applicationCategory":"UtilitiesApplication","operatingSystem":"Android 8.0 or newer","description":"A free Android launcher. Every app sits in one list, A to Z, with the alphabet on the edge of the screen, where your thumb already is.","offers":{"@type":"Offer","price":"0","priceCurrency":"USD"},"downloadUrl":"https://git.mariosem.es/msemes/Flexera-Launcher-Releases/releases/download/latest/FlexeraLauncher.apk","author":{"@type":"Organization","name":"NOMNOM Inc."}}</script>
<link rel="icon" type="image/png" sizes="64x64" href="assets/favicon-64.png">
<link rel="icon" type="image/png" sizes="32x32" href="assets/favicon-32.png">
<link rel="apple-touch-icon" href="assets/icon-180.png">
<link rel="preload" href="fonts/outfit.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="assets/flexera-icon-256.webp" as="image">
<link rel="stylesheet" href="styles.css">
<script>/* Hold the first paint until Outfit is in (or 700 ms pass), so nothing shows in a fallback face and then jumps. */
(function () { var d = document.documentElement; d.classList.add('js', 'is-loading');
var done = function () { d.classList.remove('is-loading'); }; setTimeout(done, 700);
if (document.fonts && document.fonts.load) Promise.all([document.fonts.load('400 18px Outfit'), document.fonts.load('500 80px Outfit')]).then(done, done); else done(); })();</script>
<script src="script.js" defer></script>
<!-- Privacy-friendly analytics by Plausible -->
<script async src="https://plausible.mariosem.es/js/pa-8UuCpf8b9d-Q3Fk8yf6yK.js"></script>
<script>
window.plausible=window.plausible||function(){(plausible.q=plausible.q||[]).push(arguments)},plausible.init=plausible.init||function(i){plausible.o=i||{}};
plausible.init()
</script>
</head>
<body id="top">
<!-- Line icons used by the phone drawings. 24 x 24, drawn with strokes. -->
<svg class="sprite" aria-hidden="true" focusable="false">
<symbol id="g-camera" viewBox="0 0 24 24"><path d="M4 8h3l2-3h6l2 3h3v11H4z"/><circle cx="12" cy="13" r="3.5"/></symbol>
<symbol id="g-phone" viewBox="0 0 24 24"><path d="M6.6 3.5l3 3.6-1.8 2.3a12 12 0 0 0 6.8 6.8l2.3-1.8 3.6 3-1.6 2.4c-.5.7-1.4 1-2.2.8C10.3 18.8 5.2 13.7 3.4 7.3c-.2-.8.1-1.7.8-2.2z"/></symbol>
<symbol id="g-msg" viewBox="0 0 24 24"><path d="M4 5h16v11H9.5L4 20z"/></symbol>
<symbol id="g-mail" viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3.5 6.5L12 13l8.5-6.5"/></symbol>
<symbol id="g-map" viewBox="0 0 24 24"><path d="M12 21s-6.5-6.2-6.5-11.2a6.5 6.5 0 0 1 13 0C18.5 14.8 12 21 12 21z"/><circle cx="12" cy="9.8" r="2.3"/></symbol>
<symbol id="g-music" viewBox="0 0 24 24"><path d="M9 18V5l11-2v13"/><circle cx="6.5" cy="18" r="2.5"/><circle cx="17.5" cy="16" r="2.5"/></symbol>
<symbol id="g-cal" viewBox="0 0 24 24"><rect x="4" y="5" width="16" height="15" rx="2"/><path d="M4 10h16M8 3v4M16 3v4"/></symbol>
<symbol id="g-clock" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M12 7.5V12l3 2"/></symbol>
<symbol id="g-notes" viewBox="0 0 24 24"><path d="M6 3h9l4 4v14H6z"/><path d="M9 11h7M9 15h7M9 7h3"/></symbol>
<symbol id="g-files" viewBox="0 0 24 24"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></symbol>
<symbol id="g-globe" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M3.5 12h17M12 3.5c2.5 2.6 3.5 5.5 3.5 8.5s-1 5.9-3.5 8.5c-2.5-2.6-3.5-5.5-3.5-8.5s1-5.9 3.5-8.5z"/></symbol>
<symbol id="g-sun" viewBox="0 0 24 24"><circle cx="12" cy="12" r="4"/><path d="M12 2.5V5M12 19v2.5M2.5 12H5M19 12h2.5M5.3 5.3l1.8 1.8M16.9 16.9l1.8 1.8M5.3 18.7l1.8-1.8M16.9 7.1l1.8-1.8"/></symbol>
<symbol id="g-wallet" viewBox="0 0 24 24"><rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18M15.5 14.5h2"/></symbol>
<symbol id="g-sliders" viewBox="0 0 24 24"><path d="M4 7h10M18 7h2M4 17h4M12 17h8"/><circle cx="16" cy="7" r="2"/><circle cx="10" cy="17" r="2"/></symbol>
<symbol id="g-mic" viewBox="0 0 24 24"><rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21"/></symbol>
<symbol id="g-pulse" viewBox="0 0 24 24"><path d="M3 12h4l2-4.5 3.5 9 2.5-4.5h6"/></symbol>
<symbol id="g-translate" viewBox="0 0 24 24"><path d="M4 5h9M8.5 3v2M6 5c.6 3 2.5 5.6 5 7M11 5c-.6 3.2-3 6-6.5 7.5"/><path d="M13 21l4-9 4 9M14.5 17.5h5"/></symbol>
<symbol id="g-calc" viewBox="0 0 24 24"><rect x="5" y="3" width="14" height="18" rx="2"/><path d="M8.5 7.5h7M8.5 12h.01M12 12h.01M15.5 12h.01M8.5 16.5h.01M12 16.5h.01M15.5 16.5h.01"/></symbol>
<symbol id="g-wave" viewBox="0 0 24 24"><path d="M4 10v4M8 7v10M12 4v16M16 8v8M20 11v2"/></symbol>
<symbol id="g-book" viewBox="0 0 24 24"><path d="M5 4h11a3 3 0 0 1 3 3v13H8a3 3 0 0 1-3-3z"/><path d="M5 17a3 3 0 0 1 3-3h11"/></symbol>
<symbol id="g-news" viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M7 9h6M7 13h10M7 16h7"/></symbol>
<symbol id="g-play" viewBox="0 0 24 24"><rect x="3" y="5" width="18" height="14" rx="3"/><path d="M10 9v6l5-3z"/></symbol>
<symbol id="g-bag" viewBox="0 0 24 24"><path d="M5 8h14l-1 12H6z"/><path d="M9 8a3 3 0 0 1 6 0"/></symbol>
<symbol id="g-bank" viewBox="0 0 24 24"><path d="M3 9l9-5 9 5M5 10v7M9.5 10v7M14.5 10v7M19 10v7M3 20h18"/></symbol>
<symbol id="g-shield" viewBox="0 0 24 24"><path d="M12 3l7 3v5c0 5-3 8.5-7 10-4-1.5-7-5-7-10V6z"/><path d="M9 12l2 2 4-4"/></symbol>
<symbol id="g-person" viewBox="0 0 24 24"><circle cx="12" cy="8.5" r="3.5"/><path d="M5 20c.8-3.8 3.6-6 7-6s6.2 2.2 7 6"/></symbol>
<symbol id="g-image" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 16l5-5 4 4 3-3 6 6"/><circle cx="15.5" cy="8.5" r="1.5"/></symbol>
<symbol id="g-plane" viewBox="0 0 24 24"><path d="M2.5 13.5l19-8-6.5 15-3-6.5z"/></symbol>
<symbol id="g-moon" viewBox="0 0 24 24"><path d="M19 14.5A7.5 7.5 0 1 1 9.5 5a6 6 0 0 0 9.5 9.5z"/></symbol>
<symbol id="g-search" viewBox="0 0 24 24"><circle cx="11" cy="11" r="6.5"/><path d="M16 16l4.5 4.5"/></symbol>
<symbol id="g-info" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M12 11v5.5M12 7.6v.01"/></symbol>
<symbol id="g-widgets" viewBox="0 0 24 24"><rect x="4" y="4" width="7" height="7" rx="1.5"/><rect x="13" y="13" width="7" height="7" rx="1.5"/><rect x="4" y="13" width="7" height="7" rx="1.5"/><path d="M16.5 3.5L20 7l-3.5 3.5L13 7z"/></symbol>
<symbol id="g-edit" viewBox="0 0 24 24"><path d="M4 20h4L19 9l-4-4L4 16z"/></symbol>
<symbol id="g-eyeoff" viewBox="0 0 24 24"><path d="M9.9 5.2C10.6 5.07 11.3 5 12 5c4.2 0 7.7 2.6 9.5 7-.6 1.4-1.4 2.6-2.4 3.6M16.4 17.6C15.1 18.5 13.6 19 12 19c-4.2 0-7.7-2.6-9.5-7 .8-2 2-3.6 3.5-4.8"/><path d="M14.1 14.1A3 3 0 0 1 9.9 9.9"/><path d="M4 4l16 16"/></symbol>
<symbol id="g-flip" viewBox="0 0 24 24"><path d="M4 12a8 8 0 0 1 14-5.3M20 12a8 8 0 0 1-14 5.3"/><path d="M18 3v4h-4M6 21v-4h4"/></symbol>
<symbol id="g-alarm" viewBox="0 0 24 24"><circle cx="12" cy="13" r="7"/><path d="M12 10v3.2l2.2 1.6M5 4L2.8 6.2M19 4l2.2 2.2"/></symbol>
<symbol id="g-compass" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M15.5 8.5l-2 5-5 2 2-5z"/></symbol>
<symbol id="g-game" viewBox="0 0 24 24"><rect x="2.5" y="7" width="19" height="10" rx="5"/><path d="M7 10.5v3M5.5 12h3M15.5 11h.01M17.5 13h.01"/></symbol>
<symbol id="g-heart" viewBox="0 0 24 24"><path d="M12 20s-7.5-4.6-7.5-10A4.3 4.3 0 0 1 12 7.4 4.3 4.3 0 0 1 19.5 10c0 5.4-7.5 10-7.5 10z"/></symbol>
<symbol id="g-ruler" viewBox="0 0 24 24"><path d="M3 16.5L16.5 3 21 7.5 7.5 21z"/><path d="M7 12.5l1.5 1.5M10 9.5l1.5 1.5M13 6.5l1.5 1.5"/></symbol>
<symbol id="g-radio" viewBox="0 0 24 24"><rect x="3" y="8" width="18" height="12" rx="2"/><circle cx="15.5" cy="14" r="2.5"/><path d="M7 12h3M7 15h3M6 8l11-4"/></symbol>
<symbol id="g-chart" viewBox="0 0 24 24"><path d="M3 17l5-5 4 3 8-8"/><path d="M15 7h5v5"/></symbol>
<symbol id="g-check" viewBox="0 0 24 24"><rect x="4" y="4" width="16" height="16" rx="4"/><path d="M8 12.5l2.5 2.5L16 9.5"/></symbol>
<symbol id="g-lock" viewBox="0 0 24 24"><rect x="5" y="10" width="14" height="10" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/></symbol>
</svg>
<!-- Android's mark, from simple-icons (CC0), for the download buttons. -->
<svg class="sprite" aria-hidden="true" focusable="false">
<symbol id="b-android" viewBox="0 0 24 24"><path d="M18.4395 5.5586c-.675 1.1664-1.352 2.3318-2.0274 3.498-.0366-.0155-.0742-.0286-.1113-.043-1.8249-.6957-3.484-.8-4.42-.787-1.8551.0185-3.3544.4643-4.2597.8203-.084-.1494-1.7526-3.021-2.0215-3.4864a1.1451 1.1451 0 0 0-.1406-.1914c-.3312-.364-.9054-.4859-1.379-.203-.475.282-.7136.9361-.3886 1.5019 1.9466 3.3696-.0966-.2158 1.9473 3.3593.0172.031-.4946.2642-1.3926 1.0177C2.8987 12.176.452 14.772 0 18.9902h24c-.119-1.1108-.3686-2.099-.7461-3.0683-.7438-1.9118-1.8435-3.2928-2.7402-4.1836a12.1048 12.1048 0 0 0-2.1309-1.6875c.6594-1.122 1.312-2.2559 1.9649-3.3848.2077-.3615.1886-.7956-.0079-1.1191a1.1001 1.1001 0 0 0-.8515-.5332c-.5225-.0536-.9392.3128-1.0488.5449zm-.0391 8.461c.3944.5926.324 1.3306-.1563 1.6503-.4799.3197-1.188.0985-1.582-.4941-.3944-.5927-.324-1.3307.1563-1.6504.4727-.315 1.1812-.1086 1.582.4941zM7.207 13.5273c.4803.3197.5506 1.0577.1563 1.6504-.394.5926-1.1038.8138-1.584.4941-.48-.3197-.5503-1.0577-.1563-1.6504.4008-.6021 1.1087-.8106 1.584-.4941z"/></symbol>
</svg>
<a class="skip" href="#main">Skip to content</a>
<header class="head">
<div class="wrap top">
<a class="top__brand" href="#top" aria-label="Flexera Launcher, back to the top"><img src="assets/flexera-icon-256.webp" alt="" width="28" height="28"><span>Flexera Launcher</span></a>
<nav class="top__links" aria-label="Site">
<a class="ghost top__hide" href="#alphabet">How it works</a>
<a class="ghost top__hide" href="#install">Install</a>
<a class="btn btn--sm" href="https://git.mariosem.es/msemes/Flexera-Launcher-Releases/releases/download/latest/FlexeraLauncher.apk" data-apk>Download</a>
</nav>
</div>
</header>
<main id="main">
<section class="wrap hero" aria-labelledby="hero-title">
<div class="hero__text">
<h1 id="hero-title">An app list for the thumb that’s holding the phone</h1>
<script>/* The headline comes in word by word: each word is wrapped here, in order, for the stylesheet to stagger. Edit the headline above as plain text. */
(function (h) { var words = h.textContent.trim().split(/[ \t\n]+/); h.textContent = '';
words.forEach(function (w, i) { var s = document.createElement('span'); s.className = 'w'; s.style.setProperty('--i', i); s.textContent = w;
if (i) h.appendChild(document.createTextNode(' ')); h.appendChild(s); }); })(document.getElementById('hero-title'));</script>
<p class="lede">Flexera is an Android launcher. Every app sits in one list, A&nbsp;to&nbsp;Z, with the alphabet on the edge where your thumb already is.</p>
<div class="dl">
<a class="btn btn--lg" href="https://git.mariosem.es/msemes/Flexera-Launcher-Releases/releases/download/latest/FlexeraLauncher.apk" data-apk><svg class="btn__mark" aria-hidden="true"><use href="#b-android"/></svg>Download the APK</a>
<p class="dl__note">Free, no ads, for Android 8.0 or newer. <a class="link" href="#install">How to install it</a></p>
</div>
</div>
<figure class="fig" data-fig>
<div class="fig__item fig__item--side fig__item--edge">
<div class="phone-host" data-phone="edge" role="img" aria-label="Drawing of a phone on its home screen, with a clock, a picture frame and a few apps. A thumb rests on a narrow band marked along the right edge, where sliding opens the app list."></div>
<p>Slide along the home screen’s edge, and the list opens.</p>
</div>
<div class="fig__item fig__item--main">
<div class="phone-host fig__phone" data-phone="hero" role="img" aria-label="Drawing of a phone with Flexera’s app list open. A thumb rests on the alphabet at the right edge, the letters near it curve out to the left, and F is shown large in a light circle beyond the curve, level with the apps under F."></div>
<p>The letter you’re on sits 16&nbsp;mm out, clear of your thumb.</p>
</div>
<div class="fig__item fig__item--side fig__item--quick">
<div class="phone-host" data-phone="quick" role="img" aria-label="Drawing of a phone past its last home screen page: the home screen slides away to the left, blurred and dimmed, and a black page comes in from the right, just past a dashed line 40% of the way across."></div>
<p>Swipe past your last page, and an app you picked opens.</p>
</div>
<noscript><p class="noscript">The drawings on this page need JavaScript. The download works without it.</p></noscript>
<figcaption>Drawn live at the app’s own measurements, with made-up apps.</figcaption>
</figure>
</section>
<section class="wrap sec story-sec" id="alphabet" aria-labelledby="alphabet-title">
<div class="grid story__lead">
<div class="part__head">
<h2 id="alphabet-title">The wave alphabet</h2>
</div>
</div>
<div class="grid story" data-story>
<div class="story__stage" aria-hidden="true"><div class="story__phones"><div class="phone-host" data-phone="story"></div></div></div>
<div class="story__flow">
<div class="story__part">
<article class="step" id="one-column" data-step>
<div class="step__text">
<h3>One column, A to Z</h3>
<p>Swipe up and every app is in one column on your own wallpaper, blurred just enough that white names stay readable over any picture.</p>
</div>
</article>
<article class="step" id="slide" data-step>
<div class="step__text">
<h3>Slide along the letters</h3>
<p>The letters sit low on the right edge, 20&nbsp;dp apart, so your thumb reaches every one without changing its grip. Near your thumb they swing out in a curve, so you can still read them.</p>
</div>
</article>
<article class="step" id="lands" data-step>
<div class="step__text">
<h3>Where the letter lands</h3>
<p>Stop on a letter and its apps come to the middle of the screen, not the top, which is the part furthest from your thumb.</p>
</div>
</article>
<article class="step" id="from-home" data-step>
<div class="step__text">
<h3>Straight from the home screen</h3>
<p>Slide along the edge of the home screen and the list opens under your thumb, already at that letter. Anywhere else, swipe up and hold for a moment.</p>
</div>
</article>
</div>
<section class="story__part story__night" id="past-the-last-page" aria-labelledby="past-title">
<div class="part__head">
<h2 id="past-title">Past the last page</h2>
<p class="intro">Swipe on past your last home screen page, and an app you picked opens there.</p>
</div>
<article class="step" id="no-page" data-step>
<div class="step__text">
<h3>A page that isn’t there</h3>
<p>The home screen follows your finger aside while a black page comes in. Let go past 40% and the app opens. Before that, it springs back.</p>
</div>
</article>
<article class="step" id="no-animation" data-step>
<div class="step__text">
<h3>No opening animation</h3>
<p>The app starts as your finger lifts and shows up on the black page as soon as it has something to draw. No zoom from the middle.</p>
<p class="note">Needs Android 12 or newer. Turn it on in Settings&nbsp;›&nbsp;Gestures&nbsp;›&nbsp;Quick launch.</p>
</div>
</article>
</section>
</div>
</div>
</section>
<section class="wrap sec" id="try" aria-labelledby="try-title">
<div class="grid play">
<div class="play__text">
<h2 id="try-title">Try it here</h2>
<p class="intro">Use it with a finger or a mouse. It behaves like the real launcher, up to a point.</p>
<div class="controls" role="group" aria-labelledby="show-me">
<p class="controls__label" id="show-me">Show me</p>
<div class="controls__row" data-demos>
<button class="tbtn" type="button" data-demo="drawer">Open the list</button>
<button class="tbtn" type="button" data-demo="scrub">Slide along the letters</button>
<button class="tbtn" type="button" data-demo="edge">Scrub from the home screen</button>
<button class="tbtn" type="button" data-demo="quick">Swipe past the last page</button>
<button class="tbtn tbtn--plain" type="button" data-demo="reset">Start over</button>
</div>
</div>
<div class="controls" role="group" aria-labelledby="two-settings">
<p class="controls__label" id="two-settings">Two settings from the app</p>
<div class="controls__row">
<button class="switch" type="button" role="switch" aria-checked="false" data-look="lefty"><span class="switch__track" aria-hidden="true"></span>Alphabet on the left edge</button>
<div class="seg-page" role="group" aria-label="Row size">
<button type="button" data-look="comfy" data-v="0" aria-pressed="true">Compact rows</button>
<button type="button" data-look="comfy" data-v="1" aria-pressed="false">Comfy rows</button>
</div>
</div>
</div>
<p class="play__caption" aria-live="polite" data-caption>Swipe up on the home screen to open the list.</p>
<p class="howto">Without the buttons: swipe up and hold still a moment, then slide. With a keyboard, Tab to the letters and use the arrow keys.</p>
</div>
<div class="play__stage">
<div class="phone-host" data-phone="play" role="group" aria-label="A working drawing of the launcher. The buttons beside it show each gesture if you can’t swipe on it."></div>
</div>
</div>
<div class="grid race" id="time-it" role="region" aria-labelledby="time-title">
<div class="race__stage" data-race-stage data-phase="idle">
<p class="race__pill" aria-hidden="true">Find <b data-race-pill>Radio</b></p>
<div class="phone-host race__host race__host--grid" data-race-grid aria-hidden="true"></div>
<div class="phone-host race__host race__host--list" data-phone="race" aria-hidden="true"></div>
<div class="race__overlay" data-race-overlay aria-hidden="true">
<p class="race__round" data-race-round>Round 1</p>
<p class="race__msg" data-race-msg>Press Start.</p>
</div>
</div>
<div class="race__side">
<h3 id="time-title">Time it: a grid against the list</h3>
<p id="time-rules">Find the named app in a grid drawer of 40 apps, then in Flexera’s list. It takes a mouse or a touch screen, and nothing is recorded.</p>
<table class="race__times">
<tr><th scope="row">Round 1, the grid</th><td data-race-t1>–</td></tr>
<tr><th scope="row">Round 2, the list</th><td data-race-t2>–</td></tr>
</table>
<p class="race__verdict" aria-live="polite" data-race-verdict></p>
<button class="btn" type="button" data-race-start aria-describedby="time-rules">Start</button>
</div>
</div>
</section>
<section class="wrap sec" id="smaller" aria-labelledby="smaller-title">
<h2 id="smaller-title">Smaller things it adds</h2>
<ul class="things">
<li class="thing">
<h3>Folders at the bottom</h3>
<p>A folder opens full screen with its apps in a row along the bottom, right where your thumb is.</p>
</li>
<li class="thing">
<h3>Left-handed mode</h3>
<p>The alphabet can move to the left edge, and the rows can grow. The switches above try both.</p>
</li>
<li class="thing">
<h3>A clock and a picture frame</h3>
<p>A clock that shows the weather, and a frame that turns to the next photo every ten seconds.</p>
</li>
<li class="thing">
<h3>Moving from Smart Launcher</h3>
<p>Flexera reads a Smart Launcher backup and rebuilds your home screens from it, photo widgets too.</p>
</li>
</ul>
</section>
<section class="wrap sec" id="install" aria-labelledby="install-title">
<div class="install">
<div class="install__main">
<h2 id="install-title">Install Flexera</h2>
<p class="intro">Version <span data-version>1.0.6</span>, for Android 8.0 or newer. It’s free, and there are no ads in it.</p>
<div class="install__actions">
<a class="btn btn--lg" href="https://git.mariosem.es/msemes/Flexera-Launcher-Releases/releases/download/latest/FlexeraLauncher.apk" data-apk><svg class="btn__mark" aria-hidden="true"><use href="#b-android"/></svg>Download the APK</a>
<a class="link" href="https://git.mariosem.es/msemes/Flexera-Launcher-Releases/releases">Every release, with its notes</a>
</div>
</div>
<figure class="qr">
<svg class="qr__code" viewBox="-4 -4 49 49" role="img" aria-label="QR code that downloads the newest Flexera Launcher APK"><path class="qrline" stroke="currentColor" d="M0 0.5h7m2 0h2m1 0h1m2 0h2m2 0h3m1 0h1m4 0h1m2 0h2m1 0h7m-41 1h1m5 0h1m2 0h1m1 0h3m2 0h1m1 0h1m1 0h2m3 0h1m1 0h1m2 0h1m1 0h1m1 0h1m5 0h1m-41 1h1m1 0h3m1 0h1m1 0h1m1 0h1m1 0h3m6 0h3m2 0h3m5 0h1m1 0h3m1 0h1m-41 1h1m1 0h3m1 0h1m1 0h3m2 0h1m4 0h1m3 0h6m6 0h1m1 0h3m1 0h1m-41 1h1m1 0h3m1 0h1m1 0h1m3 0h1m1 0h4m1 0h5m4 0h1m1 0h3m1 0h1m1 0h3m1 0h1m-41 1h1m5 0h1m1 0h1m1 0h4m2 0h2m2 0h3m1 0h1m2 0h1m1 0h1m4 0h1m5 0h1m-41 1h7m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h7m-33 1h1m1 0h2m3 0h1m4 0h3m1 0h1m1 0h3m-29 1h1m1 0h5m2 0h1m3 0h1m2 0h2m4 0h5m2 0h1m1 0h1m2 0h5m-38 1h1m1 0h1m4 0h1m1 0h1m1 0h1m1 0h1m1 0h4m1 0h1m1 0h1m2 0h1m1 0h1m1 0h7m1 0h3m-40 1h1m1 0h2m1 0h2m1 0h1m3 0h2m5 0h3m4 0h2m3 0h1m6 0h1m-39 1h3m4 0h1m2 0h1m3 0h2m1 0h2m1 0h4m1 0h3m2 0h2m3 0h2m1 0h1m-39 1h2m2 0h4m2 0h1m2 0h1m1 0h2m4 0h1m1 0h3m2 0h1m1 0h1m4 0h3m-38 1h1m1 0h1m1 0h1m1 0h10m1 0h1m1 0h4m1 0h2m1 0h1m2 0h2m1 0h7m-40 1h1m1 0h1m2 0h1m4 0h4m4 0h1m1 0h1m2 0h4m1 0h2m2 0h1m1 0h1m1 0h1m-37 1h1m5 0h3m2 0h1m1 0h1m3 0h6m2 0h1m1 0h1m2 0h1m2 0h2m1 0h1m2 0h1m-40 1h1m3 0h3m1 0h1m1 0h3m1 0h3m1 0h1m2 0h5m2 0h1m3 0h1m1 0h1m2 0h2m-40 1h4m1 0h1m2 0h1m4 0h3m1 0h5m1 0h1m1 0h2m1 0h5m1 0h4m1 0h2m-41 1h3m2 0h2m2 0h1m3 0h1m3 0h1m3 0h1m2 0h1m2 0h2m3 0h1m3 0h2m-37 1h1m1 0h1m4 0h1m1 0h3m2 0h4m1 0h2m6 0h1m1 0h1m1 0h3m1 0h2m-34 1h4m1 0h1m1 0h1m3 0h2m2 0h1m2 0h5m2 0h1m2 0h1m4 0h2m-39 1h1m1 0h1m5 0h1m5 0h7m2 0h1m3 0h14m-38 1h5m1 0h2m3 0h1m6 0h2m2 0h1m1 0h2m1 0h1m1 0h1m3 0h3m-37 1h2m1 0h1m7 0h1m1 0h2m2 0h1m1 0h4m2 0h2m3 0h1m2 0h1m1 0h1m-36 1h1m2 0h4m8 0h1m2 0h1m4 0h2m2 0h1m5 0h1m-35 1h1m2 0h2m2 0h1m2 0h2m2 0h1m3 0h3m1 0h1m4 0h1m2 0h1m1 0h5m2 0h1m-39 1h1m2 0h2m1 0h1m1 0h1m3 0h1m1 0h1m3 0h1m5 0h2m1 0h2m1 0h4m-36 1h2m1 0h1m1 0h1m1 0h2m2 0h1m1 0h4m3 0h2m1 0h1m2 0h1m1 0h1m1 0h4m1 0h1m1 0h1m2 0h1m-40 1h1m3 0h3m5 0h2m2 0h1m5 0h4m2 0h1m1 0h2m4 0h3m-40 1h1m3 0h2m4 0h4m4 0h1m2 0h1m1 0h2m3 0h1m1 0h5m1 0h2m2 0h1m-41 1h1m1 0h1m1 0h1m1 0h1m7 0h1m1 0h1m4 0h2m1 0h5m3 0h4m1 0h1m-38 1h1m3 0h2m4 0h2m2 0h2m5 0h1m1 0h2m1 0h3m3 0h3m1 0h2m-38 1h1m1 0h2m2 0h5m6 0h1m6 0h4m1 0h1m2 0h8m-32 1h2m3 0h2m4 0h2m2 0h1m8 0h1m3 0h1m2 0h2m-41 1h7m3 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m3 0h1m1 0h3m1 0h3m1 0h1m1 0h3m-39 1h1m5 0h1m1 0h1m1 0h2m1 0h1m1 0h2m2 0h5m2 0h1m4 0h2m3 0h1m3 0h1m-41 1h1m1 0h3m1 0h1m1 0h3m1 0h1m3 0h1m1 0h4m1 0h5m1 0h1m2 0h5m1 0h2m-40 1h1m1 0h3m1 0h1m1 0h2m1 0h2m1 0h1m2 0h1m2 0h1m2 0h1m1 0h2m6 0h1m1 0h1m1 0h1m1 0h2m-41 1h1m1 0h3m1 0h1m1 0h1m1 0h1m3 0h5m1 0h1m1 0h1m1 0h1m2 0h2m2 0h6m1 0h1m-39 1h1m5 0h1m2 0h3m2 0h3m1 0h1m1 0h2m1 0h1m2 0h2m2 0h1m1 0h1m1 0h1m1 0h2m1 0h1m-40 1h7m1 0h1m1 0h1m2 0h2m2 0h1m1 0h1m2 0h6m1 0h3m1 0h1m1 0h2m1 0h1"/></svg>
<figcaption>Scan with your phone’s camera</figcaption>
</figure>
<ol class="steps">
<li><h3>Download</h3><p>Get the APK on your phone, or scan the code.</p></li>
<li><h3>Install</h3><p>Open the file, allow installs, and tap Install.</p></li>
<li><h3>Make it home</h3><p>Open Flexera and pick it as your home app.</p></li>
</ol>
</div>
</section>
<section class="wrap sec" id="questions" aria-labelledby="questions-title">
<div class="grid faq">
<h2 id="questions-title" class="faq__title">Before you install</h2>
<div class="faq__list">
<details open>
<summary>What goes online?</summary>
<div class="faq__a">
<p>Two things, and both name only the app, <code>FlexeraLauncher</code>, as their user agent:</p>
<ul>
<li>An update check to the release page, about once a day. A download starts only when you tap Download and install.</li>
<li>The clock’s weather, once you’ve set a town for it: its coordinates go to Open-Meteo, rounded to about a kilometre.</li>
</ul>
<p>It never asks for your location, nothing needs an account, and Lawnchair’s own online features are switched off.</p>
</div>
</details>
<details>
<summary>Why isn’t it on Google Play?</summary>
<div class="faq__a"><p>It’s only released as an APK on its release page. The launcher looks there for a new version about once a day.</p></div>
</details>
<details>
<summary>Android warned me before installing. Is that normal?</summary>
<div class="faq__a"><p>Yes. Android asks before it installs anything from outside the Play Store, and Play Protect may add that the app can ask for notification access and accessibility. The first is for notification dots and the line under app names, the second only for gestures such as double-tap to lock. Both stay off until you turn them on. On Android 13 and newer you may first need Allow restricted settings, in the menu of the app’s App info.</p></div>
</details>
<details>
<summary>Will it run on my phone?</summary>
<div class="faq__a"><p>It needs Android 8.0 or newer. Before Android 12 there’s no quick launch, and the backdrop behind the list is dark without the blur.</p></div>
</details>
<details>
<summary>Can I go back to my old launcher?</summary>
<div class="faq__a"><p>Yes, whenever you like, in Settings&nbsp;›&nbsp;Apps&nbsp;›&nbsp;Default apps&nbsp;›&nbsp;Home app. Switching deletes nothing, and your old launcher keeps its layout.</p></div>
</details>
<details>
<summary>Does it work with TalkBack?</summary>
<div class="faq__a"><p>Yes. With TalkBack the alphabet is one slider that moves a letter at a time, and sliding along the home screen’s edge can be switched off in the app drawer’s settings.</p></div>
</details>
</div>
</div>
</section>
</main>
<footer class="wrap foot">
<div class="foot__top">
<p class="top__brand"><img src="assets/flexera-icon-256.webp" alt="" width="28" height="28"><span>Flexera Launcher</span></p>
<p class="foot__credit">Built on <a class="link" href="https://github.com/LawnchairLauncher/lawnchair">Lawnchair</a>, which is built on Launcher3 from the Android Open Source Project. The home screen, the dock, folders, icon packs, themed icons, the grid and the gestures are their work.</p>
</div>
<div class="foot__end">
<p>© 2026 Flexera Launcher. Made by <span class="nom" data-nom>NOMNOM Inc.</span></p>
<a class="ghost" href="#top">Back to the top</a>
</div>
</footer>
</body>
</html>
+29
View File
@@ -0,0 +1,29 @@
# The website's nginx site, mounted by docker-compose.yml. Plain HTTP on port 80:
# HTTPS belongs to whatever stands in front of this container (a reverse proxy, a tunnel).
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
charset utf-8;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# Text goes out compressed (HTML always does).
gzip on;
gzip_types text/css application/javascript text/javascript;
gzip_min_length 1024;
# The page, its stylesheet and its script keep their names from one version to the next,
# so browsers ask each time whether theirs is still current (a short "not modified" answer).
location / {
try_files $uri $uri/ =404;
expires -1;
}
# Pictures and the font change rarely: kept for a week.
location ~* \.(?:png|jpg|webp|woff2)$ {
expires 7d;
}
}
+2065
View File
File diff suppressed because it is too large. Load diff
+724
View File
@@ -0,0 +1,724 @@
/* Flexera Launcher website.
Built from UI8's SimpleList landing kit: a near-black canvas, quiet raised surfaces with solid
hairlines, white pill buttons, large card radii. One typeface, Outfit, the launcher's own, so the
page and the drawn phones speak alike. Colour lives in the phones; the page itself is ink and one
grey, plus the icon's sweep once, as the rim of the hero's stage, and the cyan of the measurements.
Nothing is loaded from anyone else. */
@font-face { font-family: "Outfit"; src: url("fonts/outfit.woff2") format("woff2"); font-weight: 100 900; font-style: normal; font-display: swap; }
:root {
/* surfaces, darkest first (SimpleList: #0D0D0F canvas, #1A1A1E surface) */
--night: #000; --canvas: #0d0d0f; --surface: #141417; --raised: #1c1c20; --hover: #242429;
/* lines: solid on dark, so they sit quietly instead of glowing */
--line: #232328; --line-strong: #34343b;
/* ink and one grey, both a touch cool to agree with the icon's blues */
--white: #fff; --text: #e4e4e9; --muted: #a2a2ab;
/* Flexera: cyan for measurements; the sweep from the icon, used once */
--measure: #19dff8;
--sweep: linear-gradient(90deg, transparent, #19dff8 18%, #0899f4 34%, #0a4cc5 50%, #5e19da 66%, #dc29f8 82%, transparent);
/* type */
--ui: "Outfit", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
--sans: var(--ui); --mono: var(--ui);
/* the names the phone drawings were written against */
--ash: var(--muted); --border: var(--line-strong); --graphite: var(--raised); --ink: var(--surface);
--edge: rgba(255, 255, 255, .06) 0 1px 0 0 inset;
--key: rgba(255, 255, 255, .06) 0 1px 0 0 inset, var(--line-strong) 0 0 0 1px;
--lift: rgba(0, 0, 0, .25) 0 1px 2px, rgba(0, 0, 0, .25) 0 6px 16px;
/* motion: a long, soft landing for things that arrive, and a firmer curve for light and colour */
--ease-out: cubic-bezier(.19, 1, .22, 1); --ease-soft: cubic-bezier(.32, .72, 0, 1);
/* shape and space */
--r-xl: 40px; --r-lg: 28px; --r-md: 16px;
--pad: 32px; --gap: 24px; --max: 1120px; --head: 72px; --sec: 160px;
color-scheme: dark;
}
*, *::before, *::after { box-sizing: border-box; }
html.is-loading body { visibility: hidden; }
html { -webkit-text-size-adjust: 100%; background: var(--canvas); overflow-x: clip; scrollbar-width: thin; scrollbar-color: rgb(127 127 127 / .35) transparent; }
::-webkit-scrollbar { width: 10px; height: 10px; background: transparent; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: rgb(127 127 127 / .35); border-radius: 999px; border: 3px solid transparent; background-clip: padding-box; }
::-webkit-scrollbar-thumb:hover { background-color: rgb(127 127 127 / .55); }
::-webkit-scrollbar-corner { background: transparent; }
@media (prefers-reduced-motion: no-preference) { html { scroll-behavior: smooth; } }
body { margin: 0; background: var(--canvas); color: var(--muted); font: 400 18px/1.6 var(--ui); -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; font-synthesis: none; font-kerning: normal; overflow-x: clip; }
img, svg { display: block; }
a { color: inherit; }
p { margin: 0 0 16px; }
p, li, dd { text-wrap: pretty; }
h1, h2, h3 { margin: 0; color: var(--white); font-weight: 500; text-wrap: balance; }
h2 { font-size: 52px; line-height: 1.06; letter-spacing: -.03em; }
h3 { font-size: 24px; line-height: 1.3; letter-spacing: -.01em; }
::selection { background: var(--text); color: var(--canvas); }
:focus-visible { outline: 2px solid var(--white); outline-offset: 3px; border-radius: 4px; }
code { font: 500 1em/1 var(--ui); color: var(--text); }
.sprite { position: absolute; width: 0; height: 0; overflow: hidden; }
.skip { position: absolute; left: 16px; top: -64px; z-index: 100; display: inline-flex; align-items: center; height: 44px; padding: 0 20px; border-radius: 999px; background: var(--white); color: var(--canvas); font: 500 16px/1 var(--ui); text-decoration: none; }
.skip:focus { top: 14px; }
.wrap { max-width: calc(var(--max) + 2 * var(--pad)); margin: 0 auto; padding-left: var(--pad); padding-right: var(--pad); }
.grid { display: grid; grid-template-columns: repeat(12, minmax(0, 1fr)); column-gap: var(--gap); }
.intro { margin: 20px 0 0; max-width: 30em; font-size: 20px; line-height: 1.55; color: var(--muted); }
.note { margin: 20px 0 0; font-size: 16px; line-height: 1.55; color: var(--muted); }
.link { color: var(--text); text-decoration: underline; text-decoration-color: rgba(255, 255, 255, .3); text-decoration-thickness: 1px; text-underline-offset: 4px; transition: color .15s ease, text-decoration-color .15s ease; }
.link:hover { color: var(--white); text-decoration-color: var(--white); }
.ghost { color: var(--muted); text-decoration: none; transition: color .15s ease; }
.ghost:hover { color: var(--white); }
/* buttons: SimpleList's pills. White is the one primary; everything else is quieter. */
.btn { display: inline-flex; align-items: center; justify-content: center; gap: 10px; height: 48px; padding: 0 24px; border: 0; border-radius: 999px; background: var(--white); color: var(--canvas); font: 500 16px/1 var(--ui); text-decoration: none; white-space: nowrap; cursor: pointer; box-shadow: var(--lift); transition: background-color .15s ease, transform .2s var(--ease-soft), box-shadow .2s ease; }
.btn:hover { background: color-mix(in oklch, var(--white) 88%, var(--canvas)); }
@media (hover: hover) and (pointer: fine) { .btn:hover { transform: translateY(-1px); box-shadow: rgba(0, 0, 0, .3) 0 2px 4px, rgba(0, 0, 0, .3) 0 12px 28px; } }
.btn:active { transform: scale(.97); }
.btn--lg { height: 56px; padding: 0 28px; font-size: 17px; }
.btn--sm { height: 40px; padding: 0 18px; font-size: 15px; }
.btn__mark { flex: none; width: 20px; height: 20px; fill: currentColor; margin-left: -4px; }
/* the bar: glass over the page (there is content scrolling under it), sticky from 700 px up */
.head { position: relative; z-index: 50; background: rgba(13, 13, 15, .72); -webkit-backdrop-filter: blur(20px) saturate(160%); backdrop-filter: blur(20px) saturate(160%); box-shadow: 0 1px 0 var(--line); transition: background-color .3s ease, box-shadow .3s ease; }
html.js:not(.is-scrolled) .head { background-color: transparent; box-shadow: none; } /* clear at the top of the page; glass once something scrolls under it (script.js) */
.top { display: flex; align-items: center; gap: 16px; height: var(--head); }
.top__brand { display: flex; align-items: center; gap: 12px; margin: 0; color: var(--white); font: 500 17px/1 var(--ui); letter-spacing: -.01em; text-decoration: none; }
.top__brand img { width: 28px; height: 28px; border-radius: 8px; }
.top__links { margin-left: auto; display: flex; align-items: center; gap: 32px; font: 400 16px/1 var(--ui); }
@media (min-width: 700px) {
.head { position: sticky; top: 0; }
html { scroll-padding-top: 88px; }
}
@supports not ((backdrop-filter: blur(1px)) or (-webkit-backdrop-filter: blur(1px))) { .head { background: rgba(13, 13, 15, .96); } }
@media (prefers-reduced-transparency: reduce) { .head { background: var(--canvas); -webkit-backdrop-filter: none; backdrop-filter: none; } }
/* hero: the claim and the download, centred, then the product on a stage of its own */
.hero { padding-top: 96px; }
.hero__text { max-width: 920px; margin: 0 auto; text-align: center; }
.hero h1 { font-size: 80px; line-height: 1.02; letter-spacing: -.04em; }
.hero h1 .w { display: inline-block; } /* one box per word, so each can rise on its own (see Motion) */
.lede { max-width: 31em; margin: 28px auto 0; font-size: 21px; line-height: 1.55; color: var(--muted); }
.dl { display: flex; flex-direction: column; align-items: center; gap: 18px; margin-top: 40px; }
.dl__note { margin: 0; font-size: 16px; line-height: 1.5; color: var(--muted); }
.dl__note .link { white-space: nowrap; }
/* The lineup, after SimpleList's hero: three stills straight on the page, standing on one line.
The list is in front and larger; a gesture stands either side of it, smaller and a step back.
Each has its caption under it, and the captions start on one line too (the rows are shared). */
.fig { position: relative; isolation: isolate; max-width: 960px; margin: 72px auto 0;
display: grid; grid-template-columns: minmax(0, 4fr) minmax(0, 5fr) minmax(0, 4fr); column-gap: 48px; row-gap: 28px; }
.fig__item { grid-row: 1 / span 2; display: grid; grid-template-rows: subgrid; }
.fig__item--edge { grid-column: 1; }
.fig__item--main { grid-column: 2; }
.fig__item--quick { grid-column: 3; }
.fig__item .phone-host { align-self: end; }
.fig__item p { align-self: start; margin: 0; font-size: 16px; line-height: 1.5; color: var(--muted); text-align: center; text-wrap: balance; }
.fig__item--side .phone-host { filter: brightness(.8); }
/* The icon's sweep, once: the rim of the phone in front, lit at two corners, and its light on the page. */
.fig__phone::before, .fig__phone::after { content: ""; position: absolute; z-index: -1; border-radius: calc(62px * var(--s, .8)); pointer-events: none;
background: linear-gradient(var(--rim, 135deg), #19dff8, #0899f4 12%, rgba(10, 76, 197, 0) 34%, rgba(94, 25, 218, 0) 66%, #5e19da 88%, #dc29f8); } /* --rim turns with the scroll position (script.js) */
.fig__phone::before { inset: -2px; }
.fig__phone::after { inset: -8px; filter: blur(24px); opacity: .45; }
.fig__phone .phone { box-shadow: inset 0 0 0 2px #3c3c42, inset 0 0 0 5px #0b0b0d, 0 0 0 1.5px rgba(255, 255, 255, .22); } /* the rim's light stands in for the shadow */
.fig figcaption { grid-column: 1 / -1; grid-row: 3; margin-top: 12px; font-size: 15px; line-height: 1.5; color: var(--muted); text-align: center; text-wrap: balance; }
.fig noscript { grid-column: 1 / -1; grid-row: 3; }
.noscript { margin: 0; padding: 24px; border: 1px dashed var(--line-strong); border-radius: var(--r-md); font-size: 16px; color: var(--muted); text-align: center; }
/* Without JavaScript there are no drawings: the captions stand as plain text, and the parts that
only work with the drawings are left out. */
html:not(.js) .phone-host:empty, html:not(.js) .story__stage { display: none; }
html:not(.js) .fig { row-gap: 0; }
html:not(.js) .fig noscript { margin-top: 28px; }
html:not(.js) .fig figcaption, html:not(.js) #try, html:not(.js) .needs-js { display: none; }
/* sections: separated by space, not lines */
.sec { padding-top: var(--sec); }
/* the wave alphabet: the phone stays put while the steps scroll past it */
.story__lead .part__head { grid-column: 1 / span 6; }
.story { margin-top: 8px; align-items: start; }
.story__stage { grid-column: 7 / span 5; grid-row: 1; position: sticky; top: 0; height: 100vh; height: 100svh; display: grid; place-items: center; z-index: 1; pointer-events: none; }
.story__phones { position: relative; height: min(calc(100vh - 168px), 720px); height: min(calc(100svh - 168px), 720px); aspect-ratio: 414 / 868; }
.story__phones .phone-host { position: absolute; inset: 0; }
.story__flow { grid-column: 1 / -1; grid-row: 1; display: grid; grid-template-columns: subgrid; position: relative; z-index: 0; }
.story__part { grid-column: 1 / -1; display: grid; grid-template-columns: subgrid; }
.story__part > .part__head { grid-column: 1 / span 5; }
.step { grid-column: 1 / -1; display: grid; grid-template-columns: subgrid; align-items: center; min-height: min(68vh, 640px); min-height: min(68svh, 640px); padding: 48px 0; }
.step__text { grid-column: 1 / span 5; grid-row: 1; }
.step__text h3 { font-size: 30px; line-height: 1.2; letter-spacing: -.02em; }
.step__text p { max-width: 26em; margin: 16px 0 0; font-size: 19px; line-height: 1.6; }
.step__text .note { font-size: 16px; }
/* Past the last page: the one band of true black, edge to edge, the page quick launch brings in. */
.story__night { position: relative; padding: 140px 0 100px; margin-top: 80px; }
.story__night::before { content: ""; position: absolute; top: 0; bottom: 0; left: 50%; width: 100vw; margin-left: -50vw; background: var(--night); box-shadow: 0 -1px 0 var(--line), 0 1px 0 var(--line); z-index: -1; }
/* try it */
.play { align-items: center; }
.play__text { grid-column: 1 / span 6; }
.play__stage { grid-column: 8 / span 4; display: grid; place-items: center; }
.play .phone-host { position: relative; height: min(78vh, 740px); height: min(78svh, 740px); touch-action: pan-y; }
.play .phone-host.is-armed { touch-action: none; }
.arm-hint { display: none; }
@media (pointer: coarse) {
.is-armable:not(.is-armed) .arm-hint { display: block; position: absolute; left: 50%; bottom: 13%; z-index: 3; translate: -50% 0; margin: 0; padding: 10px 18px; border-radius: 999px; background: var(--white); color: var(--canvas); font: 500 15px/1.2 var(--ui); white-space: nowrap; pointer-events: none; box-shadow: var(--lift); }
}
.controls { margin-top: 40px; }
.controls + .controls { margin-top: 28px; }
.controls__label { margin: 0 0 12px; font-size: 16px; line-height: 1.4; color: var(--text); }
.controls__row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.tbtn { height: 44px; padding: 0 18px; border: 0; border-radius: 999px; background: var(--raised); color: var(--text); font: 400 15px/1 var(--ui); cursor: pointer; box-shadow: var(--key); transition: background-color .15s ease, color .15s ease, transform .15s ease; }
.tbtn:hover { background: var(--hover); color: var(--white); }
.tbtn:active { transform: scale(.97); }
.tbtn--plain { background: transparent; box-shadow: none; color: var(--muted); }
.tbtn--plain:hover { background: transparent; color: var(--white); }
.switch { display: inline-flex; align-items: center; gap: 12px; height: 44px; padding: 0 12px 0 0; border: 0; background: none; color: var(--text); font: 400 15px/1 var(--ui); cursor: pointer; }
.switch__track { position: relative; flex: none; width: 40px; height: 24px; border-radius: 999px; background: var(--raised); box-shadow: var(--key); transition: background-color .15s ease; }
.switch__track::after { content: ""; position: absolute; top: 4px; left: 4px; width: 16px; height: 16px; border-radius: 50%; background: var(--muted); transition: transform .15s ease, background-color .15s ease; }
.switch[aria-checked="true"] .switch__track { background: var(--white); box-shadow: none; }
.switch[aria-checked="true"] .switch__track::after { transform: translateX(16px); background: var(--canvas); }
.seg-page { display: inline-flex; padding: 3px; border-radius: 999px; background: var(--raised); box-shadow: var(--key); }
.seg-page button { height: 38px; padding: 0 16px; border: 0; border-radius: 999px; background: transparent; color: var(--muted); font: 400 15px/1 var(--ui); cursor: pointer; transition: color .15s ease, background-color .15s ease; }
.seg-page button:not([aria-pressed="true"]):hover { color: var(--white); }
.seg-page button[aria-pressed="true"] { background: var(--white); color: var(--canvas); }
@media (pointer: coarse) { .seg-page button { height: 44px; padding: 0 18px; } } /* a finger's worth */
/* a status line, not a field: it keeps room for two lines so the layout doesn't jump as it changes */
.play__caption { margin: 40px 0 0; min-height: 3.2em; font-size: 19px; line-height: 1.6; color: var(--white); }
.howto { margin: 12px 0 0; max-width: 30em; font-size: 16px; line-height: 1.55; color: var(--muted); }
/* the race: a card of its own, SimpleList's large surface */
.race { align-items: center; margin-top: 140px; padding: 88px 0; border: 1px solid var(--line); border-radius: var(--r-xl); background: var(--surface); box-shadow: var(--edge); }
.race__stage { grid-column: 2 / span 4; justify-self: center; position: relative; height: min(74vh, 700px); height: min(74svh, 700px); aspect-ratio: 414 / 868; }
.race__side { grid-column: 7 / span 5; padding-right: 24px; }
.race__side h3 { font-size: 36px; line-height: 1.12; letter-spacing: -.025em; }
.race__side > p:not([class]) { margin: 16px 0 0; max-width: 26em; }
.race__stage .race__host { position: absolute; inset: 0; transition: opacity .3s ease; touch-action: pan-y; } /* two classes: it has to beat .phone-host's position, which comes later */
.race__stage[data-phase="r2"] .race__host--list { touch-action: none; } /* round two scrubs the letters */
.race__stage[data-phase="between"] .race__host--grid, .race__stage[data-phase="r2"] .race__host--grid, .race__stage[data-phase="done"] .race__host--grid,
.race__stage[data-phase="idle"] .race__host--list, .race__stage[data-phase="r1"] .race__host--list { opacity: 0; pointer-events: none; }
.race__overlay { position: absolute; left: 8%; right: 8%; top: 50%; translate: 0 -50%; z-index: 3; padding: 24px; border-radius: 20px; background: rgba(13, 13, 15, .84); -webkit-backdrop-filter: blur(24px); backdrop-filter: blur(24px); box-shadow: var(--key); transition: opacity .25s ease; }
.race__stage[data-phase="r1"] .race__overlay, .race__stage[data-phase="r2"] .race__overlay, .race__stage[data-phase="done"] .race__overlay { opacity: 0; pointer-events: none; }
.race__round { margin: 0; color: var(--white); font: 500 26px/1.2 var(--ui); font-variant-numeric: tabular-nums; }
.race__msg { margin: 8px 0 0; font-size: 16px; line-height: 1.5; color: var(--muted); }
.race__pill { position: absolute; left: 50%; top: -48px; translate: -50% 0; z-index: 4; display: flex; align-items: center; gap: 6px; height: 36px; margin: 0; padding: 0 16px; border-radius: 999px; background: var(--raised); box-shadow: var(--key); color: var(--muted); white-space: nowrap; font: 400 16px/1 var(--ui); opacity: 0; transition: opacity .25s ease; }
.race__pill b { color: var(--white); font-weight: 500; }
.race__stage[data-phase="r1"] .race__pill, .race__stage[data-phase="r2"] .race__pill, .race__stage[data-phase="between"] .race__pill { opacity: 1; }
.race__times { width: 100%; max-width: 26em; margin: 32px 0 20px; border-collapse: collapse; font-size: 17px; }
.race__times th, .race__times td { padding: 14px 0; border-top: 1px solid var(--line-strong); border-bottom: 1px solid var(--line-strong); }
.race__times th { text-align: left; font-weight: 400; color: var(--text); }
.race__times td { text-align: right; color: var(--white); font: 500 17px/1.5 var(--ui); font-variant-numeric: tabular-nums; }
.race__verdict { min-height: 3.2em; margin: 0 0 20px; color: var(--white); }
/* smaller things: a plain list, two by two; the content is small, so the form is too */
.things { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 56px 80px; margin: 56px 0 0; padding: 0; list-style: none; }
.thing h3 { font-size: 22px; }
.thing p { max-width: 26em; margin: 10px 0 0; font-size: 18px; }
/* install: the closing card */
.install { display: grid; grid-template-columns: minmax(0, 1fr) auto; column-gap: 64px; padding: 80px; border: 1px solid var(--line); border-radius: var(--r-xl); background: var(--surface); box-shadow: var(--edge); }
.install__main { grid-column: 1; align-self: center; }
.install__main h2 { font-size: 64px; letter-spacing: -.035em; }
.install__main [data-version] { font-variant-numeric: tabular-nums; color: var(--text); }
.install__actions { display: flex; flex-wrap: wrap; align-items: center; gap: 20px 32px; margin-top: 40px; font-size: 17px; }
.qr { grid-column: 2; margin: 0; }
.qr__code { width: 208px; height: 208px; padding: 16px; border-radius: var(--r-lg); background: var(--white); color: var(--canvas); }
.qr__code path { fill: none; stroke-width: 1; shape-rendering: crispEdges; }
.qr figcaption { margin-top: 16px; font-size: 15px; color: var(--muted); text-align: center; }
.steps { grid-column: 1 / -1; display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 40px; margin: 72px 0 0; padding: 40px 0 0; border-top: 1px solid var(--line-strong); list-style: none; }
.steps h3 { font-size: 20px; }
.steps p { margin: 8px 0 0; font-size: 17px; line-height: 1.55; }
/* questions: the title on the left, the answers on the right */
.faq { align-items: start; }
.faq__title { grid-column: 1 / span 4; position: sticky; top: 112px; }
.faq__list { grid-column: 6 / span 7; border-top: 1px solid var(--line-strong); }
.faq details { border-bottom: 1px solid var(--line-strong); }
.faq summary { position: relative; display: block; padding: 26px 56px 26px 0; color: var(--white); font-size: 20px; line-height: 1.4; font-weight: 500; letter-spacing: -.01em; cursor: pointer; list-style: none; border-radius: 0; text-wrap: balance; }
.faq summary::-webkit-details-marker { display: none; }
.faq summary::before, .faq summary::after { content: ""; position: absolute; right: 12px; top: 50%; width: 16px; height: 1.5px; margin-top: -.75px; border-radius: 1px; background: var(--muted); transition: transform .2s ease, background-color .15s ease; }
.faq summary::after { transform: rotate(90deg); }
.faq details[open] summary::after { transform: rotate(0deg); }
.faq summary:hover::before, .faq summary:hover::after { background: var(--white); }
.faq summary:focus-visible { outline-offset: 4px; }
.faq__a { padding: 0 56px 28px 0; }
.faq__a p:last-child { margin-bottom: 0; }
.faq__a ul { margin: 0 0 16px; padding-left: 1.1em; }
.faq__a li { margin: 0 0 10px; padding-left: 4px; }
.faq__a li::marker { color: var(--line-strong); }
/* footer */
.foot { margin-top: var(--sec); padding-top: 56px; padding-bottom: 48px; }
.foot__top { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr); gap: 32px 80px; padding-top: 56px; border-top: 1px solid var(--line); }
.foot__credit { max-width: 36em; margin: 0; font-size: 16px; line-height: 1.6; }
.foot__end { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 12px 32px; margin-top: 56px; font-size: 15px; }
.foot__end p { margin: 0; }
/* An egg: point at NOMNOM Inc. and something comes in from the right and eats it, a letter at a time
(script.js, setupNom). It is one of the launcher's own icons with a jaw, lavender with an indigo eye. */
.nom { position: relative; display: inline-block; white-space: nowrap; }
.nom__l { transition: opacity .1s linear; }
.nom__l.is-eaten { opacity: 0; }
.nom__muncher { position: absolute; left: 0; top: 50%; width: 20px; height: 20px; margin-top: -10px; pointer-events: none; opacity: 0; }
.nom__muncher i { position: absolute; left: 0; right: 0; height: 50%; background: #dedcf7; }
.nom__muncher i:first-child { top: 0; border-radius: 7px 7px 2px 2px; transform-origin: 100% 100%; }
.nom__muncher i:last-child { bottom: 0; border-radius: 2px 2px 7px 7px; transform-origin: 100% 0; }
.nom__muncher i:first-child::after { content: ""; position: absolute; left: 5px; top: 4px; width: 3px; height: 3px; border-radius: 50%; background: #231c86; }
.nom__muncher.is-chomping i:first-child { animation: nom-up .15s ease-in-out infinite alternate; }
.nom__muncher.is-chomping i:last-child { animation: nom-down .15s ease-in-out infinite alternate; }
.nom__muncher.is-full { animation: nom-gulp .55s var(--ease-soft); }
.nom__muncher.is-leaving { transition: opacity .25s ease; }
@keyframes nom-up { from { transform: rotate(2deg); } to { transform: rotate(38deg); } }
@keyframes nom-down { from { transform: rotate(-2deg); } to { transform: rotate(-38deg); } }
@keyframes nom-gulp { 30% { transform: translateX(-2px) scale(1.2, .8); } 62% { transform: translateX(-2px) scale(.9, 1.12); } }
/* =====================================================================
Motion. Three kinds, and all of it stands down for reduced motion:
the hero's entrance, once, when the fonts are in; sections that rise
into place as they are scrolled to; and light that answers the scroll
position or the pointer. Without JavaScript nothing here hides anything.
===================================================================== */
@media screen and (prefers-reduced-motion: no-preference) {
/* The entrance: the headline word by word, then the copy and the button, then the phones, the
list first. Each rule only names where a thing comes from; it ends as the page has it.
script.js plays the phones' own part on the same clock: the thumb comes down and the wave goes out. */
@keyframes word-in { from { opacity: 0; transform: translateY(.22em); filter: blur(12px); } }
@keyframes rise-in { from { opacity: 0; transform: translateY(20px); filter: blur(6px); } }
@keyframes phone-in { from { opacity: 0; transform: translateY(72px) scale(.96); } }
@keyframes fade-in { from { opacity: 0; } }
html.js:not(.is-loading) .hero h1 .w { animation: word-in .9s var(--ease-out) calc(var(--i, 0) * 70ms) backwards; }
html.js:not(.is-loading) .lede { animation: rise-in .9s var(--ease-out) .5s backwards; }
html.js:not(.is-loading) .dl { animation: rise-in .9s var(--ease-out) .62s backwards; }
html.js:not(.is-loading) .fig__item .phone-host { animation: phone-in 1.3s var(--ease-out) .7s backwards; }
html.js:not(.is-loading) .fig__item--edge .phone-host { animation-delay: .84s; }
html.js:not(.is-loading) .fig__item--quick .phone-host { animation-delay: .94s; }
html.js:not(.is-loading) .fig__phone::before, html.js:not(.is-loading) .fig__phone::after { animation: fade-in 1.6s ease 1.5s backwards; }
html.js:not(.is-loading) .fig__item p, html.js:not(.is-loading) .fig figcaption { animation: fade-in .9s ease 1.7s backwards; }
/* Sections rise into place the first time they are scrolled to (script.js marks them .rv, then .is-in). */
html.rv-on .rv { opacity: 0; transform: translateY(28px); transition: opacity .9s var(--ease-soft) var(--rv-d, 0ms), transform 1.1s var(--ease-out) var(--rv-d, 0ms), filter .9s var(--ease-soft) var(--rv-d, 0ms); }
html.rv-on .rv--h { filter: blur(10px); } /* headings also come out of a blur */
html.rv-on .rv.is-in { opacity: 1; transform: none; filter: none; }
html.rv-on .rv.rv--now { transition: none; }
/* The answers open and close at their own height, where the browser can do that. */
@supports (interpolate-size: allow-keywords) {
.faq details { interpolate-size: allow-keywords; }
.faq details::details-content { block-size: 0; overflow: clip; opacity: 0; transition: block-size .4s var(--ease-soft), opacity .3s ease, content-visibility .4s allow-discrete; }
.faq details[open]::details-content { block-size: auto; opacity: 1; }
}
}
/* The story: the chapter the phone is playing is lit, the others wait at a lower light. */
@media screen {
.story.is-live .step__text { transition: opacity .45s var(--ease-soft); }
.story.is-live .step:not(.is-active) .step__text { opacity: .36; }
}
/* A light on the rim of the two cards, under the pointer (script.js adds .glint and moves it). */
.race, .install { position: relative; }
.glint { position: absolute; inset: -1px; padding: 1px; border-radius: inherit; pointer-events: none; opacity: 0; transition: opacity .4s ease;
background: radial-gradient(520px circle at var(--mx, 50%) var(--my, 0px), rgba(255, 255, 255, .4), rgba(255, 255, 255, 0) 60%);
-webkit-mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0); -webkit-mask-composite: xor;
mask: linear-gradient(#000 0 0) content-box exclude, linear-gradient(#000 0 0); }
.race:hover > .glint, .install:hover > .glint { opacity: 1; }
@media (prefers-contrast: more) { :root { --line: #4a4a52; --line-strong: #6a6a72; --muted: #c4c4cc; --text: #f2f2f5; } .story.is-live .step:not(.is-active) .step__text { opacity: 1; } }
@media (prefers-reduced-transparency: reduce) { .race__overlay { background: var(--surface); -webkit-backdrop-filter: none; backdrop-filter: none; } }
/* =====================================================================
The phone. Drawn at 390 x 844, one pixel per dp, and scaled to fit
its host, so every measurement inside stays the same at any size.
===================================================================== */
.phone-host { position: relative; aspect-ratio: 414 / 868; }
.phone {
position: absolute; left: 0; top: 0;
width: 414px; height: 868px;
padding: 12px;
border-radius: 60px;
background: #141416;
box-shadow: inset 0 0 0 2px #3c3c42, inset 0 0 0 5px #0b0b0d, 0 0 0 1.5px rgba(255, 255, 255, .22), 0 6px 56px 12px rgba(0, 0, 0, .45);
transform-origin: 0 0;
transform: scale(var(--s, .5));
user-select: none; -webkit-user-select: none;
}
.phone::before, .phone::after { /* side buttons */
content: ""; position: absolute; right: -4px; width: 4px; border-radius: 0 3px 3px 0; background: #2a2a2f;
}
.phone::before { top: 190px; height: 70px; }
.phone::after { top: 290px; height: 110px; }
.screen {
position: relative;
width: 390px; height: 844px;
border-radius: 48px;
overflow: hidden;
background: #0b0b0d;
font-family: var(--ui);
color: #fff;
isolation: isolate;
contain: strict;
}
.screen * { box-sizing: border-box; }
.screen .ic svg, .screen .gl { fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
/* The wallpaper and the home screen sit in one layer, which quick launch moves aside. Each has a
blurred copy that fades in over it; the blur itself never animates.
The wallpaper is a plain abstract one: a few flat shapes in muted shades of the icon's indigo,
so that the blur has edges to soften.
Its shapes are placed from --o, so the blurred copy, which is larger, lines up with the sharp one. */
.world { position: absolute; inset: 0; transform-origin: 50% 50%; }
.wall {
--o: 0px;
position: absolute; inset: -30px;
background-color: #141045;
background-image:
radial-gradient(circle, #2b2380 0 70px, transparent 70.5px),
radial-gradient(circle, #07062a 0 22px, transparent 22.5px),
radial-gradient(circle, #4f56c8 0 112px, transparent 112.5px),
linear-gradient(#4f56c8, #4f56c8),
radial-gradient(circle, #3a2a9a 0 96px, transparent 96.5px),
linear-gradient(#3a2a9a, #3a2a9a),
radial-gradient(circle, transparent 0 131px, #c9c7f2 131.5px 133.5px, transparent 134px),
linear-gradient(to bottom, #181355, #0d0a38);
background-size: 140px 140px, 44px 44px, 224px 224px, 224px 344px, 192px 192px, 192px 214px, 268px 268px, 450px 904px;
background-position:
calc(302px + var(--o)) calc(140px + var(--o)),
calc(60px + var(--o)) calc(778px + var(--o)),
calc(8px + var(--o)) calc(448px + var(--o)),
calc(8px + var(--o)) calc(560px + var(--o)),
calc(256px + var(--o)) calc(594px + var(--o)),
calc(256px + var(--o)) calc(690px + var(--o)),
calc(-14px + var(--o)) calc(426px + var(--o)),
var(--o) var(--o);
background-repeat: no-repeat;
}
.wall--blur { --o: 30px; inset: -60px; filter: blur(30px); opacity: 0; will-change: opacity; }
.sbar { position: absolute; left: 0; right: 0; top: 0; height: 40px; padding: 14px 28px 0; display: flex; justify-content: space-between; font: 600 14px/1 var(--ui); z-index: 30; pointer-events: none; }
.sbar__icons { display: flex; align-items: center; gap: 6px; }
.sbar__sig { display: flex; align-items: flex-end; gap: 2px; height: 11px; }
.sbar__sig i { width: 3px; background: #fff; border-radius: 1px; }
.sbar__sig i:nth-child(1) { height: 4px; } .sbar__sig i:nth-child(2) { height: 6px; } .sbar__sig i:nth-child(3) { height: 8px; } .sbar__sig i:nth-child(4) { height: 11px; }
.sbar__bat { width: 22px; height: 11px; border-radius: 3px; border: 1.5px solid #fff; padding: 1.5px; }
.sbar__bat::before { content: ""; display: block; width: 72%; height: 100%; background: #fff; border-radius: 1px; }
.notch { position: absolute; left: 50%; top: 12px; width: 22px; height: 22px; margin-left: -11px; border-radius: 50%; background: #000; z-index: 31; box-shadow: inset 0 0 0 4px #111; }
.home { position: absolute; inset: 0; transform-origin: 50% 60%; }
.home--blur { opacity: 0; pointer-events: none; will-change: opacity, transform; }
.home__blurred { position: absolute; inset: 0; filter: blur(24px); }
.pages { position: absolute; inset: 0; }
.page { position: absolute; top: 0; width: 390px; height: 844px; }
.cell { position: absolute; display: flex; flex-direction: column; align-items: center; padding-top: 8px; }
.cell .lbl { margin-top: 7px; font: 500 12.5px/1.2 var(--ui); text-shadow: 0 1px 4px rgba(0, 0, 0, .55); white-space: nowrap; }
.cell.tap .ic, .cell.tap .fic { animation: tapb .3s ease; }
@keyframes tapb { 40% { transform: scale(.86); } }
/* Icons are drawn the way Android 13 and Lawnchair theme them, tinted from the wallpaper, with
a few apps that don't support it left in their own colours (script.js, ODD). */
.ic {
position: relative; display: grid; place-items: center;
width: 58px; height: 58px; border-radius: 30%;
color: var(--fg, #231c86);
background: var(--bg, #dedcf7);
box-shadow: 0 4px 10px -6px rgba(0, 0, 0, .5);
flex: none;
}
.ic svg { width: 46%; height: 46%; }
.ndot { position: absolute; top: 4px; left: calc(50% + 20px); width: 13px; height: 13px; border-radius: 50%; background: #231c86; border: 2px solid #dedcf7; }
.fic { width: 58px; height: 58px; padding: 7px; border-radius: 30%; background: rgba(10, 9, 51, .55); display: grid; grid-template-columns: 1fr 1fr; gap: 4px; }
.ic--mini { width: 100%; height: auto; aspect-ratio: 1; box-shadow: none; }
.ic--mini svg { stroke-width: 2.6; }
.w-clock { position: absolute; padding: 26px 18px 0; }
.clk__line { white-space: nowrap; }
.clk__line > span { display: inline-block; will-change: transform; }
.clk__time { font: 300 88px/1 var(--ui); letter-spacing: -.02em; font-variant-numeric: tabular-nums; }
.clk__date { margin-top: 8px; font: 500 18px/1.2 var(--ui); }
.clk__wx { margin-top: 4px; font: 400 16px/1.2 var(--ui); opacity: .92; }
/* The picture frame's three photos: the sea, mountains, and lemons on a checked cloth. */
.w-pics { position: absolute; padding: 8px 12px 18px; }
.pics { position: relative; width: 100%; height: 100%; border-radius: 30px; overflow: hidden; box-shadow: 0 10px 24px -10px rgba(0, 0, 0, .6); }
.pic { position: absolute; inset: 0; opacity: 0; transition: opacity .6s ease; }
.pic.on { opacity: 1; }
.pic--a {
background:
repeating-linear-gradient(to bottom, transparent 0 8px, rgba(255, 255, 255, .16) 8px 9px) 0 74% / 100% 30% no-repeat,
linear-gradient(to bottom, #9fcbe8 0, #dcecf5 50%, #2c7aa6 50.5%, #1a557e 84%, #e2d1ab 84.5%, #cdb68c 100%);
}
.pic--b {
background:
linear-gradient(150deg, transparent 52%, #3a4757 52.4%) 0 100% / 60% 62% no-repeat,
linear-gradient(-140deg, transparent 50%, #4b5d6e 50.4%) 100% 100% / 75% 75% no-repeat,
linear-gradient(140deg, transparent 50%, #5f7385 50.4%) 0 100% / 75% 55% no-repeat,
linear-gradient(to bottom, #9fb7c9, #dce4e8);
}
.pic--c {
background:
radial-gradient(ellipse 7% 5% at 33% 50%, rgba(255, 255, 230, .7), transparent),
radial-gradient(ellipse 23% 17% at 38% 55%, #f6d64e 0 72%, #ddb12a 94%, transparent 100%),
radial-gradient(ellipse 21% 15% at 66% 66%, #f0c93e 0 72%, #d6a422 94%, transparent 100%),
radial-gradient(ellipse 30% 9% at 54% 76%, rgba(10, 20, 40, .35), transparent 70%),
repeating-linear-gradient(to right, rgba(255, 255, 255, .16) 0 11px, transparent 11px 22px),
repeating-linear-gradient(to bottom, rgba(255, 255, 255, .16) 0 11px, transparent 11px 22px),
#3b6ea6;
}
.pagedots { position: absolute; left: 0; right: 0; top: 748px; display: flex; justify-content: center; gap: 8px; }
.pagedots i { width: 7px; height: 7px; border-radius: 50%; background: rgba(255, 255, 255, .45); transition: background .2s, width .2s; }
.pagedots i.on { background: #fff; width: 18px; border-radius: 4px; }
/* Quick launch: the home screen dims beside a black page that comes in from the side. */
.qdim { position: absolute; inset: 0; background: #000; opacity: 0; z-index: 8; pointer-events: none; }
.qpage { position: absolute; top: 0; bottom: 0; right: 0; width: 0; background: #000; z-index: 9; pointer-events: none; }
.qpage.is-left { right: auto; left: 0; }
/* The list's backdrop, black over the blurred wallpaper; full-screen folders share it. */
.scrim { position: absolute; inset: 0; background: #000; opacity: 0; z-index: 10; pointer-events: none; }
.ffolder { position: absolute; left: 14px; width: 362px; bottom: 40px; z-index: 11; visibility: hidden; opacity: 0; }
.ffolder__grid { display: grid; grid-template-columns: repeat(4, 90.5px); grid-auto-rows: 104px; }
.ffolder__app { display: flex; flex-direction: column; align-items: center; padding-top: 8px; }
.ffolder__app span { margin-top: 7px; font: 500 12.5px/1.2 var(--ui); color: #fff; text-shadow: 0 1px 4px rgba(0, 0, 0, .55); white-space: nowrap; }
.ffolder__name { height: 24px; text-align: center; font: 600 17px/24px var(--ui); color: #fff; }
.drawer { position: absolute; inset: 0; z-index: 12; visibility: hidden; }
.drawer__in { position: absolute; inset: 0; opacity: 0; -webkit-mask-image: linear-gradient(to bottom, transparent 40px, #000 40px); mask-image: linear-gradient(to bottom, transparent 40px, #000 40px); } /* rows are cut at the status bar */
.list { position: absolute; left: 0; right: 0; top: 40px; padding: 0 56px 0 24px; will-change: transform; }
.search { display: flex; align-items: center; gap: 12px; height: 48px; margin: 8px 0 12px; padding: 0 18px; border-radius: 24px; background: rgba(255, 255, 255, .12); color: rgba(255, 255, 255, .7); font: 400 16px/1 var(--ui); }
.search .gl { width: 22px; height: 22px; color: rgba(255, 255, 255, .7); stroke-width: 2.2; }
.hdr { display: flex; align-items: flex-end; height: 34px; padding: 0 0 4px; font: 700 12px/1 var(--ui); color: rgba(255, 255, 255, .8); text-shadow: 0 2px 6px rgba(0, 0, 0, .45); }
.row { display: flex; align-items: center; gap: 16px; height: 50px; overflow: hidden; border-radius: 12px; transition: background .2s; }
.row .ic { width: 34px; height: 34px; box-shadow: none; }
.row__t { display: flex; flex-direction: column; min-width: 0; flex: 1; }
.row__n { font: 400 15px/1.2 var(--ui); color: #fff; text-shadow: 0 1px 3px rgba(0, 0, 0, .45); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.row__p { margin-top: 2px; font: 400 11.7px/1.2 var(--ui); color: rgba(255, 255, 255, .7); text-shadow: 0 1px 3px rgba(0, 0, 0, .45); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.row.flash { background: rgba(255, 255, 255, .12); }
.row.held { background: rgba(255, 255, 255, .1); }
/* The two settings from the app. */
.is-comfy .row { height: 58px; gap: 18px; }
.is-comfy .row .ic { width: 40px; height: 40px; }
.is-comfy .row__n { font-size: 16px; }
.is-comfy .row__p { font-size: 12.5px; }
.is-comfy .hdr { height: 38px; padding-bottom: 5px; font-size: 13px; }
.is-lefty .list { padding: 0 24px 0 56px; }
.is-lefty .alpha { right: auto; left: 15px; }
/* The wave alphabet: the magnifier and the letters, 20 apart, 30 in from the edge. */
.alpha { position: absolute; right: 15px; top: 314px; width: 30px; height: 360px; display: flex; flex-direction: column; z-index: 3; pointer-events: none; }
.alpha > span { display: grid; place-items: center; height: 20px; flex: none; color: rgba(255, 255, 255, .7); font: 400 12px/1 var(--ui); text-shadow: 0 1px 3px rgba(0, 0, 0, .45); transform-origin: 50% 50%; }
.alpha > span.on { font-weight: 700; color: #fff; }
.alpha__s svg { width: 13px; height: 13px; stroke-width: 2.4; pointer-events: none; }
.sdim { position: absolute; inset: 0; background: #000; opacity: 0; z-index: 2; pointer-events: none; }
.bubble { position: absolute; left: 0; top: 0; width: 40px; height: 40px; display: grid; place-items: center; border-radius: 50%; background: #f1f1f4; color: #17181c; font: 700 22px/1 var(--ui); box-shadow: 0 1px 6px rgba(0, 0, 0, .4); opacity: 0; z-index: 4; pointer-events: none; transform-origin: 50% 50%; }
.bubble svg { width: 22px; height: 22px; fill: none; stroke: currentColor; stroke-width: 2.4; }
.menu { position: absolute; left: 0; top: 0; width: 236px; padding: 6px 0; border-radius: 24px; background: #f1f1f4; color: #17181c; z-index: 20; opacity: 0; visibility: hidden; transform-origin: 30% 0; box-shadow: 0 24px 50px -16px rgba(0, 0, 0, .65); }
.mi { display: flex; align-items: center; gap: 16px; height: 50px; padding: 0 20px; font: 500 16px/1 var(--ui); }
.mi .gl { width: 22px; height: 22px; stroke-width: 1.9; color: #45474f; }
.mi--hide.pick { background: #dcdde3; }
.snack { position: absolute; left: 24px; right: 24px; bottom: 64px; display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 16px 22px; border-radius: 18px; background: #f1f1f4; color: #17181c; font: 500 15px/1.2 var(--ui); z-index: 21; opacity: 0; visibility: hidden; box-shadow: 0 18px 40px -14px rgba(0, 0, 0, .6); }
.snack__undo { all: unset; font: 700 15px/1 var(--ui); color: #1e44c4; cursor: pointer; padding: 4px; }
.sheet { position: absolute; left: 0; right: 0; bottom: 0; padding: 12px 22px 36px; border-radius: 30px 30px 0 0; background: #f1f1f4; color: #17181c; z-index: 22; transform: translateY(105%); box-shadow: 0 -20px 50px -20px rgba(0, 0, 0, .5); }
.sheet__grab { display: block; width: 36px; height: 4px; margin: 0 auto 14px; border-radius: 2px; background: #a7a9b1; }
.sheet h4 { margin: 0 0 10px; font: 600 22px/1.2 var(--ui); }
.sheet__h { margin: 14px 0 8px; font: 600 13.5px/1 var(--ui); color: #55575f; }
.seg { display: flex; border: 1.5px solid #8a8c95; border-radius: 22px; overflow: hidden; }
.seg span { flex: 1; display: grid; place-items: center; height: 40px; font: 500 14px/1 var(--ui); border-left: 1.5px solid #8a8c95; transition: background .2s; }
.seg span:first-child { border-left: 0; }
.seg span.on { background: #dcdde3; font-weight: 700; }
/* The app quick launch opens: a camera, there at once, with no animation, pointed at a desk. */
.app { position: absolute; inset: 0; background: #000; z-index: 25; visibility: hidden; }
.cam__view {
position: absolute; left: 0; right: 0; top: 52px; height: 560px; overflow: hidden;
background: linear-gradient(to bottom, #cdc5b8 0, #b8afa1 58%, #8f6e52 58.2%, #775a41 100%);
}
.cam__view::before { /* the desk's grain */ content: ""; position: absolute; left: 0; right: 0; top: 58%; bottom: 0; background: repeating-linear-gradient(177deg, transparent 0 13px, rgba(0, 0, 0, .07) 13px 15px); }
.cam__book { position: absolute; left: 34px; top: 372px; width: 196px; height: 124px; background: linear-gradient(100deg, #2f4a5c, #284052); clip-path: polygon(12% 0, 100% 7%, 93% 100%, 0 88%); }
.cam__mug { position: absolute; left: 238px; top: 262px; width: 82px; height: 104px; border-radius: 6px 6px 18px 18px; background: linear-gradient(to right, #d6d2c9, #f5f2eb 38%, #e1ddd4); box-shadow: 16px 18px 20px -8px rgba(40, 25, 10, .35); }
.cam__mug::before { /* the rim and the coffee */ content: ""; position: absolute; left: 0; right: 0; top: -9px; height: 18px; border-radius: 50%; background: radial-gradient(ellipse at 50% 60%, #4a2f1e 0 56%, #efebe3 58%); }
.cam__mug::after { /* the handle */ content: ""; position: absolute; right: -27px; top: 22px; width: 34px; height: 46px; border: 8px solid #e3dfd7; border-left: 0; border-radius: 0 24px 24px 0; }
.cam__grid { position: absolute; inset: 0; background: linear-gradient(to right, transparent 33%, rgba(255, 255, 255, .35) 33%, rgba(255, 255, 255, .35) calc(33% + 1px), transparent calc(33% + 1px), transparent 66%, rgba(255, 255, 255, .35) 66%, rgba(255, 255, 255, .35) calc(66% + 1px), transparent calc(66% + 1px)), linear-gradient(to bottom, transparent 33%, rgba(255, 255, 255, .35) 33%, rgba(255, 255, 255, .35) calc(33% + 1px), transparent calc(33% + 1px), transparent 66%, rgba(255, 255, 255, .35) 66%, rgba(255, 255, 255, .35) calc(66% + 1px), transparent calc(66% + 1px)); }
.cam__focus { position: absolute; left: 279px; top: 314px; width: 76px; height: 76px; margin: -38px; border: 2px solid #ffe066; border-radius: 6px; }
.cam__modes { position: absolute; left: 0; right: 0; top: 632px; display: flex; justify-content: center; gap: 26px; font: 600 13px/1 var(--ui); letter-spacing: .08em; text-transform: uppercase; color: #9d9ab8; }
.cam__modes .on { color: #ffd27a; }
.cam__bar { position: absolute; left: 0; right: 0; top: 684px; display: flex; align-items: center; justify-content: space-between; padding: 0 44px; }
.cam__thumb { width: 50px; height: 50px; border-radius: 12px; background: linear-gradient(to bottom, #c9c1b4 56%, #8a6a4f 56%); border: 2px solid #fff; }
.cam__shutter { width: 78px; height: 78px; border-radius: 50%; background: #fff; box-shadow: 0 0 0 5px #000, 0 0 0 9px #fff; transition: transform .12s ease; }
.cam__flip { display: grid; place-items: center; width: 50px; height: 50px; border-radius: 50%; background: #26243a; }
.cam__flip .gl { width: 24px; height: 24px; color: #fff; }
.gbar { position: absolute; left: 50%; bottom: 9px; width: 124px; height: 5px; margin-left: -62px; border-radius: 3px; background: rgba(255, 255, 255, .88); z-index: 40; pointer-events: none; }
.finger {
position: absolute; left: 0; top: 0; width: 50px; height: 50px; margin: -25px 0 0 -25px;
border-radius: 50%;
background: rgba(255, 255, 255, .22);
border: 2px solid rgba(255, 255, 255, .85);
box-shadow: 0 0 0 6px rgba(255, 255, 255, .08), 0 8px 20px rgba(0, 0, 0, .35);
z-index: 50; opacity: 0; pointer-events: none;
}
.finger__ring { position: absolute; inset: -9px; border-radius: 50%; background: conic-gradient(rgba(255, 255, 255, .9) calc(var(--ring, 0) * 1turn), transparent 0); -webkit-mask: radial-gradient(closest-side, transparent 78%, #000 80%); mask: radial-gradient(closest-side, transparent 78%, #000 80%); }
/* Measurement marks, drawn on the phone's screen in its own pixels. */
.marks { position: absolute; inset: 0; width: 100%; height: 100%; z-index: 45; pointer-events: none; overflow: visible; }
.mk line, .mk path, .mk circle { fill: none; stroke: var(--measure); stroke-width: 1.5; stroke-linecap: round; }
.mk .dash { stroke-dasharray: 4 4; }
.mk .area { fill: rgba(25, 223, 248, .16); stroke: none; }
.mk .area--dashed { stroke: var(--measure); stroke-width: 1.5; stroke-dasharray: 4 4; }
.mk__label rect { fill: rgba(0, 0, 0, .72); stroke: none; }
.mk__label text { fill: var(--measure); stroke: none; font: 500 13px var(--mono); } /* the page's technical face, not the phone's */
.fig__item--side .mk .dash, .fig__item--side .mk .area--dashed { stroke-width: 2.2; stroke-dasharray: 6 6; } /* drawn smaller: the lines would thin out at 1.5 */
.fig__item--side .mk__label { display: none; }
/* The playground's alphabet for the keyboard and screen readers: a slider over the letters. */
.strip-a11y { position: absolute; z-index: 2; left: calc((12px + 330px) * var(--s, .5)); top: calc((12px + 298px) * var(--s, .5)); width: calc(60px * var(--s, .5)); height: calc(392px * var(--s, .5)); border-radius: 8px; pointer-events: none; }
.phone-host.is-lefty .strip-a11y { left: calc(12px * var(--s, .5)); }
.strip-a11y:focus-visible { outline: 2px solid var(--measure); outline-offset: 2px; }
.ffolder__app.tap .ic { animation: tapb .3s ease; }
/* The race's grid phone. */
.rgrid { position: absolute; left: 8px; right: 8px; top: 52px; display: grid; grid-template-columns: repeat(5, 1fr); row-gap: 12px; }
.rcell { all: unset; display: flex; flex-direction: column; align-items: center; gap: 5px; cursor: pointer; -webkit-tap-highlight-color: transparent; }
.rcell .ic { width: 50px; height: 50px; }
.rcell__n { max-width: 70px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font: 500 10.5px/1.15 var(--ui); color: #fff; text-shadow: 0 1px 4px rgba(0, 0, 0, .6); }
.rcell.miss .ic, .row.miss { animation: miss .32s ease; }
.rcell.hit .ic { box-shadow: 0 0 0 3px #fff; }
@keyframes miss { 25% { translate: -6px 0; } 75% { translate: 6px 0; } }
/* ---------- responsive ---------- */
@media (max-width: 1199px) {
.hero h1 { font-size: 68px; }
.fig { max-width: 880px; column-gap: 40px; }
}
@media (max-width: 1099px) {
:root { --sec: 128px; }
h2 { font-size: 44px; }
.hero { padding-top: 88px; }
.hero h1 { font-size: 60px; }
.fig { column-gap: clamp(20px, 3.4vw, 36px); row-gap: 24px; }
.story__lead .part__head { grid-column: 1 / -1; }
.story__part > .part__head, .step__text { grid-column: 1 / span 6; }
.story__stage { grid-column: 7 / span 6; }
.story__phones { height: min(calc(100vh - 168px), 640px); height: min(calc(100svh - 168px), 640px); }
.play__text { grid-column: 1 / span 7; }
.play__stage { grid-column: 8 / span 5; }
/* The phones follow their column's width here, so that a tall, narrow window can't push them out of it. */
.play .phone-host { height: auto; width: min(100%, 320px, 37vh); width: min(100%, 320px, 37svh); }
.race { padding: 64px 40px; }
.race__stage { grid-column: 1 / span 5; height: auto; width: min(100%, 300px, 36vh); width: min(100%, 300px, 36svh); }
.race__side { grid-column: 6 / span 7; padding-right: 0; }
.race__side h3 { font-size: 30px; }
.install { padding: 56px; column-gap: 40px; }
.install__main h2 { font-size: 52px; }
.qr__code { width: 176px; height: 176px; }
.things { column-gap: 48px; }
.faq__title { grid-column: 1 / -1; position: static; margin-bottom: 40px; }
.faq__list { grid-column: 1 / -1; }
}
@media (max-width: 899px) {
/* three columns get too narrow to keep the steps' lines even: stack them */
.steps { grid-template-columns: minmax(0, 1fr); gap: 24px; }
.steps p { max-width: 30em; }
}
@media (max-width: 859px) {
/* the two side captions are the same length; held this narrow they both run to three lines, never two and three */
.fig__item--side p { max-width: 11.5em; margin-left: auto; margin-right: auto; }
}
@media (max-width: 699px) {
:root { --pad: 20px; --head: 64px; --sec: 80px; }
body { font-size: 17px; }
h2 { font-size: 34px; line-height: 1.1; letter-spacing: -.025em; }
h3 { font-size: 21px; }
.intro { font-size: 18px; margin-top: 16px; }
.top__hide { display: none; }
.top__brand { font-size: 16px; }
.head .top__brand { min-height: 44px; } /* a finger's worth */
/* What the launcher is, and the download, come first; the drawings follow. */
.hero { padding-top: 48px; }
.hero h1 { font-size: 42px; line-height: 1.06; letter-spacing: -.035em; }
.lede { margin-top: 20px; font-size: 18px; }
.dl { margin-top: 32px; gap: 14px; }
.dl .btn { width: 100%; }
.dl__note { font-size: 15px; }
/* the lineup: the list on a row of its own, the two gestures side by side under it */
.fig { max-width: 440px; grid-template-columns: repeat(2, minmax(0, 1fr)); column-gap: 20px; row-gap: 16px; margin-top: 48px; } /* 440: the two under it never outgrow the list */
.fig__item--main { grid-column: 1 / -1; grid-row: 1; display: block; margin-bottom: 32px; }
.fig__item--main .phone-host { width: min(250px, 66vw); margin: 0 auto; }
.fig__item--main p { max-width: 17em; margin: 20px auto 0; }
.fig__item--side { grid-row: 2 / span 2; }
.fig__item--edge { grid-column: 1; }
.fig__item--quick { grid-column: 2; }
.fig__item p { font-size: 15px; }
.fig__item--side p { max-width: 11em; }
.fig figcaption, .fig noscript { grid-row: 4; }
.fig figcaption { margin-top: 16px; }
/* the story: the phone stays on top, opaque from edge to edge, and takes its own taps: text scrolls under it, never over it.
Its background follows the black band's edges (script.js sets --night-from and --night-to). */
.story__lead .part__head { grid-column: 1 / -1; }
.story { display: block; margin-top: 24px; }
.story [id] { scroll-margin-top: min(52vh, 150vw); scroll-margin-top: min(52svh, 150vw); } /* a jump lands below the phone, not under it */
.story__stage { position: sticky; top: 0; height: min(52vh, 150vw); height: min(52svh, 150vw); z-index: 2; pointer-events: auto; margin: 0 calc(-1 * var(--pad));
background: linear-gradient(to bottom, var(--canvas) 0 var(--night-from, 100%), var(--night) var(--night-from, 100%) var(--night-to, 100%), var(--canvas) var(--night-to, 100%));
box-shadow: 0 1px 0 var(--line); }
.story__phones { height: min(48vh, 140vw); height: min(48svh, 140vw); }
.story__flow { display: block; position: relative; z-index: 1; }
.story__part, .step { display: block; }
.story__part > .part__head { padding-top: 8px; }
.step { min-height: min(64vh, 560px); min-height: min(64svh, 560px); padding: 32px 0 40px; }
.step__text h3 { font-size: 24px; }
.step__text p { font-size: 17px; margin-top: 12px; }
.step__text .note { font-size: 15px; }
.story__night { padding: 64px 0 24px; margin-top: 24px; }
.story.is-live .step:not(.is-active) .step__text { opacity: 1; } /* one chapter's text is on screen at a time here, so none is dimmed */
/* try it */
.play__text, .play__stage, .race__stage, .race__side { grid-column: 1 / -1; }
.controls { margin-top: 32px; }
.tbtn { height: 44px; padding: 0 16px; }
.play__caption { font-size: 17px; margin-top: 32px; }
.howto { font-size: 15px; }
.play__stage { margin-top: 32px; }
.play .phone-host, .race__stage { height: auto; width: min(100%, 258px, 30.5vh); width: min(100%, 258px, 30.5svh); }
.race { margin-top: 80px; padding: 40px 20px 48px; border-radius: var(--r-lg); }
.race__side { order: -1; }
.race__side h3 { font-size: 26px; }
.race__side .btn { width: 100%; }
.race__stage { margin-top: 72px; }
/* smaller things */
.things { grid-template-columns: minmax(0, 1fr); gap: 32px; margin-top: 36px; }
.thing h3 { font-size: 20px; }
.thing p { font-size: 17px; margin-top: 6px; }
/* install: on a phone the code is no use, so it goes */
.install { display: block; padding: 40px 20px; border-radius: var(--r-lg); }
.install__main h2 { font-size: 38px; }
.install__actions { flex-direction: column; align-items: stretch; gap: 10px; margin-top: 32px; text-align: center; }
.install__actions .btn { width: 100%; }
.install__actions .link { padding: 10px 0; } /* a finger's worth */
.qr { display: none; }
.steps { grid-template-columns: minmax(0, 1fr); gap: 24px; margin-top: 40px; padding-top: 32px; }
.steps h3 { font-size: 18px; }
.steps p { font-size: 16px; }
/* questions */
.faq__title { margin-bottom: 24px; }
.faq summary { padding: 22px 44px 22px 0; font-size: 18px; }
.faq summary::before, .faq summary::after { right: 4px; }
.faq__a { padding-right: 0; }
/* footer */
.foot { padding-top: 0; }
.foot__top { grid-template-columns: minmax(0, 1fr); padding-top: 40px; }
.foot__credit { font-size: 15px; }
.foot__end { flex-direction: column; margin-top: 32px; font-size: 15px; }
.foot__end { gap: 2px; }
.foot__end .ghost { width: fit-content; padding: 10px 0; }
}
@media (forced-colors: active) {
.tbtn, .seg-page, .switch__track, .race__overlay, .race, .install { border: 1px solid CanvasText; }
.btn { border: 1px solid currentColor; }
.seg-page button[aria-pressed="true"] { outline: 2px solid Highlight; outline-offset: -2px; }
.switch__track::after, .faq summary::before, .faq summary::after { background: CanvasText; }
.switch[aria-checked="true"] .switch__track { background: Highlight; }
.switch[aria-checked="true"] .switch__track::after { background: HighlightText; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation-duration: .001ms !important; animation-iteration-count: 1 !important; transition-duration: .001ms !important; }
}
/* Printed: dark on white, and, as without JavaScript, the text without the drawings, the playground or the bar. */
@media print {
:root { --canvas: #fff; --surface: #fff; --raised: #fff; --night: #fff; --line: #c4c4c4; --line-strong: #c4c4c4;
--white: #000; --text: #1d1d1f; --muted: #4b4b4d; color-scheme: light; }
.head, .skip, .fig .phone-host, .fig figcaption, .story__stage, #try, .needs-js, .qr { display: none; }
.fig { margin-top: 24px; row-gap: 0; }
.sec, .story__night { padding-top: 48px; padding-bottom: 48px; }
.step { min-height: 0; padding: 16px 0; }
.story__lead .part__head, .story__part > .part__head, .step__text { grid-column: 1 / -1; }
.install { padding: 0; border: 0; }
.btn { box-shadow: none; border: 1px solid var(--line); }
details > :not(summary) { display: block !important; }
h2, h3 { break-after: avoid; }
}
+32 -4
View File
@@ -243,6 +243,7 @@ android {
// Flexera Launcher: debug builds always use the debug key, so the release key in
// keystore.properties signs releases only.
signingConfig signingConfigs.debug
// Flexera Launcher: the app's name, as Android and the app's own screens show it.
resValue("string", "derived_app_name", "Flexera Launcher (Debug)")
manifestPlaceholders.quickstepMinSdk = "0"
@@ -252,6 +253,7 @@ android {
}
release {
// Flexera Launcher: the app's name, as Android and the app's own screens show it.
resValue("string", "derived_app_name", "Flexera Launcher")
minifyEnabled true
shrinkResources true
@@ -282,20 +284,28 @@ android {
minSdk = 26
}
// Flexera Launcher: its own application ids, so it installs beside Lawnchair, never over it.
// The github one must never change: Android updates an installed copy only from an APK with
// the same id, the updater (app.flexera.update.FlexeraUpdater) accepts no other, and
// flexera/release.ps1 starts and checks the release under it.
github {
applicationId 'com.sema.flexeralauncher'
dimension "channel"
// Flexera Launcher: github is the channel that is released, so Android Studio and the
// lint task use it by default. Lawnchair made play the default, and a play build
// switches features off (isPlayStoreFlavor), so it would not test what is released.
isDefault true
}
nightly {
applicationId 'com.sema.flexeralauncher.nightly'
applicationId 'com.sema.flexeralauncher.nightly' // Flexera Launcher: its own, as for github.
dimension "channel"
}
play {
applicationId "com.sema.flexeralauncher.play"
applicationId "com.sema.flexeralauncher.play" // Flexera Launcher: its own, as for github.
dimension "channel"
isDefault true
// Flexera Launcher: not the default channel; github is.
}
configureEach {
@@ -343,7 +353,9 @@ android {
lawnWithQuickstepGithub {
manifest.srcFile "quickstep/AndroidManifest-launcher.xml"
// Flexera Launcher: branding and default overrides. This variant-level source set
// outranks 'lawn' and 'main', so nothing upstream has to be edited.
// outranks 'lawn' and 'main', so nothing upstream has to be edited. Lawnchair's and
// Launcher3's code calls into these folders, so the nightly and play variants below
// get them too; without them those variants do not compile.
res.srcDirs = ['flexera/res']
java.srcDirs = ['flexera/src']
kotlin.directories.add('flexera/src')
@@ -361,10 +373,18 @@ android {
lawnWithQuickstepNightly {
manifest.srcFile "quickstep/AndroidManifest-launcher.xml"
// Flexera Launcher: the same folders as the github variant; see there.
res.srcDirs = ['flexera/res']
java.srcDirs = ['flexera/src']
kotlin.directories.add('flexera/src')
}
lawnWithQuickstepPlay {
manifest.srcFile "quickstep/AndroidManifest-launcher.xml"
// Flexera Launcher: the same folders as the github variant; see there.
res.srcDirs = ['flexera/res']
java.srcDirs = ['flexera/src']
kotlin.directories.add('flexera/src')
}
withQuickstep {
@@ -380,6 +400,7 @@ androidComponents {
onVariants(selector().all()) { variant ->
def channel = variant.productFlavors.last().second
variant.outputs.forEach { output ->
// Flexera Launcher: flexera/release.ps1 looks for the release APK under this name.
output.outputFileName.set("FlexeraLauncher.${output.versionName.get()}.$channel.${variant.buildType}.apk")
}
@@ -494,6 +515,11 @@ dependencies {
implementation libs.kdrag0n.colorkt
implementation libs.coil.compose
implementation libs.xdrop.fuzzywuzzy
// Flexera Launcher: encodes the QR code on the About screen. Nothing else of it is used.
implementation libs.zxing.core
// Flexera Launcher: finds an article's text in its web page, and cleans what the RSS reader
// shows of it (app.flexera.reader.ArticleStore).
implementation libs.jsoup
implementation libs.bundles.opto
implementation libs.androidx.datastore.preferences
@@ -566,6 +592,8 @@ licensee {
allowUrl("https://github.com/patrykmichalik/opto/blob/master/LICENSE")
allowUrl("https://github.com/RikkaApps/HiddenApiRefinePlugin/blob/main/LICENSE")
allowUrl("https://opensource.org/licenses/mit-license.php")
// Flexera Launcher: jsoup's licence page, the MIT licence.
allowUrl("https://jsoup.org/license")
bundleAndroidAsset = true
androidAssetReportPath = 'licenses.json'
+70 -1
View File
@@ -7,9 +7,78 @@
the app's own update check (app.flexera.update.FlexeraUpdater). Lawnchair's online features stay
switched off in code; see app.flexera.FlexeraNetwork.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<!-- Lets the app hand a downloaded update to Android's installer. The owner still confirms each install. -->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<!--
Since Android 17 an app needs this to reach a device on the network the phone itself is on.
The update server can be such a device: at the owner's home its name leads to its address
on the home network. Asked for only when a check for updates is stopped by it (About screen).
-->
<uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" />
<application>
<!--
The picture widget that comes with the launcher. Not exported: only this launcher can
place it, and only this launcher knows how to draw it.
-->
<receiver
android:name="app.flexera.widget.PictureWidgetProvider"
android:exported="false"
android:label="@string/flexera_picture_widget">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/flexera_picture_widget_info" />
</receiver>
<!-- The clock widget that comes with the launcher: the time and the date. -->
<receiver
android:name="app.flexera.widget.ClockWidgetProvider"
android:exported="false"
android:label="@string/flexera_clock_widget">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/flexera_clock_widget_info" />
</receiver>
<!-- The clock widget's options, a sheet over the home screen. -->
<activity
android:name="app.flexera.widget.ClockWidgetConfigActivity"
android:excludeFromRecents="true"
android:exported="false"
android:theme="@style/Theme.Transparent" />
<!-- Opens Android's photo picker for the picture widget; it has no screen of its own. -->
<activity
android:name="app.flexera.widget.PictureWidgetConfigActivity"
android:excludeFromRecents="true"
android:exported="false"
android:theme="@style/Theme.Transparent" />
<!--
The home screen's database. Not exported, so other apps cannot reach it. Launcher3 exports
it for system apps that hold its READ_SETTINGS and WRITE_SETTINGS permissions, but
Lawnchair's manifest removes the definitions of those two permissions, so nothing ties
them to this app's signing key: any app could define them for itself and then read,
change or erase the home screen. The launcher itself never goes through this provider;
it uses the database directly. Only android:exported changes here; the rest of the
declaration is in AndroidManifest-common.xml.
-->
<provider
android:name="com.android.launcher3.LauncherProvider"
android:exported="false"
tools:replace="android:exported" />
</application>
</manifest>
+206 -27
View File
@@ -5,12 +5,15 @@
.DESCRIPTION
One command per release. It
1. writes the new version to flexera/version.properties and commits it,
2. builds the signed release APK, compiling the Kotlin code from scratch,
3. checks that the APK is signed with the release key (not the debug key),
2. builds the signed release APK, compiling the Kotlin code from scratch, and records the
commit it was built from (source edited while it builds counts as uncommitted changes),
3. checks that the APK carries the release certificate, the one every installed copy has,
4. installs the APK on the running Android emulator, starts it and looks for a crash,
5. creates the release "v<version>" in https://git.mariosem.es/msemes/Flexera-Launcher-Releases,
6. attaches the APK to it, and
7. tags the source commit it was built from.
5. creates the release "v<version>" in https://git.mariosem.es/msemes/Flexera-Launcher-Releases
as a draft, which only you can see,
6. attaches the APK to it and then publishes it, and
7. tags the source commit it was built from. A tag of that version already on another
commit stops the script before anything is published, and -BuildOnly warns of it.
Installed copies of the app look at that repository once a day (app.flexera.update.FlexeraUpdater)
and offer the new version. A release that crashes at start would therefore reach the phone on
@@ -34,7 +37,13 @@
-SkipBuild to publish that same file.
.PARAMETER SkipBuild
Use the APK that is already in build\outputs instead of building again.
Use the APK that is already in build\outputs instead of building again. Every build of this
script records, in a file next to the APK, the commit it was built from and the APK's SHA-256,
and step 7 tags that commit. -SkipBuild stops when that record is missing (the APK was built
some other way, or by an older copy of this script) or describes another file (the APK was
built again since), and when the commits since the build change anything but this script and
WEBSITE\: the APK would be published without those changes. An APK built with uncommitted
changes (with -AllowDirty, or edited while it built) is published only with -AllowDirty again.
.PARAMETER NoSmokeTest
Skip step 4. Only for a machine without an emulator; try the APK on a phone yourself first.
@@ -76,6 +85,11 @@ $HomeActivity = "$AppId/app.lawnchair.LawnchairLauncher"
$JavaHome = 'C:\Program Files\Android\Android Studio\jbr'
$Adb = Join-Path $env:LOCALAPPDATA 'Android\Sdk\platform-tools\adb.exe'
$SmokeTestSeconds = 25
# The certificate every release is signed with, as the "certificate SHA-256 digest" that apksigner
# prints. Android installs an update only when it is signed with the same certificate as the copy
# already installed, so an APK signed with any other key, a keystore made anew under the same name
# included, could not update a single installed copy. It is no secret: every published APK carries it.
$ReleaseCertificateDigest = 'c5584f64eae90ba27f9b39dad2baa7ed6f60d248175578acd8cf1f178facfc70'
$Root = Split-Path -Parent $PSScriptRoot
Set-Location $Root
@@ -101,6 +115,9 @@ function Get-ApiClient {
}
function Read-Response($response, [string]$what) {
# A request that got no answer at all (no connection, a time-out) arrives here as nothing:
# Windows PowerShell gives $null for the result of a failed request instead of an error.
if (-not $response) { throw "$what failed: no answer from $Server" }
$text = $response.Content.ReadAsStringAsync().Result
if (-not $response.IsSuccessStatusCode) {
throw "$what failed: HTTP $([int]$response.StatusCode) $text"
@@ -108,6 +125,16 @@ function Read-Response($response, [string]$what) {
if ($text) { return $text | ConvertFrom-Json }
}
function Remove-Draft($release) {
Read-Response ($client.DeleteAsync("$Api/releases/$($release.id)").Result) "Removing the draft $($release.tag_name)" | Out-Null
# Gitea keeps the name of a removed release on record as a tag, even for a draft, which never
# had a git tag. That record goes too.
$response = $client.DeleteAsync("$Api/tags/$($release.tag_name)").Result
if (-not ($response -and ($response.IsSuccessStatusCode -or [int]$response.StatusCode -eq 404))) {
Write-Warning "The draft $($release.tag_name) is gone, but Gitea still keeps its name on record. That does no harm: the next release of that version reuses it."
}
}
# --- 1. Version ----------------------------------------------------------------------------------
Step "1/7 Version $Version"
@@ -155,6 +182,13 @@ if ($current -ne $Version) {
# --- 2. Build ------------------------------------------------------------------------------------
$apk = Join-Path $Root "build\outputs\apk\lawnWithQuickstepGithub\release\FlexeraLauncher.$Version.github.release.apk"
# A file in build\outputs says nothing about the source it came from, so each build records its
# commit next to it, with the APK's SHA-256 to tie the record to that very file. -SkipBuild
# publishes an APK only on that record's word, and step 7 tags the commit it names.
$buildRecord = [IO.Path]::ChangeExtension($apk, '.build.json')
# The files that never go into the APK, as git pathspecs. A commit that changes only these, such
# as a fix to this script between -BuildOnly and -SkipBuild, leaves the APK as current as it was.
$notInApk = @(':(exclude)flexera/release.ps1', ':(exclude)WEBSITE')
if ($SkipBuild) {
Step "2/7 Build skipped"
@@ -163,6 +197,10 @@ if ($SkipBuild) {
if (-not (Test-Path (Join-Path $Root 'keystore.properties'))) {
throw "keystore.properties is missing, so the APK would be signed with the debug key and could not update an installed copy."
}
# Read before Gradle starts, because that is when Gradle takes the commit it builds into the
# app: the About screen shows it after the version number.
$builtCommit = git rev-parse HEAD
$builtDirty = [bool](git status --porcelain -- . $notInApk)
# A release compiles its Kotlin code from scratch. Compiled output reused from an earlier
# build has produced an APK that crashed at start after a preference class had changed
# (NoSuchFieldError: $stable), so nothing compiled earlier is trusted here.
@@ -170,11 +208,65 @@ if ($SkipBuild) {
Get-ChildItem (Join-Path $Root 'build\kotlin') -Directory -Filter "compile${Variant}Kotlin*" -ErrorAction SilentlyContinue |
Remove-Item -Recurse -Force
$env:JAVA_HOME = $JavaHome
cmd /c ".\gradlew.bat assemble$Variant --no-build-cache --console=plain"
# "2>&1" inside cmd: Gradle prints compiler warnings on its error stream. If this script's
# output is piped or sent to a file, PowerShell would otherwise take the first such line
# for an error and stop the build. Only the exit code says whether the build failed.
cmd /c ".\gradlew.bat assemble$Variant --no-build-cache --console=plain 2>&1"
if ($LASTEXITCODE -ne 0) { throw "The build failed." }
}
if (-not (Test-Path $apk)) { throw "Expected the APK at $apk, but it is not there." }
$apkSha256 = (Get-FileHash -Algorithm SHA256 -LiteralPath $apk).Hash
if ($SkipBuild) {
# A record that is missing or cannot be read counts as none.
$record = $null
try { $record = [IO.File]::ReadAllText($buildRecord) | ConvertFrom-Json } catch { }
if (-not $record -or $record.commit -notmatch '^[0-9a-f]{40}$' -or $record.sha256 -ne $apkSha256) {
throw "Nothing records which commit $(Split-Path $apk -Leaf) was built from, or the APK was built again outside this script since. -SkipBuild publishes only an APK that this script built: run it again without -SkipBuild."
}
$builtCommit = $record.commit
$builtDirty = $record.dirty
} else {
# Gradle compiles each file when it gets to it, so an edit made while it builds may be in the
# APK, whole or in part, though no commit has it. The APK then counts as one built with
# uncommitted changes.
$edited = git status --porcelain -- . $notInApk
if ($edited -and -not $builtDirty) {
Write-Warning "The source was changed while the APK was being built, so the APK may hold changes that no commit has:`n$($edited -join "`n")"
$builtDirty = $true
}
}
$changed = git diff --name-only $builtCommit HEAD -- . $notInApk
if ($LASTEXITCODE -ne 0) {
throw "Commit $builtCommit, which the APK was built from, is not in this repository. Build the APK again (run the script without -SkipBuild)."
}
if ($changed) {
throw "The APK was built from commit $builtCommit, but the commits after it change the app, which the APK may not have. Nothing was published; build it again from the current commit (run the script without -SkipBuild).`n$($changed -join "`n")"
}
if (-not $SkipBuild) {
[IO.File]::WriteAllText($buildRecord, ([ordered]@{ commit = $builtCommit; sha256 = $apkSha256; dirty = $builtDirty } | ConvertTo-Json))
}
# Step 1 needs -AllowDirty for any uncommitted edit, the website's included, so the flag says
# nothing about the APK itself. Whether the APK holds uncommitted changes is said here, in the
# run that publishes it too.
if ($builtDirty) {
Write-Warning "Built from commit $builtCommit, but with uncommitted changes: the APK may hold changes that no commit has."
} else {
Write-Host "Built from commit $builtCommit."
}
if ($builtDirty -and -not $AllowDirty -and -not $BuildOnly) {
throw "The APK was built while the source had uncommitted changes, so it matches no commit. Nothing was published. Commit them and build again, or publish this APK as it is with -SkipBuild -AllowDirty."
}
# Step 7 puts the tag v<version> on that commit. A tag of that name already on another commit, left
# from a withdrawn release of this version, would go on marking the wrong source. -BuildOnly
# publishes nothing, so it only warns, in time to remove the tag before the run that publishes.
$tagged = git rev-parse -q --verify "refs/tags/v$Version^{commit}"
if ($tagged -and $tagged -ne $builtCommit) {
$staleTag = "The tag v$Version is already on commit $tagged, but the APK was built from $builtCommit, and the script publishes nothing while that tag is there. If it marks a release that was withdrawn, remove it (git tag -d v$Version, and if it was pushed, git push origin :refs/tags/v$Version too) and run the script again with -SkipBuild."
if ($BuildOnly) { Write-Warning $staleTag } else { throw $staleTag }
}
# --- 3. Signature --------------------------------------------------------------------------------
Step "3/7 Checking the signature"
@@ -187,6 +279,13 @@ $certificate = & $apksigner.FullName verify --print-certs $apk
if ($LASTEXITCODE -ne 0) { throw "The APK's signature does not verify." }
$signer = ($certificate | Where-Object { $_ -match 'certificate DN' }) -join '; '
if ($signer -match 'Android Debug') { throw "The APK is signed with the debug key ($signer). Check keystore.properties." }
# apksigner writes "Signer #1 certificate SHA-256 digest: ..." and, from build-tools 37 on,
# "V2 Signer: certificate SHA-256 digest: ...".
$digests = @($certificate | ForEach-Object { if ($_ -match 'certificate SHA-256 digest: ([0-9a-f]+)') { $Matches[1] } } | Sort-Object -Unique)
if ($digests.Count -ne 1 -or $digests[0] -ne $ReleaseCertificateDigest) {
$certificate | ForEach-Object { Write-Host $_ }
throw "The APK is not signed with the release certificate (SHA-256 $ReleaseCertificateDigest), so it could not update any installed copy. keystore.properties must name the original flexera-release.jks; a keystore made anew cannot sign updates."
}
Write-Host $signer
Write-Host ("APK: {0} ({1:N1} MB)" -f (Split-Path $apk -Leaf), ((Get-Item $apk).Length / 1MB))
@@ -198,8 +297,22 @@ if ($NoSmokeTest) {
} else {
Step "4/7 Starting the APK on the emulator"
$emulator = & $Adb devices | Where-Object { $_ -match '^(emulator-\d+)\s+device$' } |
ForEach-Object { $Matches[1] } | Select-Object -First 1
$emulators = @(& $Adb devices | Where-Object { $_ -match '^(emulator-\d+)\s+device$' } |
ForEach-Object { $Matches[1] })
# Another project's emulator may run beside this one: the APK goes only to the one of this
# project, known by its name, or to the only emulator there is.
$named = @($emulators | Where-Object {
((& $Adb -s $_ emu avd name) | Select-Object -First 1).Trim() -eq 'Flexera_Launcher_A17'
})
if ($named.Count -gt 0) {
$emulator = $named[0]
} elseif ($emulators.Count -eq 1) {
$emulator = $emulators[0]
} elseif ($emulators.Count -gt 1) {
throw "Several emulators are running ($($emulators -join ', ')) and none is Flexera_Launcher_A17, so the APK would go to one that may belong to something else. Start Flexera_Launcher_A17, or close the others, and run this again with -SkipBuild."
} else {
$emulator = $null
}
if (-not $emulator) {
throw "No running emulator found. Start one (emulator.exe -avd Flexera_Launcher_A17) and run this again with -SkipBuild, or pass -NoSmokeTest."
}
@@ -208,6 +321,13 @@ if ($NoSmokeTest) {
if ($LASTEXITCODE -ne 0 -or -not ($install -match 'Success')) {
throw "Could not install the APK on $emulator. If an older build signed with another key is installed there, uninstall it first: adb uninstall $AppId"
}
# When this app is the emulator's home app, Android restarts it the moment the old copy is
# gone, and that first start can die inside Android itself while the files are still being
# swapped (a NullPointerException in ActivityThread.handleBindApplication, with no line of
# this app in it). That is not the new build crashing: let the swap settle, then start
# from a clean slate and judge what happens from there.
Start-Sleep -Seconds 6
& $Adb -s $emulator shell am force-stop $AppId
& $Adb -s $emulator logcat -b crash -c
& $Adb -s $emulator shell am start -n $HomeActivity | Out-Null
Write-Host "Installed on $emulator and started; watching for $SmokeTestSeconds seconds..."
@@ -233,38 +353,97 @@ if ($BuildOnly) {
Step "5/7 Creating release v$Version in $ReleaseRepository"
$body = @{ tag_name = "v$Version"; name = "Flexera Launcher $Version"; body = $Notes; draft = $false; prerelease = $false } | ConvertTo-Json
# The release starts as a draft, which neither the app's update check nor the QR code's address
# sees, and is published in step 6 once both APKs are attached to it. A run that was stopped in
# between (Ctrl+C, a closed window, a lost connection) leaves its draft behind, and the server
# would not take a second release of the same version.
$drafts = Read-Response ($client.GetAsync("$Api/releases?draft=true&limit=50").Result) 'Looking for an unfinished draft'
foreach ($draft in $drafts) {
if ($draft.draft -and $draft.tag_name -eq "v$Version") {
Remove-Draft $draft
Write-Host "Removed the unfinished draft of v$Version that an earlier run left behind."
}
}
# The release is made on the release repository's default branch. Gitea would pick that branch by
# itself, except for a version whose name it still keeps on record, as it does after a draft was
# removed by hand in Gitea: then it takes the branch from this request alone, and publishing a
# release without one fails.
$branch = (Read-Response ($client.GetAsync($Api).Result) 'Reading the release repository').default_branch
$body = @{ tag_name = "v$Version"; target_commitish = $branch; name = "Flexera Launcher $Version"; body = $Notes; draft = $true; prerelease = $false } | ConvertTo-Json
$content = New-Object System.Net.Http.StringContent($body, [Text.Encoding]::UTF8, 'application/json')
$release = Read-Response ($client.PostAsync("$Api/releases", $content).Result) 'Creating the release'
# --- 6. APK --------------------------------------------------------------------------------------
Step "6/7 Uploading the APK"
Step "6/7 Uploading the APK and publishing the release"
$assetName = "FlexeraLauncher-$Version.apk"
$stream = [IO.File]::OpenRead($apk)
# The APK goes up twice. Once under a name with its version, which is what a person looking at
# the release sees and what the app's updater downloads. And once under a name that never
# changes, so that <server>/<repo>/releases/download/latest/FlexeraLauncher.apk always leads to
# the newest APK: the address in the QR code on the app's About screen (FlexeraUpdater.LATEST_APK_URL).
# The versioned one goes first, because the updater takes the first .apk it finds.
$assetNames = @("FlexeraLauncher-$Version.apk", 'FlexeraLauncher.apk')
$uploaded = @()
$publishing = $false
try {
$file = New-Object System.Net.Http.StreamContent($stream)
$file.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse('application/vnd.android.package-archive')
$form = New-Object System.Net.Http.MultipartFormDataContent
$form.Add($file, 'attachment', $assetName)
$asset = Read-Response ($client.PostAsync("$Api/releases/$($release.id)/assets?name=$assetName", $form).Result) 'Uploading the APK'
foreach ($assetName in $assetNames) {
$stream = [IO.File]::OpenRead($apk)
try {
$file = New-Object System.Net.Http.StreamContent($stream)
$file.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse('application/vnd.android.package-archive')
$form = New-Object System.Net.Http.MultipartFormDataContent
$form.Add($file, 'attachment', $assetName)
$uploaded += Read-Response ($client.PostAsync("$Api/releases/$($release.id)/assets?name=$assetName", $form).Result) "Uploading $assetName"
} finally {
$stream.Dispose()
}
}
# Only now, with both APKs attached, does the release become the one that the app's update
# check and the QR code's address find.
$publish = New-Object System.Net.Http.HttpRequestMessage((New-Object System.Net.Http.HttpMethod 'PATCH'), "$Api/releases/$($release.id)")
$publish.Content = New-Object System.Net.Http.StringContent('{"draft": false}', [Text.Encoding]::UTF8, 'application/json')
$publishing = $true
if ((Read-Response ($client.SendAsync($publish).Result) 'Publishing the release').draft) {
throw "Publishing the release failed: the server kept it as a draft."
}
} catch {
# A release without its APK would make every installed copy report a failed check.
$client.DeleteAsync("$Api/releases/$($release.id)").Result | Out-Null
$client.DeleteAsync("$Api/tags/v$Version").Result | Out-Null
throw
} finally {
$stream.Dispose()
# The app does not see the draft, but it would stand in the next run's way. A release whose
# publishing went through with only the answer lost stays, though: it has both APKs.
$failure = $_
$state = $null
try {
$state = Read-Response ($client.GetAsync("$Api/releases/$($release.id)").Result) 'Reading the draft'
if ($state.draft) {
Remove-Draft $state
Write-Host "The draft v$Version was removed again; nothing was published."
} else {
Write-Warning "v$Version was published after all, with both APKs. Only the source tag is missing: git tag -a v$Version -m `"Flexera Launcher $Version`" $builtCommit"
}
} catch {
# Once the request to publish has gone out, a release that cannot be read back may be live.
if ($publishing -and -not $state) {
Write-Warning "Whether v$Version was published could not be checked ($($_.Exception.Message)). If $Api/releases/latest names v$Version, it was, with both APKs, and only the source tag is missing: git tag -a v$Version -m `"Flexera Launcher $Version`" $builtCommit. If not, the next run removes the draft."
} else {
Write-Warning "The draft v$Version could not be removed ($($_.Exception.Message)). Only you can see it, and the next run removes it."
}
}
throw $failure
}
Write-Host "Uploaded: $($asset.browser_download_url)"
$uploaded | ForEach-Object { Write-Host "Uploaded: $($_.browser_download_url)" }
# --- 7. Source tag -------------------------------------------------------------------------------
Step "7/7 Tagging the source"
git tag -a "v$Version" -m "Flexera Launcher $Version"
if ($LASTEXITCODE -ne 0) { Write-Warning "Could not create the tag v$Version (does it exist already?)." }
# The commit the APK was built from, which need not be HEAD: a fix to this script may have been
# committed after it, and the branch may have moved on while the APK went up.
if ($tagged) {
Write-Host "The tag v$Version is already on $builtCommit."
} else {
git tag -a "v$Version" -m "Flexera Launcher $Version" $builtCommit
if ($LASTEXITCODE -ne 0) { Write-Warning "Could not create the tag v$Version. Create it with: git tag -a v$Version -m `"Flexera Launcher $Version`" $builtCommit" }
}
if ($PushSource) {
git push origin HEAD "v$Version"
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- A sun over a hill on a rounded plate: the stand-in for the picture widget's content. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="120dp"
android:height="120dp"
android:viewportWidth="120"
android:viewportHeight="120">
<path
android:fillColor="#FF3D4A70"
android:pathData="M28,0h64a28,28 0,0 1,28 28v64a28,28 0,0 1,-28 28h-64a28,28 0,0 1,-28 -28v-64a28,28 0,0 1,28 -28z" />
<path
android:fillColor="#99FFFFFF"
android:pathData="M84,36m-12,0a12,12 0,1 1,24 0a12,12 0,1 1,-24 0" />
<path
android:fillColor="#40FFFFFF"
android:pathData="M0,120L0,104Q40,52 92,120Z" />
</vector>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Material icon "arrow_back" (Apache 2.0), for the RSS reader's article view. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:autoMirrored="true"
android:tint="#FFFFFF"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFF"
android:pathData="M20,11H7.83l5.59,-5.59L12,4l-8,8 8,8 1.41,-1.41L7.83,13H20v-2z" />
</vector>
+30
View File
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- "Hide app" in an app's long-press menu: an eye with a line through it. Drawn as strokes;
the menu tints it like its other icons. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:tint="#000000"
android:viewportWidth="24"
android:viewportHeight="24">
<!-- The eye's outline, open on the side the line crosses first. -->
<path
android:pathData="M9.9,5.2C10.6,5.07 11.3,5 12,5C16.2,5 19.7,7.6 21.5,12C20.9,13.4 20.1,14.6 19.1,15.6M16.4,17.6C15.1,18.5 13.6,19 12,19C7.8,19 4.3,16.4 2.5,12C3.3,10 4.5,8.4 6,7.2"
android:strokeColor="@android:color/white"
android:strokeWidth="1.8"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<!-- What the line leaves of the pupil. -->
<path
android:pathData="M14.1,14.1C13.56,14.66 12.82,15 12,15C10.34,15 9,13.66 9,12C9,11.18 9.34,10.44 9.9,9.9"
android:strokeColor="@android:color/white"
android:strokeWidth="1.8"
android:strokeLineCap="round"
android:strokeLineJoin="round" />
<!-- The line. -->
<path
android:pathData="M4,4L20,20"
android:strokeColor="@android:color/white"
android:strokeWidth="1.8"
android:strokeLineCap="round" />
</vector>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Material icon "open_in_new" (Apache 2.0), for the RSS reader's article view. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:tint="#FFFFFF"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFF"
android:pathData="M19,19H5V5h7V3H5c-1.11,0 -2,0.9 -2,2v14c0,1.1 0.89,2 2,2h14c1.1,0 2,-0.9 2,-2v-7h-2v7zM14,3v2h3.59l-9.83,9.83 1.41,1.41L19,6.41V10h2V3h-7z" />
</vector>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Material icon "refresh" (Apache 2.0): the RSS reader's refresh button. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:tint="#FFFFFF"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFF"
android:pathData="M17.65,6.35C16.2,4.9 14.21,4 12,4c-4.42,0 -7.99,3.58 -7.99,8s3.57,8 7.99,8c3.73,0 6.84,-2.55 7.73,-6h-2.08c-0.82,2.33 -3.04,4 -5.65,4 -3.31,0 -6,-2.69 -6,-6s2.69,-6 6,-6c1.66,0 3.14,0.69 4.22,1.78L13,11h7V4l-2.35,2.35z" />
</vector>
+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Material icon "rss_feed" (Apache 2.0): the RSS reader's gesture action. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FF000000"
android:pathData="M6.18,17.82m-2.18,0a2.18,2.18 0,1 1,4.36 0a2.18,2.18 0,1 1,-4.36 0" />
<path
android:fillColor="#FF000000"
android:pathData="M4,4.44v2.83c7.03,0 12.73,5.7 12.73,12.73h2.83c0,-8.59 -6.97,-15.56 -15.56,-15.56zM4,10.1v2.83c3.9,0 7.07,3.17 7.07,7.07h2.83c0,-5.47 -4.43,-9.9 -9.9,-9.9z" />
</vector>
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Material icon "share" (Apache 2.0), for the RSS reader's article view. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:tint="#FFFFFF"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFF"
android:pathData="M18,16.08c-0.76,0 -1.44,0.3 -1.96,0.77L8.91,12.7c0.05,-0.23 0.09,-0.46 0.09,-0.7s-0.04,-0.47 -0.09,-0.7l7.05,-4.11c0.54,0.5 1.25,0.81 2.04,0.81 1.66,0 3,-1.34 3,-3s-1.34,-3 -3,-3 -3,1.34 -3,3c0,0.24 0.04,0.47 0.09,0.7L8.04,9.81C7.5,9.31 6.79,9 6,9c-1.66,0 -3,1.34 -3,3s1.34,3 3,3c0.79,0 1.5,-0.31 2.04,-0.81l7.12,4.16c-0.05,0.21 -0.08,0.43 -0.08,0.65 0,1.61 1.31,2.92 2.92,2.92 1.61,0 2.92,-1.31 2.92,-2.92s-1.31,-2.92 -2.92,-2.92z" />
</vector>
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Material icon "tune" (Apache 2.0): the RSS reader's button for its feeds and settings. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:tint="#FFFFFF"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFF"
android:pathData="M3,17v2h6v-2H3zM3,5v2h10V5H3zM13,21v-2h8v-2h-8v-2h-2v6h2zM7,9v2H3v2h4v2h2V9H7zM21,13v-2H11v2h10zM15,9h2V7h4V5h-4V3h-2v6z" />
</vector>
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
What Android is told the clock widget looks like before it has anything to show: a plain
clock that keeps time by itself. Flexera Launcher never shows it; it draws the widget itself
(app.flexera.widget.ClockWidgetView).
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="vertical"
android:paddingStart="12dp"
android:paddingEnd="12dp">
<TextClock
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-light"
android:format12Hour="h:mm"
android:format24Hour="H:mm"
android:textColor="@android:color/white"
android:textSize="48sp" />
<TextClock
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:format12Hour="EEEE, d MMMM"
android:format24Hour="EEEE, d MMMM"
android:textColor="@android:color/white"
android:textSize="14sp" />
</LinearLayout>
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
What Android is told the picture widget looks like before it has anything to show. Flexera
Launcher never shows it: it draws the widget itself (app.flexera.widget.PictureWidgetView).
-->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:importantForAccessibility="no"
android:scaleType="fitCenter"
android:src="@drawable/flexera_picture_widget_sample" />
</FrameLayout>
+65 -22
View File
@@ -1,11 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Drawer list (PRD AD-2, AD-3). Rows are sized for thumb taps; 48dp is Android's minimum target. -->
<dimen name="flexera_drawer_row_height">64dp</dimen>
<!-- Smaller than a home-screen icon, so rows have air between them. -->
<dimen name="flexera_drawer_row_icon_size">46dp</dimen>
<dimen name="flexera_drawer_row_icon_gap">20dp</dimen>
<dimen name="flexera_drawer_row_text_size">17sp</dimen>
<!-- Drawer list (PRD AD-2, AD-3). A compact list, at the owner's request: more apps within a
thumb's reach. The row stays just above 48dp, Android's minimum for a tap target.
(First version: 64dp rows, 46dp icons, 17sp names.) -->
<dimen name="flexera_drawer_row_height">50dp</dimen>
<!-- Well under a home-screen icon, so rows have air between them. -->
<dimen name="flexera_drawer_row_icon_size">34dp</dimen>
<dimen name="flexera_drawer_row_icon_gap">16dp</dimen>
<dimen name="flexera_drawer_row_text_size">15sp</dimen>
<!-- The "comfy" row size the owner can choose instead (Settings, App drawer): a little
larger all round, between compact and the first version. -->
<dimen name="flexera_drawer_row_height_comfy">58dp</dimen>
<dimen name="flexera_drawer_row_icon_size_comfy">40dp</dimen>
<dimen name="flexera_drawer_row_icon_gap_comfy">18dp</dimen>
<dimen name="flexera_drawer_row_text_size_comfy">16sp</dimen>
<!-- Row padding on the edge without the wave alphabet. The search bar lines up with it. -->
<dimen name="flexera_drawer_row_padding_start">24dp</dimen>
<!-- Row padding on the wave alphabet's edge, which is the end edge unless the owner moves it
@@ -13,29 +21,64 @@
<dimen name="flexera_drawer_row_padding_end">56dp</dimen>
<!-- Wave alphabet (PRD AD-4 to AD-6). -->
<!-- How wide a band along the edge starts a scrub when touched. -->
<dimen name="flexera_wave_touch_width">40dp</dimen>
<!-- Where the letters rest, measured from the edge. -->
<dimen name="flexera_wave_edge_inset">16dp</dimen>
<!-- How wide a band along the edge starts a scrub when touched in the open drawer. -->
<dimen name="flexera_wave_touch_width">60dp</dimen>
<!-- The same band on the home screen, where nothing shows it: narrower, so that fewer
swipes that only pass near the edge are taken for a scrub (PRD AD-10). -->
<dimen name="flexera_wave_home_touch_width">40dp</dimen>
<!-- Where the letters rest, measured from the edge. Inward of the strip of edge where
Android starts its Back swipe (about 24dp), so a thumb on the letters is not on it.
(First version: 16dp, with the whole edge reserved, which left no Back swipe.) -->
<dimen name="flexera_wave_edge_inset">30dp</dimen>
<dimen name="flexera_wave_letter_size">12sp</dimen>
<!-- Letters never sit further apart than this, however few there are. -->
<dimen name="flexera_wave_max_spacing">30dp</dimen>
<!-- Letters never sit further apart than this, however few there are. Close together, a
little closer than Niagara Launcher's, so a whole alphabet is about 83 mm tall and fits
the stretch of edge a thumb covers without shifting the grip. (First version: 30dp,
which spread the alphabet over the whole edge.) -->
<dimen name="flexera_wave_max_spacing">20dp</dimen>
<!-- The stretch of edge kept for the alphabet is as tall as 26 letters and sits low: its end
this far above the navigation bar (on top of the vertical margin). The letters that
exist are centred in it. -->
<dimen name="flexera_wave_bottom_offset">40dp</dimen>
<dimen name="flexera_wave_vertical_margin">16dp</dimen>
<!-- How far before the finger the wave's peak sits, so the thumb never covers the letter. -->
<dimen name="flexera_wave_finger_gap">52dp</dimen>
<!-- How far beyond the finger the wave's peak sits, so the thumb never covers the selected
letter. A thumb hides about 11 mm (70dp) to each side of the point it touches; the
letter's centre has to clear that by its own half width and a margin. At 52dp, the
first value, the letter sat under the thumb. -->
<dimen name="flexera_wave_finger_gap">104dp</dimen>
<!-- The smallest bulge, used when the finger is right on the edge. -->
<dimen name="flexera_wave_min_reach">60dp</dimen>
<!-- How far up and down the edge the bulge spreads. -->
<dimen name="flexera_wave_width">56dp</dimen>
<dimen name="flexera_wave_min_reach">96dp</dimen>
<!-- How far up and down the edge the bulge spreads, at the least: wide, so that about five
letters on each side of the finger ride the wave and curve around the thumb, as in
Niagara Launcher. A taller wave is wider (WaveAlphabetView.WAVE_WIDTH_SHARE_OF_REACH). -->
<dimen name="flexera_wave_width">104dp</dimen>
<!-- The wave's peak never comes closer than this to the opposite edge of the screen. It
leaves room for the bubble beyond the peak. -->
<dimen name="flexera_wave_far_margin">66dp</dimen>
<!-- The bubble with the selected letter: its size, how far beyond the wave's peak its
centre sits, and how close it may come to a screen edge. -->
<dimen name="flexera_wave_bubble_radius">20dp</dimen>
<dimen name="flexera_wave_bubble_gap">38dp</dimen>
<dimen name="flexera_wave_bubble_text_size">22sp</dimen>
<dimen name="flexera_wave_bubble_edge_margin">6dp</dimen>
<dimen name="flexera_wave_bubble_shadow_radius">6dp</dimen>
<!-- Swipe up and hold (PRD AD-17): a pause only counts once the swipe has travelled this far. -->
<dimen name="flexera_hold_min_swipe">72dp</dimen>
<!-- Swipe up and hold (PRD AD-17): a pause only counts once the swipe has travelled this far.
Enough to tell a hold from a hesitant start, short enough that a small swipe counts. -->
<dimen name="flexera_hold_min_swipe">32dp</dimen>
<!-- Soft shadow behind white drawer text, for readability over light wallpaper. -->
<dimen name="flexera_drawer_text_shadow_radius">3dp</dimen>
<dimen name="flexera_drawer_text_shadow_dy">1dp</dimen>
<dimen name="flexera_drawer_header_height">44dp</dimen>
<dimen name="flexera_drawer_header_padding_bottom">6dp</dimen>
<dimen name="flexera_drawer_header_text_size">14sp</dimen>
<!-- Picture widget: the words on a widget that has no pictures, and the room beside them. -->
<dimen name="flexera_picture_widget_hint_text_size">13sp</dimen>
<dimen name="flexera_picture_widget_hint_margin">10dp</dimen>
<dimen name="flexera_drawer_header_height">34dp</dimen>
<dimen name="flexera_drawer_header_padding_bottom">4dp</dimen>
<dimen name="flexera_drawer_header_text_size">12sp</dimen>
<dimen name="flexera_drawer_header_height_comfy">38dp</dimen>
<dimen name="flexera_drawer_header_padding_bottom_comfy">5dp</dimen>
<dimen name="flexera_drawer_header_text_size_comfy">13sp</dimen>
</resources>
+4
View File
@@ -2,4 +2,8 @@
<resources>
<!-- The wave alphabet view inside the drawer (app.flexera.drawer.WaveAlphabetView). -->
<item name="flexera_wave_alphabet" type="id" />
<!-- View tag that marks an app row of the drawer list (FlexeraDrawer.styleAppRow). -->
<item name="flexera_drawer_row" type="id" />
<!-- View tag on a drawer row: set while the row shows a notification preview under the app name. -->
<item name="flexera_notification_preview" type="id" />
</resources>
+284 -11
View File
@@ -27,9 +27,64 @@
<string name="flexera_about_built_on_title">Lawnchair</string>
<string name="flexera_about_built_on_body">Flexera Launcher is a modified version of Lawnchair, the open-source launcher made by the Lawnchair team. Lawnchair is itself based on Launcher3 from the Android Open Source Project.</string>
<string name="flexera_about_lawnchair_source">Lawnchair source code</string>
<!-- Import of a Smart Launcher backup (app.flexera.backup) -->
<string name="flexera_import_smart_launcher">Import from Smart Launcher</string>
<string name="flexera_import_smart_launcher_description">Home screens, folders and widgets from a Smart Launcher backup file (.slbk)</string>
<string name="flexera_import_found">In this backup</string>
<string name="flexera_import_screens">Home screens</string>
<string name="flexera_import_screens_value">%1$d, on a grid of %2$d by %3$d</string>
<string name="flexera_import_apps">Apps on the home screens</string>
<string name="flexera_import_folders">Folders</string>
<plurals name="flexera_import_folders_value">
<item quantity="one">%1$d, holding %2$d app</item>
<item quantity="other">%1$d, holding %2$d apps</item>
</plurals>
<string name="flexera_import_widgets">Widgets</string>
<string name="flexera_import_widgets_value">%1$d. Each arrives in its place as “tap to set up”: Android asks you to allow it again, and its own settings start fresh.</string>
<string name="flexera_import_photo_widgets">Photo widgets</string>
<plurals name="flexera_import_photo_widgets_value">
<item quantity="one">%1$d. It becomes Flexera Launcher\'s picture widget and keeps its photo. Tap it once after the import.</item>
<item quantity="other">%1$d. They become Flexera Launcher\'s picture widgets and keep their photos. Tap each once after the import.</item>
</plurals>
<string name="flexera_import_left_out">Left out</string>
<string name="flexera_import_own_widgets">Other widgets of Smart Launcher itself</string>
<plurals name="flexera_import_own_widgets_value">
<item quantity="one">%1$d. It exists only inside Smart Launcher, so its place stays empty.</item>
<item quantity="other">%1$d. They exist only inside Smart Launcher, so their places stay empty.</item>
</plurals>
<string name="flexera_import_skipped">Other items</string>
<plurals name="flexera_import_skipped_value">
<item quantity="one">%1$d that this launcher cannot show or place</item>
<item quantity="other">%1$d that this launcher cannot show or place</item>
</plurals>
<string name="flexera_import_effect">What importing does</string>
<string name="flexera_import_effect_title">Replaces your current home screens</string>
<string name="flexera_import_effect_body">The home screens you have now are removed. The grid takes the size it has in the backup and the dock is switched off, because Smart Launcher has none; both can be changed again in Settings. Icons of apps that are not installed on this phone are dropped. Make a backup first if you want to be able to go back.</string>
<!-- Left out: what sits where At a Glance goes while it is shown on the home screen -->
<string name="flexera_import_glance">In the top row of the first home screen</string>
<plurals name="flexera_import_glance_value">
<item quantity="one">%1$d. At a Glance takes this row. To keep it, switch off Show on home screen (Settings, At a Glance) before importing.</item>
<item quantity="other">%1$d. At a Glance takes this row. To keep them, switch off Show on home screen (Settings, At a Glance) before importing.</item>
</plurals>
<!-- Shown only when the import changes this setting -->
<string name="flexera_import_labels">Labels on the home screen</string>
<string name="flexera_import_labels_on">Switched on, as in the backup. This can be changed again in Settings.</string>
<string name="flexera_import_labels_off">Switched off, as in the backup. This can be changed again in Settings.</string>
<!-- Shown in place of what importing does when nothing in the backup can be placed -->
<string name="flexera_import_nothing_title">Nothing to import</string>
<string name="flexera_import_nothing_body">None of the items in this backup can be placed on the home screens here, so importing it would only empty yours.</string>
<string name="flexera_import_action">Import</string>
<!-- Shown on the Import button while the import runs -->
<string name="flexera_import_importing">Importing…</string>
<string name="flexera_import_done">Imported</string>
<string name="flexera_import_failed">The import failed</string>
<string name="flexera_import_unreadable">This is not a Smart Launcher backup that can be read</string>
<string name="flexera_about_share">Share</string>
<string name="flexera_about_share_title">Scan to get Flexera Launcher</string>
<string name="flexera_about_share_qr_description">QR code that downloads the latest version</string>
<string name="flexera_about_privacy">Privacy</string>
<string name="flexera_about_privacy_title">Nothing about you leaves your phone</string>
<string name="flexera_about_privacy_body">Flexera Launcher goes online for one thing: asking its release page whether a newer version exists, about once a day, and downloading that version when you ask. It sends nothing about you, your apps or your phone.</string>
<string name="flexera_about_privacy_title">What goes online</string>
<string name="flexera_about_privacy_body">Flexera Launcher goes online for two things. It asks its release page whether a newer version exists, about once a day, and downloads that version when you ask. And if you pick a place for the weather on a clock widget, it asks Open-Meteo, a weather service, for the weather there. Looking a place up sends the name you type and your phone\'s language; asking for its weather sends the place, to about a kilometre, and whether you use Celsius or Fahrenheit. Nothing else about you, your apps or your phone leaves it.</string>
<!-- Lawnchair's wording promised web results and grid settings that this app does not have -->
<string name="all_apps_device_search_hint">Search apps and more</string>
@@ -39,34 +94,182 @@
<!-- The drawer's wave alphabet -->
<!-- Read by screen readers as the name of the alphabet strip, followed by the current letter -->
<string name="flexera_alphabet_description">Alphabet</string>
<string name="flexera_row_size">Row size</string>
<string name="flexera_row_size_compact">Compact</string>
<string name="flexera_row_size_comfy">Comfy</string>
<string name="flexera_alphabet_search">Search</string>
<!-- App drawer settings (app.flexera.ui.FlexeraDrawerSettings) -->
<string name="flexera_notification_previews">Notification previews</string>
<string name="flexera_notification_previews_description">Show an app\'s latest notification under its name in the app list. Works when notification dots are on (Settings, General).</string>
<!-- Read by screen readers for an app in the app list that shows its latest notification under its name. %1$s is the app's name with how many notifications it has, such as "Messages has 1 notification"; %2$s is the notification -->
<string name="flexera_notification_preview_description">%1$s. %2$s</string>
<string name="flexera_alphabet_heading">Alphabet</string>
<string name="flexera_alphabet_on_left">Alphabet on the left edge</string>
<string name="flexera_alphabet_on_left_description">For left-handed use. The letters normally sit on the right edge.</string>
<string name="flexera_scrub_from_home">Scrub from the home screen</string>
<string name="flexera_scrub_from_home_description">Slide up or down along the alphabet\'s edge of the home screen to open the app list at a letter. Swipe up and hold does the same from anywhere.</string>
<!-- Quick launch: a swipe on past the first or the last home screen page (app.flexera.home.QuickLaunch) -->
<string name="flexera_hide_app">Hide app</string>
<!-- Shown after an app was hidden from the app list. %1$s is the app's name -->
<string name="flexera_app_hidden">%1$s is hidden</string>
<string name="flexera_folder_blur">Blur behind open folders</string>
<!-- Home screen settings, Widgets: every widget's edges meet the edges of the icons -->
<string name="flexera_align_widgets">Line up with icons</string>
<string name="flexera_align_widgets_description">The edges of every widget meet the edges of the icons above, below and beside it</string>
<string name="flexera_folder_blur_description">Blurs the home screen while a folder is open</string>
<!-- Folder settings: folders open over the whole screen, apps at the bottom (app.flexera.home.FullScreenFolders) -->
<string name="flexera_full_screen_folders">Full screen folders</string>
<string name="flexera_full_screen_folders_description">Opens folders over the whole screen, with their apps at the bottom, within reach of your thumb</string>
<!-- Home screen settings, Layout: the space at the screen's sides, above the first row and below the last (app.flexera.home.HomeMargins) -->
<string name="flexera_home_margins">Margins</string>
<string name="flexera_home_side_margins">Side margins</string>
<string name="flexera_home_top_margin">Top margin</string>
<string name="flexera_home_bottom_margin">Bottom margin</string>
<!-- Under the margin sliders when the grid cannot lay out as much as they ask for -->
<string name="flexera_home_margins_limited">The grid leaves no more room: larger margins would cut off labels or make icons overlap. Fewer rows or columns leave more room.</string>
<!-- Lawnchair's "Home screen grid", the settings page with the preview, which has the margins as well since 1.0.6 -->
<string name="home_screen_grid">Grid and margins</string>
<string name="flexera_quick_launch">Quick launch</string>
<string name="flexera_quick_launch_description">Swipe on from the first or the last home screen page, as if there were one more, to open an app or do something else. Has no effect while Infinite scrolling is on.</string>
<string name="flexera_quick_launch_first_page">Swipe past the first page</string>
<string name="flexera_quick_launch_last_page">Swipe past the last page</string>
<!-- Shown when a swipe past the first or the last page is to open an app that can no longer be opened. %1$s is the app's name -->
<string name="flexera_quick_launch_app_missing">%1$s isn\'t installed or is disabled</string>
<!-- The clock widget that comes with the launcher (app.flexera.widget) -->
<!-- Its name in the list of widgets -->
<string name="flexera_clock_widget">Clock</string>
<string name="flexera_clock_widget_description">The time and the date, lined up with your icons</string>
<!-- The clock widget's options, reached from its edit button -->
<string name="flexera_clock_widget_alignment">Alignment</string>
<string name="flexera_clock_widget_left">Left</string>
<string name="flexera_clock_widget_center">Center</string>
<string name="flexera_clock_widget_right">Right</string>
<string name="flexera_clock_widget_size">Size</string>
<string name="flexera_clock_widget_small">Small</string>
<string name="flexera_clock_widget_large">Large</string>
<!-- What a screen reader says for the clock size slider. %1$d is the figures' height as a percentage of an app icon's -->
<string name="flexera_clock_widget_size_value">%1$d%% of an icon\'s height</string>
<!-- Under the size slider when the widget is too small for the largest clock -->
<string name="flexera_clock_widget_size_limit">For a larger clock, make the widget bigger.</string>
<string name="flexera_clock_widget_weight">Weight</string>
<!-- The font of the clock's figures. Default is the phone's own font; Flex, Narrow and Wide are Google Sans Flex at three widths -->
<string name="flexera_clock_widget_font">Font</string>
<string name="flexera_clock_widget_font_default">Default</string>
<string name="flexera_clock_widget_font_flex">Flex</string>
<string name="flexera_clock_widget_font_narrow">Narrow</string>
<string name="flexera_clock_widget_font_wide">Wide</string>
<string name="flexera_clock_widget_font_serif">Serif</string>
<string name="flexera_clock_widget_font_mono">Mono</string>
<string name="flexera_clock_widget_thin">Thin</string>
<string name="flexera_clock_widget_light">Light</string>
<string name="flexera_clock_widget_regular">Regular</string>
<string name="flexera_clock_widget_bold">Bold</string>
<string name="flexera_clock_widget_weather">Weather</string>
<string name="flexera_clock_widget_weather_off">Off. Look a place up to show its weather under the date.</string>
<!-- %1$s is a place, such as "Berlin, State of Berlin, Germany" -->
<string name="flexera_clock_widget_weather_on">Showing the weather in %1$s</string>
<string name="flexera_clock_widget_weather_place">Town or city</string>
<string name="flexera_clock_widget_weather_search">Search</string>
<string name="flexera_clock_widget_weather_nothing">No place of that name was found</string>
<string name="flexera_clock_widget_weather_failed">The weather service could not be reached. Check the connection and try again.</string>
<!-- Shown above the places a search found, which are listed under it to pick from. %1$d is how many are listed: the weather service gives only the likeliest few, so a common name can have more -->
<plurals name="flexera_clock_widget_weather_found">
<item quantity="one">%1$d place of that name</item>
<item quantity="other">%1$d places of that name, the likeliest first</item>
</plurals>
<string name="flexera_clock_widget_weather_remove">Turn weather off</string>
<!-- How the picture of the sky before the weather line is drawn: in colour, in the colour of the text, or not at all -->
<string name="flexera_clock_widget_weather_icon">Weather icon</string>
<string name="flexera_clock_widget_icon_color">Color</string>
<string name="flexera_clock_widget_icon_plain">Plain</string>
<string name="flexera_clock_widget_icon_none">None</string>
<!-- Which app a tap on the clock widget opens: one choice for the time and date, one for the weather line -->
<string name="flexera_clock_widget_tap">Tap to open</string>
<string name="flexera_clock_widget_tap_clock">Time and date</string>
<string name="flexera_clock_widget_tap_weather">Weather</string>
<string name="flexera_clock_widget_tap_clock_default">Your clock app</string>
<string name="flexera_clock_widget_tap_weather_default">The same as the time and date</string>
<!-- Under a tap choice whose app has been uninstalled since it was picked. %1$s is the app's name -->
<string name="flexera_clock_widget_tap_missing">%1$s, not installed</string>
<string name="flexera_clock_widget_tap_reset">Reset</string>
<!-- What a screen reader says for the Reset button of a tap choice. %1$s is the choice, such as "Time and date" -->
<string name="flexera_clock_widget_tap_reset_description">Reset %1$s</string>
<!-- What a screen reader offers for a double tap on the clock widget. %1$s is an app's name -->
<string name="flexera_clock_widget_open">Open %1$s</string>
<string name="flexera_clock_widget_open_clock">Open the clock app</string>
<string name="flexera_clock_widget_weather_source">Weather data by Open-Meteo.com. A search sends it the name you type and your phone\'s language. Then the launcher asks it about the place you pick, in Celsius or Fahrenheit as your phone is set, about once an hour while the clock is in view. Nothing else is sent.</string>
<!-- The clock widget's weather line. %1$d is the temperature, %2$s a word for the sky, such as "Overcast" -->
<string name="flexera_weather_line">%1$d° · %2$s</string>
<string name="flexera_weather_clear">Clear</string>
<string name="flexera_weather_mostly_clear">Mostly clear</string>
<string name="flexera_weather_partly_cloudy">Partly cloudy</string>
<string name="flexera_weather_overcast">Overcast</string>
<string name="flexera_weather_fog">Fog</string>
<string name="flexera_weather_drizzle">Drizzle</string>
<string name="flexera_weather_rain">Rain</string>
<string name="flexera_weather_freezing_rain">Freezing rain</string>
<string name="flexera_weather_snow">Snow</string>
<string name="flexera_weather_showers">Showers</string>
<string name="flexera_weather_snow_showers">Snow showers</string>
<string name="flexera_weather_thunderstorm">Thunderstorm</string>
<!-- The picture widget that comes with the launcher (app.flexera.widget) -->
<!-- Its name in the list of widgets -->
<string name="flexera_picture_widget">Pictures</string>
<string name="flexera_picture_widget_description">One picture, or several that take turns every 10 seconds</string>
<!-- Shown on a picture widget that has no pictures -->
<string name="flexera_picture_widget_empty">Tap to choose pictures</string>
<!-- Read by screen readers. %1$d is the picture being shown, %2$d is how many there are -->
<string name="flexera_picture_widget_position">Picture %1$d of %2$d</string>
<string name="flexera_picture_widget_unreadable">None of the chosen pictures could be read</string>
<!-- Updates section of the About screen (app.flexera.update.FlexeraUpdater) -->
<string name="flexera_update_heading">Updates</string>
<!-- Button -->
<string name="flexera_update_check">Check for updates</string>
<string name="flexera_update_check_idle">Flexera Launcher also checks on its own, once a day</string>
<!-- Shown on the button while the check runs -->
<string name="flexera_update_checking">Checking for updates…</string>
<string name="flexera_update_up_to_date">You have the latest version</string>
<string name="flexera_update_check_failed">Couldn\'t reach the update server. Check your connection, then tap to try again.</string>
<string name="flexera_update_failed_title">The check for updates didn\'t work</string>
<!-- Button -->
<string name="flexera_update_try_again">Try again</string>
<!-- Button that asks Android for local network access -->
<string name="flexera_update_allow_local_network">Allow access</string>
<!-- Why a check for updates failed. %1$s is the update server's name, such as git.example.org -->
<string name="flexera_update_failed_no_permission">Android does not let Flexera Launcher use the network on this phone. Allow it in the phone\'s settings for this app, under Permissions, Network, then try again.</string>
<string name="flexera_update_failed_not_found">This phone could not find %1$s. Check the connection and any VPN or private DNS, then try again.</string>
<string name="flexera_update_failed_local_network">%1$s is on the same network as this phone, and Android lets an app reach devices there only with your permission, which it calls Nearby devices. Once you allow it, the check runs again.</string>
<string name="flexera_update_failed_no_answer">%1$s did not answer. Check the connection and any VPN, then try again.</string>
<string name="flexera_update_failed_not_secure">A secure connection to %1$s could not be made. Check the phone\'s date and time and any VPN, then try again.</string>
<string name="flexera_update_failed_server_error">%1$s answered with an error. Try again later.</string>
<string name="flexera_update_failed_bad_answer">The answer from %1$s could not be read. Try again later.</string>
<!-- %1$s is the error in the system\'s own words, for whoever looks for the cause -->
<string name="flexera_update_failed_detail">Details: %1$s</string>
<!-- %1$s is a version number such as 0.2.0 -->
<string name="flexera_update_download">Download version %1$s</string>
<string name="flexera_update_available">Version %1$s is available</string>
<!-- Button. The download is followed by the installation without another tap -->
<string name="flexera_update_download">Download and install</string>
<!-- %1$s is a file size such as 24 MB -->
<string name="flexera_update_download_size">A newer version is available (%1$s)</string>
<string name="flexera_update_download_no_size">A newer version is available</string>
<string name="flexera_update_download_failed">The download didn\'t finish. Tap to try again.</string>
<string name="flexera_update_wrong_file">The downloaded file isn\'t a newer Flexera Launcher, so it was removed. Tap to try again.</string>
<string name="flexera_update_download_size">%1$s download. The installation starts as soon as it\'s done.</string>
<string name="flexera_update_download_no_size">The installation starts as soon as the download is done.</string>
<string name="flexera_update_download_failed">The download didn\'t finish.</string>
<!-- Why a download failed, shown with the button that asks Android for local network access. %1$s is the update server's name, such as git.example.org -->
<string name="flexera_update_download_failed_local_network">%1$s is on the same network as this phone, and Android lets an app reach devices there only with your permission, which it calls Nearby devices. Once you allow it, the download starts again.</string>
<string name="flexera_update_wrong_file">The downloaded file isn\'t a newer Flexera Launcher, so it was removed.</string>
<!-- %1$s is a version number such as 0.2.0 -->
<string name="flexera_update_downloading">Downloading version %1$s</string>
<!-- %1$d is a percentage from 0 to 100 -->
<string name="flexera_update_progress">%1$d%%</string>
<string name="flexera_update_progress">%1$d%%. The installation starts as soon as it\'s done.</string>
<!-- Shown on the button while the download runs -->
<string name="flexera_update_downloading_button">Downloading…</string>
<!-- %1$s is a version number such as 0.2.0 -->
<string name="flexera_update_install">Install version %1$s</string>
<string name="flexera_update_install_hint">Downloaded and ready. If Android asks, allow Flexera Launcher to install apps, then tap here again.</string>
<string name="flexera_update_ready">Version %1$s is ready to install</string>
<!-- Button -->
<string name="flexera_update_install">Install now</string>
<string name="flexera_update_install_hint">If Android asks, allow Flexera Launcher to install apps. The installation then carries on by itself.</string>
<string name="flexera_update_whats_new">What\'s new</string>
<string name="flexera_update_notify">Notify me about new versions</string>
<string name="flexera_update_notify_hint">Notifications are off, so a new version shows up only on this screen</string>
@@ -77,4 +280,74 @@
<!-- %1$s is a version number such as 0.2.0 -->
<string name="flexera_update_notification_title">Flexera Launcher %1$s is available</string>
<string name="flexera_update_notification_text">Tap to download and install</string>
<!-- The RSS reader: a page of the owner's feeds that a gesture brings in (app.flexera.reader) -->
<string name="flexera_rss_reader">RSS reader</string>
<!-- The gesture action that brings the reader in, in the lists of gesture actions -->
<string name="flexera_gesture_open_rss_reader">Open RSS reader</string>
<!-- The reader page's heading -->
<string name="flexera_rss_page_title">Feeds</string>
<!-- Under the heading. %1$s says how long ago, such as "5 min. ago" -->
<string name="flexera_rss_updated">Updated %1$s</string>
<string name="flexera_rss_just_updated">Just updated</string>
<string name="flexera_rss_updating">Updating…</string>
<!-- A post's age when less than a minute -->
<string name="flexera_rss_just_now">Just now</string>
<plurals name="flexera_rss_failed_feeds">
<item quantity="one">%d feed couldn\'t be loaded</item>
<item quantity="other">%d feeds couldn\'t be loaded</item>
</plurals>
<string name="flexera_rss_refresh">Refresh</string>
<string name="flexera_rss_settings">Feeds and settings</string>
<string name="flexera_rss_allow_local_network">Allow local network access</string>
<string name="flexera_rss_no_feeds">No feeds yet</string>
<string name="flexera_rss_no_feeds_body">Add the sites and blogs you follow, and their newest posts show up here.</string>
<string name="flexera_rss_add_feeds">Add feeds</string>
<string name="flexera_rss_loading">Loading your feeds…</string>
<string name="flexera_rss_failed">Couldn\'t load your feeds</string>
<string name="flexera_rss_try_again">Try again</string>
<string name="flexera_rss_nothing">No posts in your feeds yet</string>
<string name="flexera_rss_no_app">No app can open this link</string>
<!-- Why a feed could not be fetched or added -->
<string name="flexera_rss_problem_offline">No connection to the internet</string>
<string name="flexera_rss_problem_timeout">The site took too long to answer</string>
<string name="flexera_rss_problem_local_network">The feed is on your local network, which Android keeps the launcher from until you allow it</string>
<string name="flexera_rss_problem_not_found">There\'s nothing at that address</string>
<string name="flexera_rss_problem_server">The site answered with an error</string>
<string name="flexera_rss_problem_not_a_feed">No feed found at that address</string>
<string name="flexera_rss_problem_not_secure">Couldn\'t make a secure connection to the site</string>
<string name="flexera_rss_problem_bad_address">That isn\'t a web address</string>
<!-- The reader's settings -->
<string name="flexera_rss_add_heading">Add a feed</string>
<string name="flexera_rss_add_description">Type a site\'s address, such as theverge.com, or the address of its feed.</string>
<string name="flexera_rss_address">Site or feed address</string>
<string name="flexera_rss_add">Add</string>
<!-- %1$s is the feed's name -->
<string name="flexera_rss_added">Added %1$s</string>
<!-- %1$s is the feed's name -->
<string name="flexera_rss_already_there">%1$s is already in your feeds</string>
<string name="flexera_rss_feeds_heading">Your feeds</string>
<string name="flexera_rss_feeds_description">Their posts appear together on the reader\'s page, the newest first. Pull the list down to refresh.</string>
<!-- Description of the button that removes a feed. %1$s is the feed's name -->
<string name="flexera_rss_remove">Remove %1$s</string>
<!-- A post's age on its card, in few letters -->
<string name="flexera_rss_age_now">now</string>
<!-- %1$d minutes -->
<string name="flexera_rss_age_minutes">%1$dm</string>
<!-- %1$d hours -->
<string name="flexera_rss_age_hours">%1$dh</string>
<!-- %1$d days -->
<string name="flexera_rss_age_days">%1$dd</string>
<string name="flexera_rss_share">Share</string>
<!-- The article view: a post read inside the reader -->
<string name="flexera_rss_back">Back to your feeds</string>
<string name="flexera_rss_visit_article">Visit article</string>
<string name="flexera_rss_loading_article">Loading the whole article…</string>
<string name="flexera_rss_article_partial">This is as much of the article as could be brought here. Visit article to read it on the site.</string>
<!-- Settings, Gestures -->
<string name="flexera_rss_gestures_description">Choose Open RSS reader for a gesture, such as a swipe past the first page, and your feeds slide in.</string>
<plurals name="flexera_rss_feed_count">
<item quantity="one">%d feed</item>
<item quantity="other">%d feeds</item>
</plurals>
</resources>
@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Flexera Launcher's clock widget (app.flexera.widget.ClockWidgetProvider). Four cells by two
when first placed, resizable from two by one upwards. The launcher draws it itself, so the
layouts named here are never shown on the home screen; previewLayout is what makes the widget
list ask for a live preview, which the launcher also draws. Nothing has to be set up when it
is added (configuration_optional); its edit button opens the options for alignment and size.
-->
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="250dp"
android:minHeight="110dp"
android:minResizeWidth="110dp"
android:minResizeHeight="40dp"
android:targetCellWidth="4"
android:targetCellHeight="2"
android:updatePeriodMillis="0"
android:description="@string/flexera_clock_widget_description"
android:configure="app.flexera.widget.ClockWidgetConfigActivity"
android:initialLayout="@layout/flexera_clock_widget_placeholder"
android:previewLayout="@layout/flexera_clock_widget_placeholder"
android:resizeMode="horizontal|vertical"
android:widgetCategory="home_screen"
android:widgetFeatures="reconfigurable|configuration_optional" />
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Flexera Launcher's picture widget (app.flexera.widget.PictureWidgetProvider). Two cells by two
when first placed, resizable down to one cell and up to the whole screen. The launcher draws it
itself, so the layouts named here are never shown on the home screen; previewLayout is what
makes the widget list ask for a live preview, which the launcher also draws.
-->
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="110dp"
android:minHeight="110dp"
android:minResizeWidth="40dp"
android:minResizeHeight="40dp"
android:targetCellWidth="2"
android:targetCellHeight="2"
android:updatePeriodMillis="0"
android:description="@string/flexera_picture_widget_description"
android:configure="app.flexera.widget.PictureWidgetConfigActivity"
android:initialLayout="@layout/flexera_picture_widget_placeholder"
android:previewLayout="@layout/flexera_picture_widget_placeholder"
android:resizeMode="horizontal|vertical"
android:widgetCategory="home_screen"
android:widgetFeatures="reconfigurable" />
@@ -0,0 +1,757 @@
package app.flexera.backup
import android.content.ComponentName
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.pm.LauncherApps
import android.database.sqlite.SQLiteDatabase
import android.net.Uri
import android.os.Process
import android.util.Log
import app.flexera.widget.PictureWidgetProvider
import app.flexera.widget.PictureWidgetStore
import app.lawnchair.DeviceProfileOverrides
import app.lawnchair.backup.LawnchairBackup
import app.lawnchair.preferences.PreferenceManager
import app.lawnchair.preferences2.PreferenceManager2
import app.lawnchair.preferences2.firstCached
import com.android.launcher3.GridType
import com.android.launcher3.InvariantDeviceProfile
import com.android.launcher3.LauncherSettings.Favorites
import com.android.launcher3.model.DatabaseHelper
import com.android.launcher3.model.DeviceGridState
import com.android.launcher3.model.ModelDbController
import com.android.launcher3.pm.UserCache
import com.android.launcher3.provider.RestoreDbTask
import com.android.launcher3.shortcuts.ShortcutKey
import com.android.launcher3.shortcuts.ShortcutRequest
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.net.URISyntaxException
import java.util.UUID
import java.util.zip.ZipInputStream
import javax.xml.parsers.DocumentBuilderFactory
import kotlin.math.max
import kotlin.math.roundToInt
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
/**
* Imports the home screens of a Smart Launcher backup: icons, folders and widgets, each in the
* place it had, on a grid of the same size and, like Smart Launcher, without a dock.
*
* A backup (a .slbk file) is a zip of Smart Launcher's own files. Two of them matter here:
* - `databases/ginlemon.flower.db`, a SQLite database. Its table `HomeItem` has one row per
* thing on a home screen (screen, cell, size) that points either at a `Launchable`, which
* `Action` describes with an ordinary Android intent, or at a `Widget` with its provider.
* A folder is a launchable too; its members are the launchables that name it as their parent.
* - the preferences file under `shared_prefs/`, where `launcher_profile_#0` holds the grid.
*
* The format is not documented. This follows one real backup, of Smart Launcher's data
* version 64, and refuses a file in which it does not find these tables.
*
* What cannot come along is said to the owner before the import ([Info]): Smart Launcher's own
* widgets, which exist only inside Smart Launcher, items of other profiles, and what sits in the
* row that At a Glance takes while it is switched on. A widget that does come along arrives as
* "tap to set up": Android has every launcher ask for its widgets itself, and keeps a widget's
* settings with the launcher that made it.
*
* The layout is handed to Launcher3 the way Lawnchair's Nova import hands over its own
* (see [app.lawnchair.backup.NovaBackupConverter]): as a database of Launcher3's own shape,
* which Launcher3's restore code then takes in.
*/
class SmartLauncherBackupConverter(
private val context: Context,
private val uri: Uri,
) {
/** What a backup holds, for the owner to see before agreeing to the import. */
data class Info(
val columns: Int,
val rows: Int,
/** Home screens with something on them; none means there is nothing to import. */
val screens: Int,
/** Whether the backup shows labels on the home screens, as the import then does; null if it does not say. */
val showLabels: Boolean?,
val apps: Int,
val folders: Int,
val appsInFolders: Int,
val widgets: Int,
/** Smart Launcher's photo widgets, which become the launcher's own picture widget. */
val photoWidgets: Int,
/** Smart Launcher's other widgets of its own, which stay behind. */
val ownWidgets: Int,
/** Things in the top row of the first screen, which At a Glance takes while it is on: they stay behind. */
val glanceRow: Int,
/** Other things that stay behind: no usable target, another profile, or no free cells. */
val skipped: Int,
)
/** Where a thing sits on the home screens, in whole cells. */
private data class Place(val screen: Int, val x: Int, val y: Int, val width: Int, val height: Int)
/** An icon: an app, or a shortcut into an app ([shortcutId] with [packageName]). */
private data class Icon(
val title: String?,
val intentUri: String,
val packageName: String?,
val shortcutId: String?,
)
private sealed interface HomeThing {
val place: Place
}
private data class HomeIcon(override val place: Place, val icon: Icon) : HomeThing
private data class HomeFolder(override val place: Place, val title: String?, val icons: List<Icon>) : HomeThing
private data class HomeWidget(override val place: Place, val provider: String) : HomeThing
/** One of Smart Launcher's photo widgets, with the unpacked files of its pictures. */
private data class HomePicture(override val place: Place, val photos: List<File>) : HomeThing
/**
* What a widget of the backup becomes: [thing], or nothing. [ownWidget] tells Smart Launcher's
* own widgets, which exist only inside it, from app widgets that cannot come along.
*/
private data class WidgetRead(val thing: HomeThing?, val ownWidget: Boolean = false)
private data class Layout(
val columns: Int,
val rows: Int,
val showLabels: Boolean?,
val things: List<HomeThing>,
val ownWidgets: Int,
val glanceRow: Int,
val skipped: Int,
) {
val info: Info
get() = Info(
columns = columns,
rows = rows,
screens = things.map { it.place.screen }.distinct().size,
showLabels = showLabels,
apps = things.count { it is HomeIcon },
folders = things.count { it is HomeFolder },
appsInFolders = things.sumOf { (it as? HomeFolder)?.icons?.size ?: 0 },
widgets = things.count { it is HomeWidget },
photoWidgets = things.count { it is HomePicture },
ownWidgets = ownWidgets,
glanceRow = glanceRow,
skipped = skipped,
)
}
/** Reads the backup and says what is in it. Throws if it is not a backup this can read. */
suspend fun parseInfo(): Info = withContext(Dispatchers.IO) {
// Counting the photo widgets needs none of their pictures.
withUnpackedBackup(withPhotos = false) { dir -> readLayout(dir).info }
}
/**
* Replaces the home screens with the backup's. The launcher has to be restarted afterwards
* to show them.
*/
suspend fun convertAndRestore() {
val layout = withContext(Dispatchers.IO) {
// The backup stays unpacked to the end: the photo widgets' pictures are read from it.
withUnpackedBackup(withPhotos = true) { dir -> readLayout(dir).also(::restore) }
}
// Settings that make the result match the source: no dock, because Smart Launcher has
// none, and labels as they were. Last, so that a failed import changes nothing.
val prefs2 = PreferenceManager2.getInstance(context)
prefs2.isHotseatEnabled.set(false)
layout.showLabels?.let { prefs2.showIconLabelsOnHomeScreen.set(it) }
}
/** Puts the layout into the launcher's database and keeps the photo widgets' pictures. */
private fun restore(layout: Layout) {
val tempDir = newTempDir()
try {
val staged = File(tempDir, STAGED_DB)
val shortcuts = writeLauncherDb(layout, staged)
applyGrid(layout)
val restored = context.getDatabasePath(LawnchairBackup.RESTORED_DB_FILE_NAME)
restored.parentFile?.mkdirs()
staged.copyTo(restored, overwrite = true)
// Opening the controller moves the restored file into place; the restore task
// then marks every item as freshly restored, which is what makes Launcher3 ask
// for the widgets anew and drop icons of apps that are not installed.
check(RestoreDbTask.performRestore(context, ModelDbController(context))) {
"Launcher3 did not accept the converted layout"
}
pinShortcuts(shortcuts)
} finally {
tempDir.deleteRecursively()
}
keepPictures(layout)
}
/**
* Puts the pictures of the imported photo widgets where the picture widget finds them. Each
* widget arrives as "tap to set up" like every imported widget; the tap then gives it these
* pictures in place of asking for some (PictureWidgetConfigActivity).
*/
private fun keepPictures(layout: Layout) {
PictureWidgetStore.clearImports(context)
for (thing in layout.things) {
if (thing is HomePicture && thing.photos.isNotEmpty()) {
PictureWidgetStore.stageImport(
context,
thing.place.screen,
thing.place.x,
thing.place.y,
thing.photos.map(Uri::fromFile),
)
}
}
}
// ---- Reading the backup ------------------------------------------------------------------
private fun <T> withUnpackedBackup(withPhotos: Boolean, block: (File) -> T): T {
val dir = newTempDir()
try {
unpack(dir, withPhotos)
return block(dir)
} finally {
dir.deleteRecursively()
}
}
private fun newTempDir(): File {
removeLeftovers(context.cacheDir)
return File(context.cacheDir, "$TEMP_DIR_PREFIX${UUID.randomUUID()}").apply { mkdirs() }
}
/**
* Unpacks the database, the preference files and, with [withPhotos], the pictures of the
* photo widgets, and nothing else, into [dir]. Entry names come from the file and are not
* trusted: only the known places are accepted, each file lands under a name made here, a
* few preference files and pictures at most are taken, and a file of unreasonable size, or
* more in all than any backup holds, ends the import.
*/
private fun unpack(dir: File, withPhotos: Boolean) {
val descriptor = context.contentResolver.openFileDescriptor(uri, "r")
?: error("Cannot open the backup file")
descriptor.use {
ZipInputStream(FileInputStream(it.fileDescriptor)).use { zip ->
var prefs = 0
var photos = 0
var unpacked = 0L
var entry = zip.nextEntry
while (entry != null) {
val name = entry.name
val photo = SL_PHOTO_ENTRY.matchEntire(name)
// Where the entry goes, and how large it may be.
val target: Pair<File, Long>? = when {
entry.isDirectory -> null
name == SL_DB_ENTRY -> File(dir, SL_DB) to MAX_DB_BYTES
name.startsWith(SL_PREFS_DIR) && name.endsWith(".xml") && prefs < MAX_PREFS_FILES -> {
prefs++
File(dir, PREFS_PREFIX + File(name).name) to MAX_PREFS_BYTES
}
// A photo widget's picture, kept under the number of its widget.
withPhotos && photo != null && photos < MAX_PHOTOS ->
File(dir, photoName(photo.groupValues[1], photos++)) to MAX_PHOTO_BYTES
else -> null
}
if (target != null) {
val (file, limit) = target
require(file.canonicalPath.startsWith(dir.canonicalPath + File.separator)) {
"Backup entry outside the import folder: $name"
}
FileOutputStream(file).use { out ->
val buffer = ByteArray(64 * 1024)
var total = 0L
while (true) {
val read = zip.read(buffer)
if (read < 0) break
total += read
unpacked += read
require(total <= limit) { "Backup entry too large: $name" }
require(unpacked <= MAX_UNPACKED_BYTES) { "Backup too large to unpack" }
out.write(buffer, 0, read)
}
}
}
entry = zip.nextEntry
}
}
}
}
private fun readLayout(dir: File): Layout {
val dbFile = File(dir, SL_DB)
require(dbFile.exists()) { "No Smart Launcher database in this file" }
val grid = readGrid(dir)
SQLiteDatabase.openDatabase(dbFile.absolutePath, null, SQLiteDatabase.OPEN_READONLY).use { db ->
for (table in listOf(T_HOME, T_LAUNCHABLE, T_ACTION, T_WIDGET)) {
require(tableExists(db, table)) { "Smart Launcher database without table $table" }
}
return readHomeScreens(db, grid, dir)
}
}
private data class Grid(val columns: Int, val rows: Int, val showLabels: Boolean?)
/** The home grid from the preferences, or null where a backup does not state it. */
private fun readGrid(dir: File): Grid? {
val files = dir.listFiles { file -> file.name.startsWith(PREFS_PREFIX) } ?: return null
for (file in files) {
try {
val document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file)
val strings = document.documentElement.getElementsByTagName("string")
for (i in 0 until strings.length) {
val node = strings.item(i)
val name = node.attributes?.getNamedItem("name")?.nodeValue ?: continue
if (!name.startsWith(SL_PROFILE_KEY_PREFIX)) continue
val settings = JSONObject(node.textContent).optJSONObject("gridUserSettings") ?: continue
val columns = settings.optInt("columns", 0)
val rows = settings.optInt("rows", 0)
if (columns in 1..MAX_GRID && rows in 1..MAX_GRID) {
val labels = if (settings.has("hasLabel")) settings.optBoolean("hasLabel") else null
return Grid(columns, rows, labels)
}
}
} catch (e: Exception) {
Log.w(TAG, "Unreadable preference file in backup: ${file.name}", e)
}
}
return null
}
private fun readHomeScreens(db: SQLiteDatabase, grid: Grid?, dir: File): Layout {
data class Row(
val launchable: Long?,
val widget: Long?,
val screen: Int,
val x: Int,
val y: Int,
val width: Int,
val height: Int,
)
// Smart Launcher can keep more than one arrangement ("configId"); the first is the one
// in use on a phone held upright.
val rows = ArrayList<Row>()
db.rawQuery(
"SELECT idLaunchable, idWidget, screen, cellX, cellY, spanX, spanY FROM $T_HOME " +
"WHERE configId = (SELECT MIN(configId) FROM $T_HOME) ORDER BY zIndex, id",
null,
).use { c ->
while (c.moveToNext()) {
rows.add(
Row(
launchable = if (c.isNull(0)) null else c.getLong(0),
widget = if (c.isNull(1)) null else c.getLong(1),
screen = c.getInt(2),
x = c.getDouble(3).roundToInt(),
y = c.getDouble(4).roundToInt(),
width = c.getDouble(5).roundToInt().coerceAtLeast(1),
height = c.getDouble(6).roundToInt().coerceAtLeast(1),
),
)
}
}
val columns = grid?.columns ?: max(MIN_GRID, rows.maxOfOrNull { it.x + it.width } ?: 0)
val gridRows = grid?.rows ?: max(MIN_GRID, rows.maxOfOrNull { it.y + it.height } ?: 0)
// Launcher3 numbers its screens from 0 without gaps, left to right.
val screenIndex = rows.map { it.screen }.distinct().sorted().withIndex().associate { it.value to it.index }
val taken = HashSet<Triple<Int, Int, Int>>()
// While At a Glance is switched on it takes the top row of the first screen, and Launcher3
// drops what a layout puts there (LoaderCursor.checkItemPlacement) or At a Glance covers it.
val glance = PreferenceManager2.getInstance(context).enableSmartspace.firstCached()
val things = ArrayList<HomeThing>()
var ownWidgets = 0
var glanceRow = 0
var skipped = 0
for (row in rows) {
val screen = screenIndex.getValue(row.screen)
val place = Place(screen, row.x, row.y, row.width, row.height)
val cells = cellsOf(place)
// Launcher3 keeps one thing per cell and nothing outside the grid.
val fits = row.x >= 0 && row.y >= 0 && row.x + row.width <= columns &&
row.y + row.height <= gridRows && cells.none { it in taken }
val widget = row.widget?.let { readWidget(db, it, place, dir) }
val read: HomeThing? = when {
widget != null -> widget.thing
row.launchable != null -> readLaunchable(db, row.launchable, place)
else -> null
}
when {
widget?.ownWidget == true -> ownWidgets++
read == null || !fits -> skipped++
glance && screen == 0 && row.y == 0 -> glanceRow++
else -> {
things.add(read)
taken.addAll(cells)
}
}
}
return Layout(columns, gridRows, grid?.showLabels, things, ownWidgets, glanceRow, skipped)
}
private fun cellsOf(place: Place): List<Triple<Int, Int, Int>> = buildList {
for (x in place.x until place.x + place.width) {
for (y in place.y until place.y + place.height) {
add(Triple(place.screen, x, y))
}
}
}
/**
* What a widget of the backup becomes. An ordinary app widget of the phone's owner keeps its
* provider. Smart Launcher's photo widget becomes the launcher's own picture widget, with the
* pictures the backup holds for it. Smart Launcher's other widgets have no counterpart, and
* neither has an app widget of another profile or one without a provider this can use.
*/
private fun readWidget(db: SQLiteDatabase, id: Long, place: Place, dir: File): WidgetRead =
db.rawQuery("SELECT type, provider, userId FROM $T_WIDGET WHERE id = ?", arrayOf(id.toString())).use { c ->
if (!c.moveToFirst()) {
WidgetRead(null)
} else {
val type = c.getInt(0)
val provider = if (c.isNull(1)) null else c.getString(1)
val user = if (c.isNull(2)) OWNER_USER else c.getInt(2)
val component = provider?.let(ComponentName::unflattenFromString)
when {
type == SL_WIDGET_TYPE_APP && component != null && user == OWNER_USER ->
WidgetRead(HomeWidget(place, component.flattenToString()))
type != SL_WIDGET_TYPE_APP && provider?.endsWith(SL_PHOTO_WIDGET_CLASS) == true -> {
val prefix = photoName(id.toString(), null)
val photos = dir.listFiles { file -> file.name.startsWith(prefix) }
WidgetRead(HomePicture(place, photos?.sortedBy { it.name }.orEmpty()))
}
type != SL_WIDGET_TYPE_APP -> WidgetRead(null, ownWidget = true)
else -> WidgetRead(null)
}
}
}
/** The icon or folder behind a launchable, or null if it has no target this can use. */
private fun readLaunchable(db: SQLiteDatabase, id: Long, place: Place): HomeThing? {
val action = readAction(db, id) ?: return null
if (action.type != SL_ACTION_TYPE_FOLDER) {
return action.toIcon()?.let { HomeIcon(place, it) }
}
val icons = ArrayList<Icon>()
db.rawQuery(
"SELECT id FROM $T_LAUNCHABLE WHERE idParentFolderLaunchable = ? ORDER BY position, id",
arrayOf(id.toString()),
).use { c ->
while (c.moveToNext()) {
readAction(db, c.getLong(0))?.takeIf { it.type != SL_ACTION_TYPE_FOLDER }?.toIcon()?.let(icons::add)
}
}
// Launcher3 has no use for a folder with nothing in it.
return if (icons.isEmpty()) null else HomeFolder(place, action.label, icons)
}
private data class Action(
val type: Int,
val intentUri: String?,
val user: Int,
val label: String?,
val shortcutId: String?,
) {
/** Launcher3's form of this action, if it opens an app or one of an app's shortcuts. */
fun toIcon(): Icon? {
// Icons of a work profile or a second user are left out; -1 means "no user", as on folders.
if (user != OWNER_USER && user != NO_USER) return null
val intent = try {
Intent.parseUri(intentUri ?: return null, 0)
} catch (_: URISyntaxException) {
return null
}
val component = intent.component
val packageName = component?.packageName ?: intent.`package`
return when {
!shortcutId.isNullOrEmpty() && packageName != null ->
Icon(label, ShortcutKey.makeIntent(shortcutId, packageName).toUri(0), packageName, shortcutId)
component != null -> Icon(label, launchIntentFor(component).toUri(0), packageName, null)
else -> null
}
}
}
/** The first action of a launchable, which is what a tap does. */
private fun readAction(db: SQLiteDatabase, launchable: Long): Action? =
db.rawQuery(
"SELECT type, intentUri, userId, label, deepShortcutId FROM $T_ACTION " +
"WHERE idLaunchable = ? ORDER BY actionId LIMIT 1",
arrayOf(launchable.toString()),
).use { c ->
if (!c.moveToFirst()) {
null
} else {
Action(
type = c.getInt(0),
intentUri = if (c.isNull(1)) null else c.getString(1),
user = if (c.isNull(2)) OWNER_USER else c.getInt(2),
label = if (c.isNull(3)) null else c.getString(3),
shortcutId = if (c.isNull(4)) null else c.getString(4),
)
}
}
private fun tableExists(db: SQLiteDatabase, table: String): Boolean =
db.rawQuery("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?", arrayOf(table)).use {
it.moveToFirst()
}
// ---- Writing Launcher3's layout ----------------------------------------------------------
/**
* Writes [layout] as a Launcher3 database at [target]. Returns the app shortcuts in it, by
* package, which the launcher has to pin before it may show them.
*/
private fun writeLauncherDb(layout: Layout, target: File): Map<String, Set<String>> {
val profileId = UserCache.INSTANCE.get(context).getSerialNumberForUser(Process.myUserHandle())
val shortcuts = HashMap<String, MutableSet<String>>()
val now = System.currentTimeMillis()
var nextId = 1
SQLiteDatabase.openOrCreateDatabase(target, null).use { db ->
db.version = DatabaseHelper.SCHEMA_VERSION
Favorites.addTableToDb(db, profileId, false)
fun insert(
container: Int,
place: Place?,
rank: Int,
itemType: Int,
title: String? = null,
intentUri: String? = null,
provider: String? = null,
): Int {
val id = nextId++
db.insertOrThrow(
Favorites.TABLE_NAME,
null,
ContentValues().apply {
put(Favorites._ID, id)
put(Favorites.TITLE, title)
put(Favorites.INTENT, intentUri)
put(Favorites.CONTAINER, container)
put(Favorites.SCREEN, place?.screen ?: 0)
put(Favorites.CELLX, place?.x ?: 0)
put(Favorites.CELLY, place?.y ?: 0)
put(Favorites.SPANX, place?.width ?: 1)
put(Favorites.SPANY, place?.height ?: 1)
put(Favorites.ITEM_TYPE, itemType)
put(Favorites.APPWIDGET_ID, -1)
put(Favorites.APPWIDGET_PROVIDER, provider)
put(Favorites.MODIFIED, now)
put(Favorites.RESTORED, 0)
put(Favorites.PROFILE_ID, profileId)
put(Favorites.RANK, rank)
put(Favorites.OPTIONS, 0)
put(Favorites.APPWIDGET_SOURCE, -1)
},
)
return id
}
fun insertIcon(icon: Icon, container: Int, place: Place?, rank: Int) {
val isShortcut = icon.shortcutId != null && icon.packageName != null
if (isShortcut) {
shortcuts.getOrPut(icon.packageName!!) { HashSet() }.add(icon.shortcutId!!)
}
insert(
container = container,
place = place,
rank = rank,
itemType = if (isShortcut) Favorites.ITEM_TYPE_DEEP_SHORTCUT else Favorites.ITEM_TYPE_APPLICATION,
title = icon.title,
intentUri = icon.intentUri,
)
}
db.beginTransaction()
try {
for (thing in layout.things) {
when (thing) {
is HomeIcon -> insertIcon(thing.icon, Favorites.CONTAINER_DESKTOP, thing.place, 0)
is HomeFolder -> {
val folder = insert(
container = Favorites.CONTAINER_DESKTOP,
place = thing.place,
rank = 0,
itemType = Favorites.ITEM_TYPE_FOLDER,
title = thing.title,
)
thing.icons.forEachIndexed { rank, icon -> insertIcon(icon, folder, null, rank) }
}
is HomeWidget -> insert(
container = Favorites.CONTAINER_DESKTOP,
place = thing.place,
rank = 0,
itemType = Favorites.ITEM_TYPE_APPWIDGET,
provider = thing.provider,
)
is HomePicture -> insert(
container = Favorites.CONTAINER_DESKTOP,
place = thing.place,
rank = 0,
itemType = Favorites.ITEM_TYPE_APPWIDGET,
provider = PictureWidgetProvider.componentName.flattenToString(),
)
}
}
db.setTransactionSuccessful()
} finally {
db.endTransaction()
}
}
return shortcuts
}
/** Makes the home grid the size of the backup's, in every place the launcher keeps it. */
private fun applyGrid(layout: Layout) {
val prefs = PreferenceManager.getInstance(context)
val hotseat = prefs.hotseatColumns.get()
val gridInfo = DeviceProfileOverrides.DBGridInfo(
numHotseatColumns = hotseat,
numRows = layout.rows,
numColumns = layout.columns,
)
val gridState = DeviceGridState(
layout.columns,
layout.rows,
hotseat,
InvariantDeviceProfile.TYPE_PHONE,
gridInfo.dbFile,
GridType.GRID_TYPE_ANY,
)
gridState.writeToPrefs(context, true)
gridState.writeToPrefs(context)
InvariantDeviceProfile.INSTANCE.get(context).dbFile = gridInfo.dbFile
prefs.sp.edit()
.putInt(prefs.workspaceColumns.key, layout.columns)
.putInt(prefs.workspaceRows.key, layout.rows)
.commit()
}
/** Pins the imported app shortcuts, keeping whatever the launcher has pinned already. */
private fun pinShortcuts(shortcuts: Map<String, Set<String>>) {
if (shortcuts.isEmpty()) return
val launcherApps = context.getSystemService(LauncherApps::class.java) ?: return
val user = Process.myUserHandle()
for ((packageName, ids) in shortcuts) {
val pinned = LinkedHashSet<String>()
val current = ShortcutRequest(context, user)
.forPackage(packageName)
.query(ShortcutRequest.PINNED or LauncherApps.ShortcutQuery.FLAG_GET_KEY_FIELDS_ONLY)
if (current.wasSuccess()) current.mapTo(pinned) { it.id }
pinned.addAll(ids)
try {
launcherApps.pinShortcuts(packageName, pinned.toList(), user)
} catch (e: SecurityException) {
Log.w(TAG, "Could not pin the imported shortcuts of $packageName", e)
} catch (e: IllegalStateException) {
Log.w(TAG, "Could not pin the imported shortcuts of $packageName", e)
}
}
}
private companion object {
const val TAG = "SmartLauncherImport"
const val SL_DB_ENTRY = "databases/ginlemon.flower.db"
const val SL_PREFS_DIR = "shared_prefs/"
const val SL_PROFILE_KEY_PREFIX = "launcher_profile_"
const val T_HOME = "HomeItem"
const val T_LAUNCHABLE = "Launchable"
const val T_ACTION = "Action"
const val T_WIDGET = "Widget"
/** `Action.type` of a folder; every other type seen opens an app. */
const val SL_ACTION_TYPE_FOLDER = 9
/** `Widget.type` of an ordinary app widget; the other types are Smart Launcher's own. */
const val SL_WIDGET_TYPE_APP = 1
/** How `Widget.provider` ends for Smart Launcher's photo widget, in every edition of it. */
const val SL_PHOTO_WIDGET_CLASS = ".PhotoWidget"
/** Where a backup keeps the pictures of a photo widget: a folder named by `Widget.id`. */
val SL_PHOTO_ENTRY = Regex("files/widgetPhoto/(\\d{1,18})/[^/]+")
/** More pictures than this in one backup are not taken along. */
const val MAX_PHOTOS = 100
/**
* The name an unpacked picture gets: its widget's number, then its turn. Without a turn,
* the start of the names of all pictures of that widget.
*/
fun photoName(widget: String, turn: Int?): String = "photo_${widget}_" + (turn?.toString() ?: "")
/** Smart Launcher's user ids: the phone's owner, and "no user" on folders. */
const val OWNER_USER = 0
const val NO_USER = -1
const val TEMP_DIR_PREFIX = "smartlauncher_"
const val SL_DB = "smartlauncher.db"
const val PREFS_PREFIX = "prefs_"
const val STAGED_DB = "workspace.db"
/** Far above any real backup's database; a larger entry is not a backup. */
const val MAX_DB_BYTES = 64L * 1024 * 1024
/**
* Preference files taken from one backup, and the size of each. Smart Launcher's own is
* a few kilobytes; further files are not taken.
*/
const val MAX_PREFS_FILES = 8
const val MAX_PREFS_BYTES = 1L * 1024 * 1024
/** The size of one picture. Smart Launcher keeps a photo as a small WebP file. */
const val MAX_PHOTO_BYTES = 32L * 1024 * 1024
/** All that is unpacked from one backup, so that a crafted file cannot fill the phone's storage. */
const val MAX_UNPACKED_BYTES = 256L * 1024 * 1024
/** Whether this run of the launcher has removed what imports cut short left behind. */
private var leftoversRemoved = false
/**
* Removes the folders of imports that were cut short, for example by the process ending
* in the middle of one: they hold a copy of the owner's home screens and photos. Done
* once per run of the launcher, before its first import makes a folder, so that no folder
* of an import under way is touched.
*/
@Synchronized
fun removeLeftovers(cacheDir: File) {
if (leftoversRemoved) return
cacheDir.listFiles { file -> file.name.startsWith(TEMP_DIR_PREFIX) }?.forEach { it.deleteRecursively() }
leftoversRemoved = true
}
const val MIN_GRID = 4
const val MAX_GRID = 20
/** The intent Launcher3 itself stores for an app icon. */
fun launchIntentFor(component: ComponentName): Intent =
Intent(Intent.ACTION_MAIN)
.addCategory(Intent.CATEGORY_LAUNCHER)
.setComponent(component)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
}
}
@@ -0,0 +1,248 @@
package app.flexera.backup
import android.app.Activity
import android.content.Intent
import android.widget.Toast
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import androidx.navigation.toRoute
import app.flexera.backup.SmartLauncherImportViewModel.State
import app.lawnchair.preferences2.asState
import app.lawnchair.preferences2.preferenceManager2
import app.lawnchair.ui.preferences.LocalIsExpandedScreen
import app.lawnchair.ui.preferences.LocalNavController
import app.lawnchair.ui.preferences.components.layout.PreferenceGroup
import app.lawnchair.ui.preferences.components.layout.PreferenceLayout
import app.lawnchair.ui.preferences.components.layout.PreferenceTemplate
import app.lawnchair.ui.preferences.navigation.ImportSmartLauncherBackup
import app.lawnchair.util.BackHandler
import com.android.launcher3.R
import java.util.Base64
/**
* The screen between choosing a Smart Launcher backup and importing it. It says what the file
* holds, what will not come along and what the import replaces, and waits for the owner's word.
*/
fun NavGraphBuilder.smartLauncherImportGraph() {
composable<ImportSmartLauncherBackup> { entry ->
val route: ImportSmartLauncherBackup = entry.toRoute()
// A route that does not decode names no file that can be read; it must not end the
// launcher's process, which this screen shares with the home screen.
val backup = remember {
runCatching { String(Base64.getDecoder().decode(route.base64Uri)).toUri() }.getOrNull()
}
val viewModel: SmartLauncherImportViewModel = viewModel()
DisposableEffect(Unit) {
viewModel.open(backup)
onDispose { }
}
SmartLauncherImportScreen(viewModel)
}
}
@Composable
private fun SmartLauncherImportScreen(viewModel: SmartLauncherImportViewModel) {
val context = LocalContext.current
val state by viewModel.state.collectAsStateWithLifecycle()
PreferenceLayout(
label = stringResource(id = R.string.flexera_import_smart_launcher),
backArrowVisible = !LocalIsExpandedScreen.current,
) {
when (val current = state) {
State.Reading -> Box(modifier = Modifier.fillMaxSize()) {
CircularProgressIndicator(modifier = Modifier.align(Alignment.Center))
}
State.Unreadable -> {
val back = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher
LaunchedEffect(Unit) {
Toast.makeText(context, R.string.flexera_import_unreadable, Toast.LENGTH_LONG).show()
back?.onBackPressed()
}
}
is State.Ready -> {
// The import carries on without this screen, but it ends by restarting the
// launcher; staying here shows what is going on until then.
if (current.importing) BackHandler {}
BackupContents(current.info)
Box(
modifier = Modifier
.fillMaxWidth()
.padding(top = 8.dp)
.padding(horizontal = 16.dp),
) {
Button(
onClick = viewModel::import,
modifier = Modifier
.fillMaxWidth()
// So that a screen reader says "Importing…": it can take a while.
.semantics { liveRegion = LiveRegionMode.Polite },
// With nothing that can be placed, importing would only empty the home screens.
enabled = current.info.screens > 0 && !current.importing,
) {
if (current.importing) {
CircularProgressIndicator(
modifier = Modifier.size(ButtonDefaults.IconSize),
strokeWidth = 2.dp,
color = LocalContentColor.current,
)
Spacer(Modifier.width(ButtonDefaults.IconSpacing))
}
Text(
text = stringResource(
id = if (current.importing) R.string.flexera_import_importing else R.string.flexera_import_action,
),
)
}
}
}
}
}
}
@Composable
private fun BackupContents(info: SmartLauncherBackupConverter.Info) {
PreferenceGroup(heading = stringResource(id = R.string.flexera_import_found)) {
InfoRow(
R.string.flexera_import_screens,
stringResource(id = R.string.flexera_import_screens_value, info.screens, info.columns, info.rows),
)
if (info.apps > 0) InfoRow(R.string.flexera_import_apps, info.apps.toString())
if (info.folders > 0) {
InfoRow(
R.string.flexera_import_folders,
pluralStringResource(
id = R.plurals.flexera_import_folders_value,
count = info.appsInFolders,
info.folders,
info.appsInFolders,
),
)
}
if (info.widgets > 0) {
InfoRow(R.string.flexera_import_widgets, stringResource(id = R.string.flexera_import_widgets_value, info.widgets))
}
if (info.photoWidgets > 0) {
InfoRow(
R.string.flexera_import_photo_widgets,
pluralStringResource(
id = R.plurals.flexera_import_photo_widgets_value,
count = info.photoWidgets,
info.photoWidgets,
),
)
}
}
if (info.ownWidgets > 0 || info.glanceRow > 0 || info.skipped > 0) {
PreferenceGroup(heading = stringResource(id = R.string.flexera_import_left_out)) {
if (info.ownWidgets > 0) {
InfoRow(
R.string.flexera_import_own_widgets,
pluralStringResource(
id = R.plurals.flexera_import_own_widgets_value,
count = info.ownWidgets,
info.ownWidgets,
),
)
}
if (info.glanceRow > 0) {
InfoRow(
R.string.flexera_import_glance,
pluralStringResource(id = R.plurals.flexera_import_glance_value, count = info.glanceRow, info.glanceRow),
)
}
if (info.skipped > 0) {
InfoRow(
R.string.flexera_import_skipped,
pluralStringResource(id = R.plurals.flexera_import_skipped_value, count = info.skipped, info.skipped),
)
}
}
}
if (info.screens == 0) {
PreferenceGroup {
PreferenceTemplate(
title = { Text(text = stringResource(id = R.string.flexera_import_nothing_title)) },
description = { Text(text = stringResource(id = R.string.flexera_import_nothing_body)) },
)
}
} else {
PreferenceGroup(heading = stringResource(id = R.string.flexera_import_effect)) {
PreferenceTemplate(
title = { Text(text = stringResource(id = R.string.flexera_import_effect_title)) },
description = { Text(text = stringResource(id = R.string.flexera_import_effect_body)) },
)
// The import makes this setting match the backup; said only where that changes it.
val labelsNow by preferenceManager2().showIconLabelsOnHomeScreen.asState()
val labels = info.showLabels
if (labels != null && labels != labelsNow) {
InfoRow(
R.string.flexera_import_labels,
stringResource(id = if (labels) R.string.flexera_import_labels_on else R.string.flexera_import_labels_off),
)
}
}
}
}
@Composable
private fun InfoRow(labelRes: Int, value: String) {
PreferenceTemplate(
title = { Text(text = stringResource(id = labelRes)) },
description = { Text(text = value) },
)
}
/** Returns an action that lets the owner pick a backup file and then opens the import screen for it. */
@Composable
fun smartLauncherImportOpener(): () -> Unit {
val navController = LocalNavController.current
val request = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode != Activity.RESULT_OK) return@rememberLauncherForActivityResult
val uri = result.data?.data ?: return@rememberLauncherForActivityResult
val base64Uri = Base64.getEncoder().encodeToString(uri.toString().toByteArray())
navController.navigate(ImportSmartLauncherBackup(base64Uri))
}
return {
// A .slbk file has no file type Android knows, so every file is offered.
request.launch(
Intent(Intent.ACTION_OPEN_DOCUMENT)
.addCategory(Intent.CATEGORY_OPENABLE)
.setType("*/*"),
)
}
}
@@ -0,0 +1,88 @@
package app.flexera.backup
import android.app.Application
import android.net.Uri
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import app.lawnchair.util.restartLauncher
import com.android.launcher3.R
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* Holds one Smart Launcher import: reads the chosen backup, shows what is in it, and on the
* owner's word replaces the home screens with it and restarts the launcher. Same shape as
* Lawnchair's view model for a Nova backup.
*/
internal class SmartLauncherImportViewModel(application: Application) : AndroidViewModel(application) {
sealed interface State {
data object Reading : State
data object Unreadable : State
data class Ready(val info: SmartLauncherBackupConverter.Info, val importing: Boolean = false) : State
}
private var converter: SmartLauncherBackupConverter? = null
private val mutableState = MutableStateFlow<State>(State.Reading)
val state: StateFlow<State> = mutableState.asStateFlow()
/** Reads [backup]; without one, there is nothing to read. */
fun open(backup: Uri?) {
if (converter != null) return
if (backup == null) {
mutableState.value = State.Unreadable
return
}
val converter = SmartLauncherBackupConverter(getApplication(), backup).also { converter = it }
viewModelScope.launch {
mutableState.value = try {
State.Ready(converter.parseInfo())
} catch (t: Throwable) {
Log.e(TAG, "Not a Smart Launcher backup this can read", t)
State.Unreadable
}
}
}
fun import() {
val ready = mutableState.value as? State.Ready ?: return
val converter = converter ?: return
// With nothing that can be placed, importing would only empty the home screens.
if (ready.importing || ready.info.screens == 0) return
viewModelScope.launch {
mutableState.value = ready.copy(importing = true)
// Once begun, the import runs to its end and restarts the launcher even if the owner
// leaves this screen, for example by removing it in Recents, which ends this view
// model. Cut short, it would leave the new home screens in the database without
// their settings, to appear unannounced at some later restart.
withContext(NonCancellable) {
val context = getApplication<Application>()
val imported = try {
converter.convertAndRestore()
true
} catch (t: Throwable) {
Log.e(TAG, "Import failed", t)
false
}
if (imported) {
Toast.makeText(context, R.string.flexera_import_done, Toast.LENGTH_SHORT).show()
restartLauncher(context)
} else {
mutableState.value = ready.copy(importing = false)
Toast.makeText(context, R.string.flexera_import_failed, Toast.LENGTH_LONG).show()
}
}
}
}
private companion object {
const val TAG = "SmartLauncherImport"
}
}
+177 -9
View File
@@ -6,6 +6,7 @@ import android.graphics.Point
import android.graphics.Rect
import android.os.Build
import android.util.TypedValue
import android.view.ContextThemeWrapper
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
@@ -16,7 +17,10 @@ import com.android.launcher3.BubbleTextView
import com.android.launcher3.R
import com.android.launcher3.allapps.ActivityAllAppsContainerView
import com.android.launcher3.allapps.BaseAllAppsAdapter.AdapterItem
import androidx.recyclerview.widget.RecyclerView
import com.android.launcher3.views.BaseDragLayer
import kotlin.math.max
import kotlin.math.min
/**
* Flexera Launcher's app drawer: a single-column alphabetical list with letter headers
@@ -44,9 +48,54 @@ object FlexeraDrawer {
@JvmStatic
fun sectionHeader(sectionName: String): AdapterItem = SectionHeaderItem(sectionName)
/** The sizes the owner can give the list's rows (Settings, App drawer). */
enum class RowSize(val key: String) { COMPACT("compact"), COMFY("comfy") }
/** The row size in use. Changing the setting recreates the launcher. */
@JvmStatic
fun createSectionHeader(inflater: LayoutInflater, parent: ViewGroup): View =
inflater.inflate(R.layout.flexera_all_apps_section_header, parent, false).also(::applySidePadding)
fun rowSize(context: Context): RowSize {
val key = PreferenceManager.getInstance(context).flexeraDrawerRowSize.get()
return RowSize.entries.firstOrNull { it.key == key } ?: RowSize.COMPACT
}
/** Picks the dimension of the row size in use. */
private fun sized(context: Context, compact: Int, comfy: Int): Int =
if (rowSize(context) == RowSize.COMFY) comfy else compact
/** How tall a letter header is. */
@JvmStatic
fun headerHeight(context: Context): Int = context.resources.getDimensionPixelSize(
sized(context, R.dimen.flexera_drawer_header_height, R.dimen.flexera_drawer_header_height_comfy),
)
@JvmStatic
fun createSectionHeader(inflater: LayoutInflater, parent: ViewGroup): View {
val header = inflater.inflate(R.layout.flexera_all_apps_section_header, parent, false) as TextView
val context = header.context
val res = context.resources
// The layout carries the compact sizes; the row size in use has the last word.
header.layoutParams.height = headerHeight(context)
header.setTextSize(
TypedValue.COMPLEX_UNIT_PX,
res.getDimension(
sized(context, R.dimen.flexera_drawer_header_text_size, R.dimen.flexera_drawer_header_text_size_comfy),
),
)
header.setPadding(
header.paddingLeft,
header.paddingTop,
header.paddingRight,
res.getDimensionPixelSize(
sized(
context,
R.dimen.flexera_drawer_header_padding_bottom,
R.dimen.flexera_drawer_header_padding_bottom_comfy,
),
),
)
applySidePadding(header)
return header
}
/**
* True when the owner has moved the wave alphabet to the left edge (PRD AD-15). Changing the
@@ -87,9 +136,20 @@ object FlexeraDrawer {
@JvmStatic
fun styleAppRow(icon: BubbleTextView) {
val res = icon.resources
icon.layoutParams.height = res.getDimensionPixelSize(R.dimen.flexera_drawer_row_height)
icon.compoundDrawablePadding = res.getDimensionPixelSize(R.dimen.flexera_drawer_row_icon_gap)
icon.setTextSize(TypedValue.COMPLEX_UNIT_PX, res.getDimension(R.dimen.flexera_drawer_row_text_size))
// Other icons share the "all apps" display type (search results, for one); this tag
// tells list rows apart from them.
icon.setTag(R.id.flexera_drawer_row, true)
val context = icon.context
icon.layoutParams.height = rowHeight(context)
icon.setIconSizeOverride(
res.getDimensionPixelSize(
sized(context, R.dimen.flexera_drawer_row_icon_size, R.dimen.flexera_drawer_row_icon_size_comfy),
),
)
icon.compoundDrawablePadding = res.getDimensionPixelSize(
sized(context, R.dimen.flexera_drawer_row_icon_gap, R.dimen.flexera_drawer_row_icon_gap_comfy),
)
icon.setTextSize(TypedValue.COMPLEX_UNIT_PX, rowTextSize(context))
applySidePadding(icon)
// The drawer has no background, so names sit directly on the dimmed wallpaper: white,
// with a soft shadow to stay readable over light areas.
@@ -105,12 +165,98 @@ object FlexeraDrawer {
/** Shadow behind white drawer text. */
const val TEXT_SHADOW_COLOR = 0x73000000
/**
* How tall an app row is. The row has to hold the name with a notification preview under
* it (PRD AD-11). At the usual font size the set height does; with a large system font
* the row grows instead.
*/
@JvmStatic
fun rowHeight(context: Context): Int = max(
context.resources.getDimensionPixelSize(
sized(context, R.dimen.flexera_drawer_row_height, R.dimen.flexera_drawer_row_height_comfy),
),
(rowTextSize(context) * ROW_HEIGHT_IN_TEXT_SIZES).toInt(),
)
/** The size of an app name in a row, in pixels. */
private fun rowTextSize(context: Context): Float = context.resources.getDimension(
sized(context, R.dimen.flexera_drawer_row_text_size, R.dimen.flexera_drawer_row_text_size_comfy),
)
/** The least a row's height may be, in name text sizes: two lines of text and some air. */
private const val ROW_HEIGHT_IN_TEXT_SIZES = 2.4f
/**
* What lies between the open drawer and the blurred wallpaper: black at 78%, whatever the
* theme and the wallpaper. Lawnchair's backdrop is a grey at 40%, which over a light
* wallpaper leaves a light grey behind the drawer's white names.
*/
const val BACKDROP_COLOR = 0xC7000000.toInt()
/**
* [context] in the dark theme, for views that lie on the drawer's backdrop. The backdrop is
* dark whatever the theme ([BACKDROP_COLOR]), but Lawnchair colours its search field, its
* results, their cards and its "no results" message from the theme, which in the light theme,
* or over a light wallpaper, gives dark text.
*/
@JvmStatic
fun backdropContext(context: Context): Context = ContextThemeWrapper(context, R.style.AppTheme_Dark)
/**
* Lawnchair fades the search field's pill out while the owner types, leaving the text on the
* drawer's panel. This drawer has no panel, so the pill stays.
*/
const val KEEP_SEARCH_FIELD_BACKGROUND = true
/**
* Moves the search field up with the list, so that it scrolls away like the list's first
* row and comes back when the list is at its top. The field is not a row of the list: it
* lies over the list's top padding and is shifted by as much as the list has scrolled.
* While a search is on, and where the drawer does not use this (work tabs, a hidden or a
* floating search field), the field stays in place.
*/
@JvmStatic
fun moveSearchFieldWithList(appsView: ActivityAllAppsContainerView<*>) {
val field = appsView.searchView ?: return
val list = appsView.activeRecyclerView
val scrolled = if (list == null || appsView.isSearching || !appsView.flexeraSearchFieldScrolls()) {
0
} else {
scrolledFromTop(list)
}
// The field and the list's rows vanish at the same line, the top of the drawer's
// content, which is the lower edge of the status bar. The rows are cut there by the
// list's own top edge; the field is cut here, and travels no further than it takes to
// be all above that line.
val line = appsView.paddingTop
val moved = min(scrolled, max(0, field.bottom - line))
field.translationY = -moved.toFloat()
val hidden = line - (field.top - moved)
if (hidden > 0) {
// The view copies the rectangle, so one scratch rectangle serves every call.
fieldClip.set(0, hidden, field.width, max(hidden, field.height))
field.clipBounds = fieldClip
} else {
field.clipBounds = null
}
}
private val fieldClip = Rect()
/**
* How far [list] has scrolled from its top, in pixels, for as long as its first row is
* still attached; after that, simply "far". Counting rows is exact, which the list's own
* scroll offset, an estimate from row heights, is not.
*/
private fun scrolledFromTop(list: RecyclerView): Int {
val first = list.getChildAt(0) ?: return 0
return if (list.getChildAdapterPosition(first) == 0) {
max(0, list.paddingTop - first.top)
} else {
Int.MAX_VALUE
}
}
/**
* Where the drawer panel sits for a given all-apps progress (0 = open, 1 = closed). Launcher3
* slides the panel up from the bottom; here it stays in place and fades (see
@@ -197,12 +343,19 @@ object FlexeraDrawer {
appsView: ActivityAllAppsContainerView<*>,
dragLayer: BaseDragLayer<*>,
ev: MotionEvent,
) = scrubFromSwipe(appsView, dragLayer, ev.x, ev.y)
/** The same, for a finger position ([x], [y]) in the drag layer's coordinates. */
@JvmStatic
fun scrubFromSwipe(
appsView: ActivityAllAppsContainerView<*>,
dragLayer: BaseDragLayer<*>,
x: Float,
y: Float,
) {
val wave = waveAlphabet(appsView) ?: return
val offset = layoutOffset(wave, dragLayer)
val x = ev.x - offset.x
val y = ev.y - offset.y
if (wave.isScrubbing) wave.moveScrub(x, y) else wave.beginScrub(x, y)
if (wave.isScrubbing) wave.moveScrub(x - offset.x, y - offset.y) else wave.beginScrub(x - offset.x, y - offset.y)
}
/**
@@ -217,7 +370,7 @@ object FlexeraDrawer {
): Boolean {
val wave = waveAlphabet(appsView) ?: return false
val offset = layoutOffset(wave, dragLayer)
return wave.isOnStripBand(ev.x - offset.x, ev.y - offset.y)
return wave.isOnHomeBand(ev.x - offset.x, ev.y - offset.y)
}
/**
@@ -236,12 +389,27 @@ object FlexeraDrawer {
return offset
}
/**
* A scrub that started from a swipe and ends sooner than this was not meant as one: nobody
* reads a letter and means it in a fifth of a second. The swipe opens the plain list.
*/
const val MIN_SCRUB_MS = 200L
/** Ends a scrub started by [scrubFromSwipe]; the drawer stays open at the chosen letter. */
@JvmStatic
fun endScrubFromSwipe(appsView: ActivityAllAppsContainerView<*>) {
waveAlphabet(appsView)?.endScrub()
}
/**
* Ends a scrub started by [scrubFromSwipe] and undoes it, so the drawer opens the way an
* ordinary swipe up leaves it.
*/
@JvmStatic
fun cancelScrubFromSwipe(appsView: ActivityAllAppsContainerView<*>) {
waveAlphabet(appsView)?.cancelScrub()
}
/**
* A letter header. It carries its letter so that the adapter's diffing notices when the
* header at a position changes, for example after an app is installed or removed.
@@ -1,5 +1,6 @@
package app.flexera.drawer
import android.os.SystemClock
import android.view.MotionEvent
import android.view.ViewConfiguration
import app.lawnchair.preferences.PreferenceManager
@@ -16,7 +17,10 @@ import kotlin.math.abs
* touch. Nothing is drawn on the home screen; the letters appear with the drawer.
*
* The edge is shared with page swipes, taps and item drags, so this claims a touch only once it
* has clearly moved up or down, and never while an item is being dragged. It is off by default.
* has clearly moved up or down, and never while an item is being dragged. It also leaves alone a
* touch on an icon that the owner gave a swipe up or down of its own, as the home screen's other
* swipes do. A touch that lifts again within [FlexeraDrawer.MIN_SCRUB_MS] was a flick, not a
* scrub, and opens the plain list. The setting is on unless the owner switches it off.
*/
class FlexeraEdgeScrubController(private val launcher: Launcher) : TouchController {
@@ -26,6 +30,7 @@ class FlexeraEdgeScrubController(private val launcher: Launcher) : TouchControll
/** The current touch started on the edge and may still turn into a scrub. */
private var candidate = false
private var scrubbing = false
private var scrubStartTime = 0L
private var downX = 0f
private var downY = 0f
@@ -48,7 +53,12 @@ class FlexeraEdgeScrubController(private val launcher: Launcher) : TouchControll
dy > touchSlop && dy > dx * VERTICAL_BIAS -> {
candidate = false
scrubbing = true
launcher.stateManager.goToState(LauncherState.ALL_APPS)
scrubStartTime = SystemClock.uptimeMillis()
// The drawer starts opening and the alphabet takes the finger in the same
// moment. Opening comes first: with Remember position on, its start notes
// where the list stands, which a flick sends it back to, so the note must
// be taken before the scrub's first jump.
openDrawer()
FlexeraDrawer.scrubFromSwipe(launcher.appsView, launcher.dragLayer, ev)
return true
}
@@ -68,23 +78,55 @@ class FlexeraEdgeScrubController(private val launcher: Launcher) : TouchControll
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
scrubbing = false
FlexeraDrawer.endScrubFromSwipe(launcher.appsView)
if (SystemClock.uptimeMillis() - scrubStartTime < FlexeraDrawer.MIN_SCRUB_MS) {
// A flick up that happened to start on the edge: open the plain list.
FlexeraDrawer.cancelScrubFromSwipe(launcher.appsView)
} else {
FlexeraDrawer.endScrubFromSwipe(launcher.appsView)
}
}
}
return true
}
/**
* Opens the drawer in [OPEN_MS]. Asking the state manager to go there would take the
* drawer's own 600 ms, far too slow for a list that the finger is already scrubbing.
*/
private fun openDrawer() {
launcher.stateManager.createAnimationToNewWorkspace(LauncherState.ALL_APPS, OPEN_MS).apply {
dispatchOnStart()
start()
}
}
private fun canStart(ev: MotionEvent): Boolean =
prefs.flexeraScrubFromHome.get() &&
(ev.edgeFlags and Utilities.EDGE_NAV_BAR) == 0 &&
launcher.isInState(LauncherState.NORMAL) &&
AbstractFloatingView.getTopOpenView(launcher) == null &&
FlexeraDrawer.isOnHomeEdge(launcher.appsView, launcher.dragLayer, ev)
FlexeraDrawer.isOnHomeEdge(launcher.appsView, launcher.dragLayer, ev) &&
!isOnIconWithVerticalSwipe(ev)
/**
* True when [ev] lands on a home-screen icon that has a swipe up or down of its own. An icon
* in the column next to the edge lies partly on it, and a swipe there is still the icon's: a
* scrub would take the touch away from the icon before its swipe could run.
*/
private fun isOnIconWithVerticalSwipe(ev: MotionEvent): Boolean {
val workspace = launcher.workspace ?: return false
val coord = floatArrayOf(ev.x, ev.y)
launcher.dragLayer.mapCoordInSelfToDescendant(workspace, coord)
return workspace.isTouchOnIconWithSwipeGesture(coord[0], coord[1], true)
}
override fun dump(): String = "FlexeraEdgeScrubController candidate=$candidate scrubbing=$scrubbing"
private companion object {
/** A slide counts as vertical when it has moved this many times further up or down than sideways. */
const val VERTICAL_BIAS = 2f
/** How long the drawer takes to open under a scrub; the same as after swipe up and hold. */
const val OPEN_MS = 120L
}
}
@@ -0,0 +1,252 @@
package app.flexera.drawer
import android.app.Notification
import android.os.Build
import android.os.Process
import android.service.notification.NotificationListenerService.Ranking
import android.service.notification.NotificationListenerService.RankingMap
import android.service.notification.StatusBarNotification
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.TextUtils
import android.text.style.CharacterStyle
import android.text.style.RelativeSizeSpan
import android.text.style.UpdateAppearance
import android.view.accessibility.AccessibilityNodeInfo
import app.lawnchair.preferences.PreferenceManager
import com.android.launcher3.BubbleTextView
import com.android.launcher3.R
import com.android.launcher3.dot.DotInfo
import com.android.launcher3.model.data.ItemInfo
import java.util.concurrent.ConcurrentHashMap
import kotlin.math.roundToInt
/**
* Inline notification previews (PRD AD-11): in the drawer list, a row whose app has
* notifications shows the latest one under the app name, smaller and dimmer.
*
* It rides on what Launcher3 already has for notification dots. The same notification access
* feeds it, the same filter decides which notifications count, and a row is refreshed whenever
* its dot is. Without notification access there are no dots and no previews.
*
* It never shows what Android itself would hide. Of another profile's notification, a work
* profile's for one, it shows only what Android shows while that profile is locked, and it shows
* nothing for an app that is paused, or whose profile is.
*
* Launcher3's listener hands each notification to [onPosted], [onRemoved] or [onFullRefresh] on
* its worker thread; the rows read the stored text on the main thread through [apply].
*/
object FlexeraNotificationPreview {
private class Preview(val text: String, val postTime: Long)
/** What [apply] put on a row: the row's whole text, and the preview line in it. */
private class Shown(val label: CharSequence, val preview: String)
/** Latest text per notification key, for the notifications that currently show a dot. */
private val previews = ConcurrentHashMap<String, Preview>()
/** For reading a notification's ranking. Only the listener's worker thread uses it. */
private val ranking = Ranking()
private const val MAX_LENGTH = 140
/** The preview line's text size as a share of the app name's. */
private const val TEXT_SCALE = 0.78f
/** The preview line's opacity as a share of the app name's, so the name stays the stronger. */
private const val TEXT_ALPHA = 0.7f
@JvmStatic
fun onPosted(sbn: StatusBarNotification, rankings: RankingMap?) {
val text = previewText(sbn, rankings)
if (text == null) previews.remove(sbn.key) else previews[sbn.key] = Preview(text, sbn.postTime)
}
@JvmStatic
fun onRemoved(sbn: StatusBarNotification) {
previews.remove(sbn.key)
}
@JvmStatic
fun onFullRefresh(active: List<StatusBarNotification>, rankings: RankingMap?) {
previews.clear()
active.forEach { onPosted(it, rankings) }
}
/**
* Sets [icon]'s text for [info]: the app name, plus the latest notification under it when
* [dot] says the app has any. Called for drawer rows whenever their dot state is applied, and
* when a notification changes without changing its app's dot.
*/
@JvmStatic
fun apply(icon: BubbleTextView, info: ItemInfo, dot: DotInfo?) {
// Only rows of the drawer list have room for a second line.
if (icon.getTag(R.id.flexera_drawer_row) == null) return
val name = info.title ?: return
// Android hides the notifications of a paused app (Focus mode pauses some) and of a paused
// work profile. The row's app shows as disabled then.
val preview = if (dot != null && !info.isDisabled && isEnabled(icon)) latest(dot) else null
val shown = shownOn(icon)
if (preview == null) {
if (icon.getTag(R.id.flexera_notification_preview) == null) return
// The row was showing a preview, for this app earlier or for another app before the
// view was reused. Back to the plain one-line name.
icon.setTag(R.id.flexera_notification_preview, null)
if (icon.minLines != 1 || icon.maxLines != 1) icon.setLines(1)
if (shown != null) {
// Binding a row puts its name back already, so this is a row that stays bound.
// BubbleTextView sets the name its own way, adding an archived app's cloud mark
// for one. That also resets the description, which can still say how many
// notifications the app has, or how far its download is, so the description is
// kept.
val description = icon.contentDescription
icon.applyLabel(info)
icon.contentDescription = description
}
return
}
val label = label(icon, name, preview)
// The same text again would still lay the list out and redraw the row, and a notification
// that is updated every second, as a download's is, would keep doing that for nothing.
if (shown != null && TextUtils.equals(shown.label, label)) return
show(icon, label, preview)
}
/**
* Fits the app name to the row's new width. A row bound before its first layout has no width
* yet, so a long name was left whole, and it wraps onto the preview's line until this runs.
*/
@JvmStatic
fun onSizeChanged(icon: BubbleTextView) {
val shown = shownOn(icon) ?: return
val name = (icon.tag as? ItemInfo)?.title ?: return
val label = label(icon, name, shown.preview)
if (!TextUtils.equals(shown.label, label)) show(icon, label, shown.preview)
}
/** Adds the preview line to the row's description, which is what screen readers read out. */
@JvmStatic
fun describe(icon: BubbleTextView, node: AccessibilityNodeInfo) {
val shown = shownOn(icon) ?: return
// Without a description they read the row's text, which has the preview in it already.
val description = node.contentDescription
if (description.isNullOrEmpty()) return
node.contentDescription = icon.context.getString(
R.string.flexera_notification_preview_description,
description,
shown.preview,
)
}
/**
* What [apply] put on [icon], while it is still there. BubbleTextView puts the plain name back
* whenever it binds the row, and that leaves the mark of an earlier preview behind.
*/
private fun shownOn(icon: BubbleTextView): Shown? =
(icon.getTag(R.id.flexera_notification_preview) as? Shown)
?.takeIf { TextUtils.equals(icon.text, it.label) }
private fun show(icon: BubbleTextView, label: CharSequence, preview: String) {
// Setting the number of lines always lays the row out again, so only a row that had the
// other number gets it.
if (icon.minLines != 2 || icon.maxLines != 2) icon.setLines(2)
icon.ellipsize = TextUtils.TruncateAt.END
icon.text = label
icon.setTag(R.id.flexera_notification_preview, Shown(label, preview))
}
/** The app name on the first line, the preview under it. */
private fun label(icon: BubbleTextView, name: CharSequence, preview: String): CharSequence {
// Keep a long app name on its own line, so the preview is never pushed off the row.
val width = icon.width - icon.compoundPaddingLeft - icon.compoundPaddingRight
val firstLine = if (width > 0) {
TextUtils.ellipsize(name, icon.paint, width.toFloat(), TextUtils.TruncateAt.END)
} else {
name
}
val label = SpannableStringBuilder(firstLine).append('\n')
val start = label.length
label.append(preview)
label.setSpan(RelativeSizeSpan(TEXT_SCALE), start, label.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
label.setSpan(DimSpan(), start, label.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
return label
}
private fun isEnabled(icon: BubbleTextView): Boolean =
PreferenceManager.getInstance(icon.context).flexeraNotificationPreviews.get()
/** The text of the newest of the app's notifications that has any text. */
private fun latest(dot: DotInfo): String? {
var newest: Preview? = null
for (key in dot.notificationKeys) {
val candidate = previews[key.notificationKey] ?: continue
if (newest == null || candidate.postTime > newest.postTime) newest = candidate
}
return newest?.text
}
/** "Title: text" in one line, or whichever of the two the notification has. */
private fun previewText(sbn: StatusBarNotification, rankings: RankingMap?): String? {
val notification = if (sbn.user == Process.myUserHandle()) {
sbn.notification
} else {
lockedVersion(sbn, rankings)
}
val extras = notification?.extras ?: return null
val title = extras.getCharSequence(Notification.EXTRA_TITLE).oneLine()
val text = extras.getCharSequence(Notification.EXTRA_TEXT).oneLine()
val combined = when {
title.isEmpty() -> text
text.isEmpty() -> title
else -> "$title: $text"
}
return combined.take(MAX_LENGTH).ifEmpty { null }
}
/**
* The most of another profile's notification, a work profile's for one, that Android shows
* while that profile is locked: nothing if the notification is secret, the version its app
* made for public view if the content is hidden, and the whole notification otherwise. The
* launcher cannot tell whether that profile is locked at the moment, so a preview never shows
* more than this.
*/
private fun lockedVersion(sbn: StatusBarNotification, rankings: RankingMap?): Notification? {
val notification = sbn.notification
// Android sums up the profile's lock screen settings, its admin's rules and the channel's
// setting in the ranking. Apps can read that from Android 12; before, take it that the
// content is hidden.
val override = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
rankings?.getRanking(sbn.key, ranking) == true
) {
ranking.lockscreenVisibilityOverride
} else {
Notification.VISIBILITY_PRIVATE
}
return when {
notification.visibility == Notification.VISIBILITY_SECRET ||
override == Notification.VISIBILITY_SECRET -> null
override == Notification.VISIBILITY_PRIVATE -> notification.publicVersion
// Without an override, the profile's settings let it show the content while locked,
// even that of a notification its app left private, which is the default.
else -> notification
}
}
private fun CharSequence?.oneLine(): String =
this?.toString()?.replace('\n', ' ')?.trim().orEmpty()
/**
* Draws the preview line in the row's own text colour, at [TEXT_ALPHA] of its opacity. A fixed
* colour would stay when Launcher3 fades or hides the row's text, as it does under an open
* long-press menu; this line fades with the name.
*/
private class DimSpan : CharacterStyle(), UpdateAppearance {
override fun updateDrawState(paint: TextPaint) {
paint.alpha = (paint.alpha * TEXT_ALPHA).roundToInt()
}
}
}
+82
View File
@@ -0,0 +1,82 @@
package app.flexera.drawer
import android.view.View
import androidx.lifecycle.lifecycleScope
import app.lawnchair.LawnchairLauncher
import app.lawnchair.preferences2.PreferenceManager2
import app.lawnchair.preferences2.firstCached
import com.android.launcher3.LauncherSettings.Favorites.CONTAINER_ALL_APPS
import com.android.launcher3.LauncherSettings.Favorites.ITEM_TYPE_APPLICATION
import com.android.launcher3.R
import com.android.launcher3.model.data.ItemInfo
import com.android.launcher3.pm.UserCache
import com.android.launcher3.popup.SystemShortcut
import com.android.launcher3.util.ComponentKey
import com.android.launcher3.views.Snackbar
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
/**
* "Hide app" in the menu a long press on an app opens in the app list.
*
* It puts the app on the hidden list Lawnchair already has: the one the app list and its search
* leave out, kept under Settings > App drawer > Hidden apps, where an app is brought back. Before
* this, hiding meant going through that settings page or through Customize. A message with Undo
* follows, because the app is gone from the list the moment it is hidden.
*/
object HideApp {
/**
* Offered for apps in the app list only: hiding does nothing to an icon on the home screen,
* so offering it there would promise something else. Not for apps in Private Space either:
* the list's Private Space section ignores the hidden list, so the app would stay in view
* after the message said it was hidden; locking the space is what hides its apps. Not offered
* while the home screen is locked against changes, like Customize and Uninstall.
*/
@JvmField
val SHORTCUT = SystemShortcut.Factory { launcher: LawnchairLauncher, itemInfo: ItemInfo, originalView: View ->
val component = itemInfo.targetComponent
when {
itemInfo.container != CONTAINER_ALL_APPS -> null
itemInfo.itemType != ITEM_TYPE_APPLICATION || component == null -> null
UserCache.INSTANCE.get(launcher).getUserInfo(itemInfo.user).isPrivate -> null
PreferenceManager2.getInstance(launcher).lockHomeScreen.firstCached() -> null
else -> Shortcut(launcher, itemInfo, originalView, ComponentKey(component, itemInfo.user))
}
}
private class Shortcut(
launcher: LawnchairLauncher,
itemInfo: ItemInfo,
originalView: View,
private val app: ComponentKey,
) : SystemShortcut<LawnchairLauncher>(
R.drawable.ic_flexera_hide,
R.string.flexera_hide_app,
launcher,
itemInfo,
originalView,
) {
override fun onClick(view: View) {
val launcher = mTarget
val name = mItemInfo.title?.toString().orEmpty()
dismissTaskMenuView()
setHidden(launcher, app, hidden = true)
Snackbar.show(
launcher,
launcher.getString(R.string.flexera_app_hidden, name),
R.string.undo,
null,
) { setHidden(launcher, app, hidden = false) }
}
}
private fun setHidden(launcher: LawnchairLauncher, app: ComponentKey, hidden: Boolean) {
val hiddenApps = PreferenceManager2.getInstance(launcher).hiddenApps
val key = app.toString()
launcher.lifecycleScope.launch {
val now = hiddenApps.get().first()
hiddenApps.set(if (hidden) now + key else now - key)
}
}
}
@@ -3,16 +3,20 @@ package app.flexera.drawer
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Configuration
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface
import android.graphics.fonts.FontStyle
import android.os.Build
import android.os.Bundle
import android.view.HapticFeedbackConstants
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.animation.DecelerateInterpolator
import android.widget.SeekBar
@@ -24,6 +28,8 @@ import androidx.core.view.doOnNextLayout
import androidx.customview.widget.ExploreByTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import app.lawnchair.preferences2.PreferenceManager2
import app.lawnchair.preferences2.firstCached
import com.android.launcher3.R
import com.android.launcher3.allapps.ActivityAllAppsContainerView
import kotlin.math.abs
@@ -35,16 +41,22 @@ import kotlin.math.roundToInt
/**
* The wave alphabet: a strip of letters down one edge of the drawer (PRD AD-4 to AD-6).
*
* Only letters that have apps are shown. Touching the strip and sliding along it jumps the list
* Only letters that have apps are shown, under a magnifier that stands for the search field at
* the top of the list. Touching the strip and sliding along it jumps the list
* to the letter under the finger, with a haptic tick on every change. While the finger is down,
* the letters near it bulge away from the edge in a wave, and the wave reaches further the
* further the finger moves in from the edge, so the current letter always sits beside the thumb
* instead of under it.
* the letters near it bulge away from the edge in a wide wave that curves around the thumb.
* The wave's peak, where the current letter is, stays a thumb's width beyond the finger however
* far in from the edge the finger is, and just beyond the peak a bubble shows that letter
* large. The look follows Niagara Launcher's alphabet, the owner's reference.
*
* The strip sits on the right edge unless the owner moves it to the left (PRD AD-15).
* The strip sits on the right edge unless the owner moves it to the left (PRD AD-15), and low
* on that edge, with its letters close together, so that the first letter is as easy to reach
* as the last.
*
* The view covers the whole drawer so it has room to draw the wave, but it only takes touches
* that start on the strip; every other touch falls through to the list underneath.
* that start on the strip; every other touch falls through to the list underneath. The very
* edge is also where Android starts its Back swipe. The strip leaves that to Android: a touch
* there becomes a scrub only once it moves up or down or rests, and a sideways swipe goes back.
*
* [beginScrub], [moveScrub] and [endScrub] are public so that another gesture, such as swipe up
* and hold from the home screen (PRD AD-17), can hand its touch over to the alphabet.
@@ -58,7 +70,8 @@ class WaveAlphabetView(
private val appsView: ActivityAllAppsContainerView<*>,
) : View(context) {
private data class Letter(val label: String, val adapterPosition: Int)
/** One stop on the strip: a letter, or the search field at the top of the list ([isSearch]). */
private data class Letter(val label: String, val adapterPosition: Int, val isSearch: Boolean = false)
private val res = context.resources
private val onLeft = FlexeraDrawer.alphabetOnLeft(context)
@@ -66,10 +79,15 @@ class WaveAlphabetView(
private val edgeInset = res.getDimension(R.dimen.flexera_wave_edge_inset)
private val maxSpacing = res.getDimension(R.dimen.flexera_wave_max_spacing)
private val verticalMargin = res.getDimension(R.dimen.flexera_wave_vertical_margin)
private val bottomOffset = res.getDimension(R.dimen.flexera_wave_bottom_offset)
private val fingerGap = res.getDimension(R.dimen.flexera_wave_finger_gap)
private val minReach = res.getDimension(R.dimen.flexera_wave_min_reach)
private val waveWidth = res.getDimension(R.dimen.flexera_wave_width)
private val farMargin = res.getDimension(R.dimen.flexera_wave_far_margin)
private val letterSize = res.getDimension(R.dimen.flexera_wave_letter_size)
private val headerHeight = FlexeraDrawer.headerHeight(context)
private val homeTouchWidth = res.getDimension(R.dimen.flexera_wave_home_touch_width)
private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop
/** The section name Launcher3 gives the work profile's info card, an "i" in a circle. */
private val workInfoSection = res.getString(R.string.work_profile_edu_section)
@@ -89,13 +107,57 @@ class WaveAlphabetView(
FlexeraDrawer.TEXT_SHADOW_COLOR,
)
}
private val boldTypeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
// Regular letters, and bold for the selected one and the bubble's. Android's Bold text
// setting makes both heavier, like the app names beside them (see withBoldText).
private var regularTypeface = withBoldText(Typeface.DEFAULT)
private var boldTypeface = withBoldText(Typeface.create(Typeface.DEFAULT, Typeface.BOLD))
// For the magnifier: one stroke with the letters' shadow, one without for the bubble.
private val markPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeCap = Paint.Cap.ROUND
setShadowLayer(
res.getDimension(R.dimen.flexera_drawer_text_shadow_radius),
0f,
res.getDimension(R.dimen.flexera_drawer_text_shadow_dy),
FlexeraDrawer.TEXT_SHADOW_COLOR,
)
}
private val plainMarkPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeCap = Paint.Cap.ROUND
}
// The bubble that shows the selected letter large, beyond the wave's peak: a light disc
// with a dark letter, the one thing on the dark drawer that is not white on dark.
private val bubbleRadius = res.getDimension(R.dimen.flexera_wave_bubble_radius)
private val bubbleGap = res.getDimension(R.dimen.flexera_wave_bubble_gap)
private val bubbleTextSize = res.getDimension(R.dimen.flexera_wave_bubble_text_size)
private val bubbleEdgeMargin = res.getDimension(R.dimen.flexera_wave_bubble_edge_margin)
private val bubblePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = BUBBLE_COLOR
setShadowLayer(
res.getDimension(R.dimen.flexera_wave_bubble_shadow_radius),
0f,
res.getDimension(R.dimen.flexera_drawer_text_shadow_dy),
BUBBLE_SHADOW_COLOR,
)
}
private val bubbleTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = BUBBLE_TEXT_COLOR
textAlign = Paint.Align.CENTER
typeface = boldTypeface
}
private var letters: List<Letter> = emptyList()
private var letterYs = FloatArray(0)
private var stripTop = 0f
private var stripBottom = 0f
/** How tall the edge was that the letters were last placed on: this view's height, or the one it will have. */
private var edgeHeight = 0
/** Letter size at rest. Smaller than [letterSize] when a large font would make letters collide. */
private var restingLetterSize = letterSize
private var layoutDirty = true
@@ -106,11 +168,25 @@ class WaveAlphabetView(
private var fingerY = 0f
private var selected = -1
// A touch that began on the edge strip Android uses for Back, before it is known whether
// it is a scrub: where it went down, where it is now, and the timer that makes a touch
// at rest a scrub.
private var waitingForBack = false
private var downX = 0f
private var downY = 0f
private var lastX = 0f
private var lastY = 0f
private val scrubAfterRest = Runnable {
if (waitingForBack) {
waitingForBack = false
beginScrub(lastX, lastY)
}
}
/** 0 when the strip is at rest, 1 when the wave is fully out. Animated on touch down and up. */
private var press = 0f
private var pressAnimator: ValueAnimator? = null
private val exclusionRect = Rect()
private val location = IntArray(2)
private val otherLocation = IntArray(2)
@@ -132,22 +208,33 @@ class WaveAlphabetView(
for (section in sections) {
val label = section.sectionName?.toString().orEmpty()
// Launcher3 repeats the last section once more so its own scroller can reach the
// bottom, Private Space uses a long badge string, and the work profile's info card
// has a section of its own; none of these is a letter.
if (label.isEmpty() || label.length > 2 || label == workInfoSection) continue
// bottom, Private Space names its sections with a badge image drawn over a single
// space, and the work profile's info card has a section of its own; none of these
// is a letter, and neither is a name too long for the strip.
if (label.isBlank() || label.length > 2 || label == workInfoSection) continue
if (result.isNotEmpty() && result.last().label == label) continue
result.add(Letter(label, section.position))
}
// The search field is the list's first row in all but name, and scrolls away with it.
// A magnifier above the letters says it is there and jumps back to it.
if (result.isNotEmpty() && hasSearchField()) result.add(0, Letter("", 0, isSearch = true))
return result
}
private fun hasSearchField(): Boolean =
!PreferenceManager2.getInstance(context).hideAppDrawerSearchBar.firstCached()
private fun refreshIfChanged() {
// Any new layout may have moved the list; keep the search field riding on it. A layout
// also follows new insets, which do not always change this view's size, so the letters
// are placed afresh when they are next needed.
FlexeraDrawer.moveSearchFieldWithList(appsView)
layoutDirty = true
val searching = appsView.isSearching
val fresh = readLetters()
if (fresh != letters || searching != wasSearching) {
letters = fresh
wasSearching = searching
layoutDirty = true
accessibility.invalidateRoot()
invalidate()
}
@@ -156,47 +243,95 @@ class WaveAlphabetView(
private fun computeLayout() {
layoutDirty = false
// The strip runs from where the list starts down to the navigation bar.
var top = 0f
appsView.activeRecyclerView?.let { rv ->
getLocationInWindow(location)
rv.getLocationInWindow(otherLocation)
top = (otherLocation[1] - location[1]).toFloat().coerceAtLeast(0f)
// The strip runs from where the list starts down to the navigation bar. Scrub from home
// begins a scrub while the drawer is still hidden, when its layout is missing (it has
// not been shown since the launcher started) or may be out of date (the screen has
// turned, or the insets have changed). The letters are then placed where they will be
// once it is shown, measured like the finger from where this view was last laid out.
var edgeTop = 0
edgeHeight = height
if (appsView.visibility != VISIBLE || width == 0 || height == 0) {
(appsView.parent as? View)?.let { dragLayer ->
val frame = expectedFrame(dragLayer)
edgeTop = frame.top - (top + appsView.top)
edgeHeight = frame.height()
}
}
val bottomInset = rootWindowInsets?.systemWindowInsetBottom ?: 0
val availableTop = top + verticalMargin
val availableBottom = height - bottomInset - verticalMargin
val strip = placeStrip(edgeHeight.toFloat(), listTop(), bottomInset())
val count = letters.size
letterYs = FloatArray(count)
restingLetterSize = letterSize
if (count == 0 || availableBottom <= availableTop) {
if (strip == null) {
stripTop = 0f
stripBottom = 0f
} else {
val spacing = min(maxSpacing, (availableBottom - availableTop) / count)
val blockHeight = spacing * count
// Few letters: keep the block in the middle of the edge, where a thumb rests.
stripTop = availableTop + (availableBottom - availableTop - blockHeight) / 2f
stripBottom = stripTop + blockHeight
stripTop = edgeTop + strip.top
stripBottom = stripTop + strip.spacing * count
for (i in 0 until count) {
letterYs[i] = stripTop + spacing * (i + 0.5f)
letterYs[i] = stripTop + strip.spacing * (i + 0.5f)
}
// With a large system font and a full alphabet, letters at their set size would
// overlap their neighbours; shrink them to fit their slot.
restingLetterSize = min(letterSize, spacing * MAX_LETTER_SHARE_OF_SLOT)
restingLetterSize = min(letterSize, strip.spacing * MAX_LETTER_SHARE_OF_SLOT)
}
// The strip sits where Android's back swipe starts. A home app may reserve the whole
// edge, so the scrub never turns into Back.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (onLeft) {
exclusionRect.set(0, stripTop.toInt(), touchWidth.toInt(), stripBottom.toInt())
} else {
exclusionRect.set((width - touchWidth).toInt(), stripTop.toInt(), width, stripBottom.toInt())
}
systemGestureExclusionRects = listOf(exclusionRect)
}
// The strip does not reserve the edge for itself: Android's Back swipe starts there,
// and the owner closes the drawer with it. The two share the edge by direction, see
// onTouchEvent.
}
/** Where the letters lie along an edge: the first one's slot starts at [top], and each slot is [spacing] tall. */
private class Placement(val top: Float, val spacing: Float)
/**
* Places the letters on an edge [height] tall, whose list's rows start [listTop] down it,
* above a navigation bar [bottomInset] tall; null when there are no letters or no room for
* them. The drawer places its letters with this, and scrub from home uses it to find where
* they will be while the drawer is closed.
*/
private fun placeStrip(height: Float, listTop: Float, bottomInset: Float): Placement? {
val count = letters.size
val availableTop = listTop + verticalMargin
val availableBottom = height - bottomInset - verticalMargin
if (count == 0 || availableBottom <= availableTop) return null
val spacing = min(maxSpacing, (availableBottom - availableTop) / count)
val blockHeight = spacing * count
// The stretch of edge a whole alphabet would take sits low, where a thumb reaches
// without stretching: its end a little above the navigation bar, its start
// wherever that puts it. The letters there are sit in the middle of that stretch,
// so that a short alphabet is in the middle of the thumb's reach and not at its
// lower end. Only letters that need the whole edge reach up to where the list starts.
val fullCount = FULL_ALPHABET + if (letters.first().isSearch) 1 else 0
val zoneHeight = max(blockHeight, min(availableBottom - availableTop, spacing * fullCount))
val zoneBottom = availableBottom - min(bottomOffset, availableBottom - availableTop - zoneHeight)
return Placement(zoneBottom - zoneHeight + (zoneHeight - blockHeight) / 2f, spacing)
}
/** Where the list's rows start, in this view's coordinates: below its top padding, which holds the search field. */
private fun listTop(): Float {
val rv = appsView.activeRecyclerView ?: return 0f
getLocationInWindow(location)
rv.getLocationInWindow(otherLocation)
return (otherLocation[1] - location[1] + rv.paddingTop).toFloat().coerceAtLeast(0f)
}
private fun bottomInset(): Float = (rootWindowInsets?.systemWindowInsetBottom ?: 0).toFloat()
/**
* Where this view will be in [dragLayer], the drawer's parent, once the drawer is shown: the
* drawer fills the drag layer within its margins, and this view fills the drawer within its
* padding. The margins and the padding follow the insets while the drawer is hidden; the
* drawer's layout does not.
*/
private fun expectedFrame(dragLayer: View): Rect {
val margins = appsView.layoutParams as? ViewGroup.MarginLayoutParams
return Rect(
(margins?.leftMargin ?: 0) + appsView.paddingLeft,
(margins?.topMargin ?: 0) + appsView.paddingTop,
dragLayer.width - (margins?.rightMargin ?: 0) - appsView.paddingRight,
dragLayer.height - (margins?.bottomMargin ?: 0) - appsView.paddingBottom,
)
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
@@ -212,10 +347,21 @@ class WaveAlphabetView(
override fun onDetachedFromWindow() {
viewTreeObserver.removeOnGlobalLayoutListener(layoutListener)
stopWaitingForBack()
pressAnimator?.cancel()
super.onDetachedFromWindow()
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
// Android's Bold text setting is part of the configuration; the letters follow a new
// one as a TextView does.
regularTypeface = withBoldText(Typeface.DEFAULT)
boldTypeface = withBoldText(Typeface.create(Typeface.DEFAULT, Typeface.BOLD))
bubbleTextPaint.typeface = boldTypeface
invalidate()
}
// ---- Drawing -----------------------------------------------------------------------------
override fun onDraw(canvas: Canvas) {
@@ -225,30 +371,37 @@ class WaveAlphabetView(
// Where the letters rest, and which way "away from the edge" points.
val baseX = if (onLeft) edgeInset else width - edgeInset
val inward = if (onLeft) 1f else -1f
// The wave's peak sits a fixed gap before the finger, so it reaches further out the
// further the finger is from the edge.
// The wave's peak sits a fixed gap beyond the finger, on the side away from the edge,
// which is the side the thumb leaves uncovered. So the wave reaches further out the
// further the finger is from the edge, up to nearly the whole width of the screen.
val fingerDistance = (fingerX - baseX) * inward
val maxReach = width * 0.7f
val maxReach = max(minReach + 1f, width - edgeInset - farMargin)
val fullReach = (fingerDistance + fingerGap).coerceIn(minReach, maxReach)
val reach = fullReach * press
// The wave is wide: several letters on each side of the finger ride it, so they curve
// around the whole thumb and stay readable above and below it. A wave that reaches
// far out is wider still, which keeps its shape.
val spread = max(waveWidth, fullReach * WAVE_WIDTH_SHARE_OF_REACH)
// Darken the list under the wave where its letters cross icons and names. From the
// right edge that only happens once the wave reaches well into the screen, as it does
// after swipe up and hold; from the left edge the icons sit right beside the strip.
// Darken the list a little while scrubbing, so the eye goes to the letters, and more
// where the wave lies over icons and names: from the right edge that is once it reaches
// well into the screen, as after swipe up and hold; from the left edge it is at once.
if (press > 0f) {
val overList = if (onLeft) 1f else ((fullReach - minReach) / (maxReach - minReach)).coerceIn(0f, 1f)
val reachShare = ((fullReach - minReach) / (maxReach - minReach)).coerceIn(0f, 1f)
val overList = if (onLeft) 1f else SCRUB_DIM_AT_EDGE + (1f - SCRUB_DIM_AT_EDGE) * reachShare
val dim = (SCRUB_DIM * press * overList * 255).toInt()
if (dim > 0) canvas.drawColor(Color.argb(dim, 0, 0, 0))
}
for (i in letters.indices) {
val y = letterYs[i]
val nearness = if (press > 0f) bell((y - fingerY) / waveWidth) else 0f
val nearness = if (press > 0f) bell((y - fingerY) / spread) else 0f
val isSelected = i == selected && press > 0f
val scale = 1f + (if (isSelected) SELECTED_GROWTH else NEAR_GROWTH) * nearness * press
paint.textSize = restingLetterSize * scale
paint.typeface = if (isSelected) boldTypeface else Typeface.DEFAULT
// Letters keep their size in the wave, so close neighbours never collide; the
// selected one is bold and a touch larger. Its large copy is in the bubble.
paint.textSize = restingLetterSize * (1f + (if (isSelected) SELECTED_GROWTH * press else 0f))
paint.typeface = if (isSelected) boldTypeface else regularTypeface
paint.color = if (isSelected) {
activeColor
} else {
@@ -257,30 +410,118 @@ class WaveAlphabetView(
val x = baseX + inward * reach * nearness
// Centre the glyph on the letter's line.
val baseline = y - (paint.descent() + paint.ascent()) / 2f
canvas.drawText(letters[i].label, x, baseline, paint)
if (letters[i].isSearch) {
drawSearchMark(canvas, x, y, paint.textSize * SEARCH_MARK_IN_LETTER_SIZES, paint.color, true)
} else {
val baseline = y - (paint.descent() + paint.ascent()) / 2f
canvas.drawText(letters[i].label, x, baseline, paint)
}
}
// The selected letter, large, in a bubble just beyond the wave's peak and level with
// the finger: the furthest thing from the thumb, so the thumb cannot hide it.
if (press > 0f && selected in letters.indices) {
val edgeRoom = bubbleRadius + bubbleEdgeMargin
val cx = (baseX + inward * (reach + bubbleGap * press)).coerceIn(edgeRoom, max(edgeRoom, width - edgeRoom))
val alpha = (press * 255).toInt()
bubblePaint.alpha = alpha
canvas.drawCircle(cx, fingerY, bubbleRadius * press, bubblePaint)
bubbleTextPaint.alpha = alpha
bubbleTextPaint.textSize = bubbleTextSize * press
if (letters[selected].isSearch) {
drawSearchMark(canvas, cx, fingerY, bubbleTextPaint.textSize, bubbleTextPaint.color, false)
} else {
val baseline = fingerY - (bubbleTextPaint.descent() + bubbleTextPaint.ascent()) / 2f
canvas.drawText(letters[selected].label, cx, baseline, bubbleTextPaint)
}
}
}
/**
* Draws a magnifier, the mark for the search field, [size] across and centred on
* ([cx], [cy]): a ring with a short handle. Drawn by hand so that its line weight
* matches letters of any size.
*/
private fun drawSearchMark(canvas: Canvas, cx: Float, cy: Float, size: Float, color: Int, shadow: Boolean) {
val stroke = if (shadow) markPaint else plainMarkPaint
stroke.color = color
stroke.strokeWidth = size * 0.12f
val radius = size * 0.29f
val ringX = cx - size * 0.09f
val ringY = cy - size * 0.09f
canvas.drawCircle(ringX, ringY, radius, stroke)
val rim = radius * 0.7071f
val handle = size * 0.27f
canvas.drawLine(ringX + rim, ringY + rim, ringX + rim + handle, ringY + rim + handle, stroke)
}
private fun bell(distance: Float): Float = exp(-distance * distance)
/**
* [typeface] made heavier by Android's Bold text setting (Android 12 and newer), as Android
* does for the text of a TextView but not for text drawn on a canvas.
*/
private fun withBoldText(typeface: Typeface): Typeface {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return typeface
val adjustment = res.configuration.fontWeightAdjustment
if (adjustment == 0 || adjustment == Configuration.FONT_WEIGHT_ADJUSTMENT_UNDEFINED) return typeface
val weight = (typeface.weight + adjustment).coerceIn(FontStyle.FONT_WEIGHT_MIN, FontStyle.FONT_WEIGHT_MAX)
return Typeface.create(typeface, weight, typeface.isItalic)
}
// ---- Touch -------------------------------------------------------------------------------
/** True when a touch at this point, in this view's coordinates, starts a scrub. */
fun isOnStrip(x: Float, y: Float): Boolean =
appsView.isInAllApps && !appsView.isSearching && isOnStripBand(x, y)
/** True when this point lies on the band along the edge that the letters occupy. */
fun isOnStripBand(x: Float, y: Float): Boolean = isOnBand(x, y, touchWidth)
/**
* True when this point lies on the band along the edge that the letters occupy, whether or
* not the drawer is open. Scrub from home (PRD AD-10) asks this while the drawer is closed.
* The same for the home screen, where the band is narrower because nothing shows it. The
* drawer is closed then: it may not have been laid out since the launcher started, or it
* was last laid out for another screen size or other insets. So the band is worked out
* afresh from the drag layer the drawer fills, with the same maths that places the letters.
*/
fun isOnStripBand(x: Float, y: Float): Boolean {
fun isOnHomeBand(x: Float, y: Float): Boolean {
// The letters are read afresh as well: a closed drawer lays its list out again only when
// it opens, so a change to the apps may bring no layout that reads them. When the
// launcher starts, its apps arrive after the home screen's first layout; without this
// the band would be missing until something else is laid out, and an app installed or
// removed later would leave it a slot too long or too short.
refreshIfChanged()
val dragLayer = appsView.parent as? View ?: return false
val frame = expectedFrame(dragLayer)
val strip = placeStrip(frame.height().toFloat(), listTop(), bottomInset()) ?: return false
// The point is measured from where this view was last laid out in the drag layer,
// which is the drag layer's corner until the drawer's first layout.
val dragX = x + left + appsView.left
val dragY = y + top + appsView.top
val onEdge = if (onLeft) dragX <= frame.left + homeTouchWidth else dragX >= frame.right - homeTouchWidth
val bandTop = frame.top + strip.top - verticalMargin
val bandBottom = frame.top + strip.top + strip.spacing * letters.size + verticalMargin
return onEdge && dragY >= bandTop && dragY <= bandBottom
}
private fun isOnBand(x: Float, y: Float, bandWidth: Float): Boolean {
if (layoutDirty) computeLayout()
if (letters.isEmpty()) return false
val onEdge = if (onLeft) x <= touchWidth else x >= width - touchWidth
val onEdge = if (onLeft) x <= bandWidth else x >= width - bandWidth
return onEdge && y >= stripTop - verticalMargin && y <= stripBottom + verticalMargin
}
/**
* True when a touch at [x] starts on the strip of edge where Android may begin its Back
* swipe. With three-button navigation there is no such strip.
*/
private fun isInBackSwipeZone(x: Float): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return false
@Suppress("DEPRECATION")
val insets = rootWindowInsets?.systemGestureInsets ?: return false
return if (onLeft) x < insets.left else x > width - insets.right
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.actionMasked) {
@@ -288,16 +529,50 @@ class WaveAlphabetView(
if (!isOnStrip(event.x, event.y)) return false
// Keep the drawer from scrolling or closing under the thumb.
parent?.requestDisallowInterceptTouchEvent(true)
beginScrub(event.x, event.y)
downX = event.x
downY = event.y
lastX = event.x
lastY = event.y
if (isInBackSwipeZone(event.x)) {
// This may be the start of Android's Back swipe, which moves sideways.
// Show nothing until the touch says which it is: a move up or down or a
// short rest is a scrub, a move sideways is left to Android.
waitingForBack = true
postDelayed(scrubAfterRest, REST_BEFORE_SCRUB_MS)
} else {
beginScrub(event.x, event.y)
}
return true
}
MotionEvent.ACTION_MOVE -> {
if (!scrubbing) return false
moveScrub(event.x, event.y)
lastX = event.x
lastY = event.y
if (waitingForBack) {
val dx = abs(event.x - downX)
val dy = abs(event.y - downY)
if (dy > touchSlop && dy >= dx) {
stopWaitingForBack()
beginScrub(event.x, event.y)
} else if (dx > touchSlop) {
// Sideways: Android takes the touch from here on, and with it Back.
stopWaitingForBack()
}
} else if (scrubbing) {
moveScrub(event.x, event.y)
}
return true
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
if (!scrubbing) return false
MotionEvent.ACTION_UP -> {
if (waitingForBack) {
// Down and up without moving: a tap on a letter.
stopWaitingForBack()
beginScrub(event.x, event.y)
}
endScrub()
return true
}
MotionEvent.ACTION_CANCEL -> {
stopWaitingForBack()
endScrub()
return true
}
@@ -305,6 +580,11 @@ class WaveAlphabetView(
return scrubbing
}
private fun stopWaitingForBack() {
waitingForBack = false
removeCallbacks(scrubAfterRest)
}
/** Starts a scrub with the finger at ([x], [y]) in this view's coordinates. */
fun beginScrub(x: Float, y: Float) {
refreshIfChanged()
@@ -316,9 +596,33 @@ class WaveAlphabetView(
moveScrub(x, y)
}
/**
* Ends a scrub that began with the drawer closed and undoes it: the list goes to where a
* drawer opened by a plain swipe stands, which is the top unless the owner has the drawer
* remember its place. For a scrub that turns out to have been started by mistake.
*
* The list is not asked where it stood before the scrub. A closed drawer has been told to
* go back to the top but lays its rows out again only when it opens, so until then the
* rows still report the place the drawer was left at.
*/
fun cancelScrub() {
if (!scrubbing) return
endScrub()
val rv = appsView.activeRecyclerView ?: return
rv.stopScroll()
if (PreferenceManager2.getInstance(context).rememberPosition.firstCached()) {
rv.restoreScrollPosition()
} else {
rv.scrollToTop()
}
}
/** Moves the finger of a scrub started with [beginScrub]. */
fun moveScrub(x: Float, y: Float) {
if (!scrubbing || letters.isEmpty()) return
// A scrub from home begins while the drawer is hidden. Once the drawer has been laid out,
// the finger is measured from this view's new place, and the letters are placed to match.
if (layoutDirty) computeLayout()
fingerX = x
fingerY = y.coerceIn(stripTop, stripBottom)
@@ -327,7 +631,7 @@ class WaveAlphabetView(
if (index != selected) {
selected = index
performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
scrollListTo(letters[index].adapterPosition)
scrollListTo(index)
}
invalidate()
}
@@ -341,10 +645,40 @@ class WaveAlphabetView(
val isScrubbing: Boolean get() = scrubbing
private fun scrollListTo(adapterPosition: Int) {
/**
* Brings the group of the letter at [index] to the middle of the screen, where the thumb
* is, instead of to the top: the group's middle on the list's middle, though a long group
* keeps its header in view. Near either end of the list the list simply stops at its end.
* The magnifier goes to the very top, where the search field is.
*/
private fun scrollListTo(index: Int) {
val rv = appsView.activeRecyclerView ?: return
val layoutManager = rv.layoutManager as? LinearLayoutManager ?: return
rv.stopScroll()
(rv.layoutManager as? LinearLayoutManager)?.scrollToPositionWithOffset(adapterPosition, 0)
val letter = letters[index]
if (letter.isSearch) {
layoutManager.scrollToPositionWithOffset(0, 0)
return
}
// The last letter's group runs to the end of the list, or to where Private Space starts
// if the list has it: the strip has no stop for Private Space, but its rows are not the
// letter's.
val groupEnd = letters.getOrNull(index + 1)?.adapterPosition
?: rv.apps?.fastScrollerSections
?.firstOrNull { it.position > letter.adapterPosition && it.sectionName.isNullOrBlank() }
?.position
?: rv.adapter?.itemCount
?: (letter.adapterPosition + 2)
val rows = (groupEnd - letter.adapterPosition - 1).coerceAtLeast(1)
val groupHeight = headerHeight + rows * FlexeraDrawer.rowHeight(context)
// Before the drawer is first shown its list has no height yet; it will be as tall as
// the edge the letters are placed on.
val listHeight = (if (rv.height > 0) rv.height else edgeHeight).toFloat()
val top = max(listHeight * GROUP_HIGHEST_TOP, listHeight * GROUP_MIDDLE - groupHeight / 2f)
layoutManager.scrollToPositionWithOffset(
letter.adapterPosition,
(top - rv.paddingTop).toInt().coerceAtLeast(0),
)
}
private fun animatePress(target: Float, durationMs: Long) {
@@ -405,7 +739,7 @@ class WaveAlphabetView(
private fun jumpTo(index: Int) {
val rv = appsView.activeRecyclerView ?: return
scrollListTo(letters[index].adapterPosition)
scrollListTo(index)
rv.doOnNextLayout {
chosenIndex = index
chosenAtPosition = firstVisiblePosition()
@@ -430,7 +764,9 @@ class WaveAlphabetView(
if (!stripVisible()) return
val index = currentIndex()
node.stateDescription = letters[index].label
node.stateDescription = letters[index].let {
if (it.isSearch) context.getString(R.string.flexera_alphabet_search) else it.label
}
node.setRangeInfo(
AccessibilityNodeInfoCompat.RangeInfoCompat.obtain(
AccessibilityNodeInfoCompat.RangeInfoCompat.RANGE_TYPE_INT,
@@ -459,18 +795,42 @@ class WaveAlphabetView(
}
private companion object {
/** How much larger than its resting size the selected letter grows. */
const val SELECTED_GROWTH = 1.5f
/** Where a chosen letter's group is centred, and the highest its header may go, as shares of the list's height. */
const val GROUP_MIDDLE = 0.5f
const val GROUP_HIGHEST_TOP = 0.22f
/** How much its neighbours grow, tapering with distance from the finger. */
const val NEAR_GROWTH = 0.5f
/** The magnifier's size next to a letter of the same text size. */
const val SEARCH_MARK_IN_LETTER_SIZES = 1.1f
/** How many letters a whole alphabet has; the stretch of edge kept for the strip is sized for it. */
const val FULL_ALPHABET = 26
/** How much larger than its resting size the selected letter is in the wave itself. */
const val SELECTED_GROWTH = 0.25f
/** The bubble: a near-white disc, its letter near-black, a soft shadow under it. */
const val BUBBLE_COLOR = 0xFFF1F1F4.toInt()
const val BUBBLE_TEXT_COLOR = 0xFF17181C.toInt()
const val BUBBLE_SHADOW_COLOR = 0x66000000
/** The wave's spread up and down the edge, as a share of how far it reaches out. */
const val WAVE_WIDTH_SHARE_OF_REACH = 0.36f
/** How dark the list gets under a wave that lies fully over it (0 = unchanged, 1 = black). */
const val SCRUB_DIM = 0.55f
/** The share of [SCRUB_DIM] applied when the wave stays at the right edge, clear of the list. */
const val SCRUB_DIM_AT_EDGE = 0.35f
/** The tallest a resting letter may be, as a share of the vertical room it has. */
const val MAX_LETTER_SHARE_OF_SLOT = 0.85f
/**
* How long a touch on the Back strip may rest before it counts as a scrub. Long
* enough for a Back swipe to have started moving, short enough not to be felt.
*/
const val REST_BEFORE_SCRUB_MS = 130L
const val PRESS_IN_MS = 110L
const val PRESS_OUT_MS = 220L
@@ -0,0 +1,42 @@
package app.flexera.home
import android.content.Context
import app.lawnchair.preferences2.PreferenceManager2
import app.lawnchair.preferences2.firstCached
import com.android.launcher3.Utilities
/**
* The blur of the home screen behind an open folder: whether the owner wants it, and how strong
* it is. The blur itself is the depth controller's work
* ([com.android.quickstep.util.BaseDepthControllerImpl.folderBlur]), because that already blurs
* the same views and the wallpaper for other reasons and would undo anything done past it. The
* folder's opening and closing animation moves it
* ([com.android.launcher3.folder.FolderSpringAnimatorSet]).
*/
object FolderBlur {
/**
* The blur's radius behind a fully open floating folder, as a share of the largest radius
* the launcher blurs with (30dp). Strong enough that the icons behind the folder are no
* longer read, which is the point: the folder is what is in focus.
*/
const val STRENGTH = 0.8f
/**
* Behind a full-screen folder ([FullScreenFolders]) the blur is the app drawer's: the
* largest radius, which the drawer's depth comes to.
*/
const val FULL_SCREEN_STRENGTH = 1f
/**
* How far the folder's opening animation takes the depth controller's folder blur, which is
* the share of the largest radius: [FULL_SCREEN_STRENGTH] or [STRENGTH].
*/
@JvmStatic
fun strength(fullScreen: Boolean): Float = if (fullScreen) FULL_SCREEN_STRENGTH else STRENGTH
/** Blurring a view needs Android 12. */
@JvmStatic
fun isOn(context: Context): Boolean =
Utilities.ATLEAST_S && PreferenceManager2.getInstance(context).folderBlur.firstCached()
}
@@ -0,0 +1,225 @@
package app.flexera.home
import android.content.Context
import android.graphics.Color
import android.graphics.Point
import android.view.View
import android.widget.TextView
import app.flexera.drawer.FlexeraDrawer
import app.lawnchair.preferences2.PreferenceManager2
import app.lawnchair.preferences2.firstCached
import app.lawnchair.theme.color.tokens.ColorTokens
import com.android.launcher3.CellLayout
import com.android.launcher3.DeviceProfile
import com.android.launcher3.Launcher
import com.android.launcher3.R
import com.android.launcher3.Utilities
import com.android.launcher3.pageindicators.PageIndicatorDots
import com.android.launcher3.util.SystemUiController
import com.android.launcher3.util.Themes
import kotlin.math.max
import kotlin.math.roundToInt
/**
* Full-screen folders: a folder on the home screen or in the dock opens over the whole screen
* instead of as a floating panel. There is no panel. The home screen behind is blurred and
* darkened as behind the app drawer ([FolderBlur], [dim]), with light status bar icons over it
* ([setLightBarIcons]), and the folder's apps sit at the bottom of the screen, within the
* thumb's reach, with the folder's name below them. They are laid out like the home screen's
* icons: across its grid, in its columns or in as many as the owner chose ([columns]), in rows
* as high as its rows
* ([cellSize], [com.android.launcher3.folder.FolderGridOrganizer.createFullScreenFolderGridOrganizer]),
* and in no more rows than fit on the screen ([maxHeight]).
* Where the folder's icon is makes no difference to where its apps appear.
*
* What is seen of the folder is its apps, its name and its page dots; everywhere else is the
* darkened home screen. So a tap anywhere else closes the folder, as a tap beside a floating
* folder does, also within the folder view ([com.android.launcher3.folder.Folder]), which is as
* wide as the home screen's grid: beside a short last row, or beside the name. A swipe on the
* grid still turns its pages. An app dragged out of the folder leaves it as before. A folder
* that a drag opens, to take an app, floats around its icon as before, so that it opens under
* the finger. Folders in the app list are left as they were.
*/
object FullScreenFolders {
/** Space between the folder's name, under its apps, and the navigation bar. */
private const val BOTTOM_MARGIN_DP = 16f
/**
* Space kept free below the status bar. A folder has no more rows than fit below it
* ([maxHeight]); its other apps go to its next pages.
*/
private const val TOP_MARGIN_DP = 8f
/** The folder name's hint ("Unnamed folder") while it is being edited. */
private const val HINT_COLOR = 0xB3FFFFFF.toInt()
/** Whether the owner wants folders full screen (Settings, Folders). */
@JvmStatic
fun isOn(context: Context): Boolean =
PreferenceManager2.getInstance(context).fullScreenFolders.firstCached()
/** The fewest and the most columns offered for full-screen folders (Settings, Folders). */
const val MIN_COLUMNS = 2
const val MAX_COLUMNS = 6
/**
* How many columns a full-screen folder has: as many as the owner chose under Settings,
* Folders, or the home screen's when they chose none (the default). Never more than fit
* across the home screen's grid with a whole icon in each, which the home screen's own
* count always does.
*/
@JvmStatic
fun columns(launcher: Launcher): Int {
val dp = launcher.deviceProfile
val home = homeColumns(dp)
val chosen = PreferenceManager2.getInstance(launcher).fullScreenFolderColumns.firstCached()
if (chosen <= 0) return home
val gap = dp.folderCellLayoutBorderSpacePx.x
val fit = home * homeCell(launcher).x / (dp.folderChildIconSizePx + gap)
return chosen.coerceIn(1, max(home, fit))
}
private fun homeColumns(dp: DeviceProfile): Int = max(1, dp.inv.numColumns)
/**
* A cell of the home screen as it is laid out on a page (stretched to fill it, so larger
* than the device profile's own cell size), with the space between two cells added: the
* distance from one icon to the next, across and down.
*/
private fun homeCell(launcher: Launcher): Point {
val dp = launcher.deviceProfile
val workspace = launcher.workspace
val page = workspace?.getPageAt(workspace.currentPage) as? CellLayout
var width = page?.cellWidth ?: 0
var height = page?.cellHeight ?: 0
if (width <= 0 || height <= 0) {
// No page laid out yet: the width as a page would lay it out.
val columns = homeColumns(dp)
val pageWidth = dp.deviceProperties.widthPx -
dp.workspacePadding.left - dp.workspacePadding.right -
dp.cellLayoutPaddingPx.left - dp.cellLayoutPaddingPx.right
width = (pageWidth - (columns - 1) * dp.cellLayoutBorderSpacePx.x) / columns
height = dp.cellHeightPx
}
return Point(width + dp.cellLayoutBorderSpacePx.x, height + dp.cellLayoutBorderSpacePx.y)
}
/**
* The size of a cell in a full-screen folder. Across, the home screen's grid is shared out
* among the folder's [columns], less the folder's spacing between cells: with as many
* columns as the home screen, that is the home screen's own cells, and a folder centred on
* the screen has its columns where the home screen has them; with fewer, the apps spread
* wider apart over the same width, with more they move closer together. Down, a row is as
* high as the home screen's, less the same difference in spacing, but never lower than one
* app with its label needs.
*/
@JvmStatic
fun cellSize(launcher: Launcher): Point {
val dp = launcher.deviceProfile
val home = homeCell(launcher)
val across = home.x * homeColumns(dp) / columns(launcher)
val appHeight = dp.folderChildIconSizePx + dp.folderChildDrawablePaddingPx +
Utilities.calculateTextHeight(dp.folderChildTextSizePx.toFloat())
return Point(
max(across - dp.folderCellLayoutBorderSpacePx.x, dp.folderChildIconSizePx),
max(home.y - dp.folderCellLayoutBorderSpacePx.y, appHeight),
)
}
/**
* Where a full-screen folder of [width] by [height] goes, as its left and top in [dragLayer]:
* centred across the screen, its bottom just above the navigation bar. A folder too tall for
* that starts just below the status bar instead.
*/
@JvmStatic
fun position(dragLayer: View, dp: DeviceProfile, width: Int, height: Int): IntArray {
val insets = dp.insets
val screenWidth = if (dragLayer.width > 0) dragLayer.width else dp.deviceProperties.widthPx
val left = insets.left + (screenWidth - insets.left - insets.right - width) / 2
return intArrayOf(left, max(highest(dragLayer, dp), bottom(dragLayer, dp) - height))
}
/**
* How tall a full-screen folder can be, its name included: from just below the status bar
* to its place above the navigation bar ([position]). Its grid has no more rows than fit in
* that, so that none is cut off.
*/
@JvmStatic
fun maxHeight(dragLayer: View, dp: DeviceProfile): Int =
max(0, bottom(dragLayer, dp) - highest(dragLayer, dp))
/** Where a full-screen folder's bottom is in [dragLayer]: just above the navigation bar. */
private fun bottom(dragLayer: View, dp: DeviceProfile): Int {
val screenHeight =
if (dragLayer.height > 0) dragLayer.height else dp.deviceProperties.heightPx
val margin = BOTTOM_MARGIN_DP * dragLayer.resources.displayMetrics.density
return screenHeight - dp.insets.bottom - margin.roundToInt()
}
/** The highest a full-screen folder's top goes in [dragLayer]: just below the status bar. */
private fun highest(dragLayer: View, dp: DeviceProfile): Int =
dp.insets.top + (TOP_MARGIN_DP * dragLayer.resources.displayMetrics.density).roundToInt()
/**
* How dark the home screen behind a full-screen folder gets (black, 0 to 1): as dark as
* behind the app drawer ([FlexeraDrawer.BACKDROP_COLOR]), whatever the theme and the
* wallpaper, so that the white labels stay readable. With the blur at the drawer's strength
* too ([FolderBlur.FULL_SCREEN_STRENGTH]) it is the drawer's backdrop.
*/
@JvmStatic
fun dim(): Float = Color.alpha(FlexeraDrawer.BACKDROP_COLOR) / 255f
/**
* Gives an app's label in a folder the colour of its style: white over the dimmed home
* screen, or the theme's folder text colour on a floating panel. The views in folders are
* reused from one folder to the next, so both are set every time.
*/
@JvmStatic
fun styleLabel(label: TextView, fullScreen: Boolean) {
label.setTextColor(
if (fullScreen) Color.WHITE else Themes.getAttrColor(label.context, R.attr.folderTextColor),
)
}
/**
* Colours the folder's [name] for its style: white over the dimmed home screen, or as laid
* out for a floating panel. Its size is the same in both.
*/
@JvmStatic
fun styleName(name: TextView, fullScreen: Boolean) {
val context = name.context
if (fullScreen) {
name.setTextColor(Color.WHITE)
name.setHintTextColor(HINT_COLOR)
} else {
name.setTextColor(Themes.getAttrColor(context, R.attr.folderTextColor))
name.setHintTextColor(Themes.getAttrColor(context, R.attr.folderHintTextColor))
}
}
/**
* Colours the folder's page dots for its style: white over the dimmed home screen, where the
* accent colour chosen for the panel all but disappears, or that colour on a floating panel.
*/
@JvmStatic
fun stylePageIndicator(dots: PageIndicatorDots, fullScreen: Boolean) {
val panelColor = ColorTokens.pageIndicatorDotColor.resolveColor(dots.context)
dots.setPaintColor(if (fullScreen) Color.WHITE else panelColor)
}
/**
* Makes the status bar's and the navigation bar's icons light while a full-screen folder is
* open ([open]), as over the app drawer: its backdrop is dark whatever the wallpaper, and
* the home screen's icons would be dark over a light one. A floating folder leaves them to
* the home screen, as do all folders once closed.
*/
@JvmStatic
fun setLightBarIcons(launcher: Launcher?, open: Boolean) {
val darkBars = SystemUiController.FLAG_DARK_STATUS or SystemUiController.FLAG_DARK_NAV
launcher?.systemUiController?.updateUiState(
SystemUiController.UI_STATE_FULL_SCREEN_FOLDER,
if (open) darkBars else 0,
)
}
}
+203
View File
@@ -0,0 +1,203 @@
package app.flexera.home
import android.content.Context
import android.util.DisplayMetrics
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import app.lawnchair.preferences.PreferenceAdapter
import app.lawnchair.ui.preferences.components.controls.SliderPreference
import app.lawnchair.ui.preferences.components.wallpaperSupportsDarkText
import app.lawnchair.ui.theme.LawnchairTheme
import com.android.launcher3.InvariantDeviceProfile
import com.android.launcher3.R
import com.android.launcher3.icons.IconNormalizer.ICON_VISIBLE_AREA_FACTOR
import com.android.launcher3.testing.shared.ResourceUtils.pxFromDp
/**
* The home screen's margins: the space at its sides, above its first row and below its last,
* in dp, set under Settings, Home screen, Grid and margins, where the preview shows them with the
* grid before they are kept (HomeScreenGridPreferences, through PreviewOverrides).
*
* They replace Lawnchair's Horizontal and Vertical padding, which scaled the grid's own margins
* by a percentage. On a phone those are 8 dp at the sides and nothing at the top or bottom, so
* the sides moved by a few dp over the whole slider and the top and bottom not at all, and it
* looked as if the settings did nothing.
*
* The rows and columns share what room the margins leave, so larger margins also bring the
* icons closer together; that is how the spacing between icons is set. A phone's grid does not
* shrink its icons to fit smaller cells (Launcher3 does that only for scalable grids), so the
* margins stop growing where the cells would get too small: the side margins where a column
* would be narrower than what is seen of its icon ([sidePx]), the top and bottom margins where
* a row would be shorter than its icon and label ([fitTopBottom]).
*
* The grid page's preview draws the margins over the home screen ([Guides]), so that they can
* be seen however full or empty the page is.
*/
object HomeMargins {
/** The side margins of a new install: the grid's own on a phone (dynamic_grid_left_right_margin). */
const val DEFAULT_SIDE_DP = 8
private const val MAX_SIDE_DP = 48
private const val MAX_TOP_BOTTOM_DP = 120
/** The least room a column keeps beside what is seen of its icon. */
private const val MIN_COLUMN_GAP_DP = 4f
/**
* The side margin, in pixels, for a grid of [columns] columns across [availableWidthPx] with
* icons [iconSizeDp] in size: the owner's [chosenDp], or less where that would make a column
* narrower than its icon.
*/
@JvmStatic
fun sidePx(chosenDp: Int, metrics: DisplayMetrics, availableWidthPx: Int, columns: Int, iconSizeDp: Float): Int {
val chosen = pxFromDp(chosenDp.coerceIn(0, MAX_SIDE_DP).toFloat(), metrics)
val column = pxFromDp(iconSizeDp, metrics) * ICON_VISIBLE_AREA_FACTOR +
pxFromDp(MIN_COLUMN_GAP_DP, metrics)
val most = ((availableWidthPx - columns.coerceAtLeast(1) * column) / 2f).toInt()
return chosen.coerceAtMost(most).coerceAtLeast(0)
}
/**
* What the rows can spare of a top margin of [topPx] and a bottom margin of [bottomPx]:
* [spare] is the height the rows have beyond what their icons and labels need. Both are cut
* in proportion until they fit. The top margin comes first, then the bottom one.
*/
@JvmStatic
fun fitTopBottom(topPx: Int, bottomPx: Int, spare: Int): IntArray {
val wanted = topPx + bottomPx
if (wanted <= 0 || spare <= 0) return intArrayOf(0, 0)
if (wanted <= spare) return intArrayOf(topPx, bottomPx)
val top = (topPx.toLong() * spare / wanted).toInt()
return intArrayOf(top, spare - top)
}
/**
* The margins over the grid page's preview of [idp]: tinted bands along the screen's sides
* and above and below the rows, as wide as the margins are laid out, and a dashed outline
* around the rows. Drawn in the colours of the preview's own background, which follows the
* wallpaper, so that they stand out from it.
*/
@Composable
fun Guides(idp: InvariantDeviceProfile) {
val context = LocalContext.current
val profile = remember(idp) { idp.getDeviceProfile(context) }
LawnchairTheme(darkTheme = !wallpaperSupportsDarkText()) {
val tint = MaterialTheme.colorScheme.primary
Canvas(modifier = Modifier.fillMaxSize()) {
val screen = profile.deviceProperties
val scaleX = size.width / screen.widthPx
val scaleY = size.height / screen.heightPx
val insets = profile.insets
val padding = profile.workspacePadding
val cells = profile.cellLayoutPaddingPx
// The rows, as the workspace lays them out: inside the system bars, the
// workspace's padding and the page's own.
val left = (insets.left + padding.left + cells.left) * scaleX
val right = (screen.widthPx - insets.right - padding.right - cells.right) * scaleX
val top = (insets.top + padding.top + cells.top) * scaleY
val bottom = (screen.heightPx - insets.bottom - padding.bottom - cells.bottom) * scaleY
if (right <= left || bottom <= top) return@Canvas
val band = tint.copy(alpha = BAND_ALPHA)
val side = profile.desiredWorkspaceHorizontalMarginPx * scaleX
val above = profile.flexeraTopMarginPx * scaleY
val below = profile.flexeraBottomMarginPx * scaleY
if (side > 0f) {
drawRect(band, Offset(left - side, top), Size(side, bottom - top))
drawRect(band, Offset(right, top), Size(side, bottom - top))
}
if (above > 0f) drawRect(band, Offset(left, top - above), Size(right - left, above))
if (below > 0f) drawRect(band, Offset(left, bottom), Size(right - left, below))
drawRect(
color = tint,
topLeft = Offset(left, top),
size = Size(right - left, bottom - top),
style = Stroke(
width = OUTLINE_DP.dp.toPx(),
pathEffect = PathEffect.dashPathEffect(floatArrayOf(DASH_DP.dp.toPx(), GAP_DP.dp.toPx())),
),
)
}
}
}
private const val BAND_ALPHA = 0.32f
private const val OUTLINE_DP = 1.5f
private const val DASH_DP = 5f
private const val GAP_DP = 4f
/** A top or bottom margin of [chosenDp], in pixels. */
@JvmStatic
fun topBottomPx(chosenDp: Int, metrics: DisplayMetrics): Int =
pxFromDp(chosenDp.coerceIn(0, MAX_TOP_BOTTOM_DP).toFloat(), metrics)
/**
* Whether the grid of [idp] lays out less of the margins than [sideDp], [topDp] and
* [bottomDp]: its rows or columns leave no more room (see [sidePx] and [fitTopBottom]).
*/
fun isLimited(context: Context, idp: InvariantDeviceProfile, sideDp: Int, topDp: Int, bottomDp: Int): Boolean {
val profile = idp.getDeviceProfile(context)
val metrics = context.resources.displayMetrics
val side = profile.desiredWorkspaceHorizontalMarginPx < pxFromDp(sideDp.toFloat(), metrics) - 1
val wanted = topBottomPx(topDp, metrics) + topBottomPx(bottomDp, metrics)
val laidOut = profile.flexeraTopMarginPx + profile.flexeraBottomMarginPx
return side || laidOut < wanted - 1
}
/**
* The three sliders, on the grid page in place of Lawnchair's two padding sliders on the home
* screen page. They change [side], [top] and [bottom], which the grid page keeps on Apply.
* When the grid cannot lay out as much as they ask ([limited]), a note under them says why.
*/
@Composable
fun Preferences(
side: PreferenceAdapter<Int>,
top: PreferenceAdapter<Int>,
bottom: PreferenceAdapter<Int>,
limited: Boolean,
) {
SliderPreference(
label = stringResource(id = R.string.flexera_home_side_margins),
adapter = side,
valueRange = 0..MAX_SIDE_DP,
step = 2,
showUnit = "dp",
)
SliderPreference(
label = stringResource(id = R.string.flexera_home_top_margin),
adapter = top,
valueRange = 0..MAX_TOP_BOTTOM_DP,
step = 4,
showUnit = "dp",
)
SliderPreference(
label = stringResource(id = R.string.flexera_home_bottom_margin),
adapter = bottom,
valueRange = 0..MAX_TOP_BOTTOM_DP,
step = 4,
showUnit = "dp",
)
if (limited) {
Text(
text = stringResource(id = R.string.flexera_home_margins_limited),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
)
}
}
}
+346
View File
@@ -0,0 +1,346 @@
package app.flexera.home
import android.app.ActivityOptions
import android.content.Context
import android.content.Intent
import android.content.pm.LauncherApps
import android.graphics.Canvas
import android.os.Build
import android.os.Process
import android.util.Log
import android.view.HapticFeedbackConstants
import android.view.MotionEvent
import android.view.View
import android.widget.Toast
import app.flexera.reader.ReaderPage
import app.lawnchair.LawnchairLauncher
import app.lawnchair.gestures.config.GestureHandlerConfig
import app.lawnchair.gestures.handlers.OpenAppTarget
import app.lawnchair.preferences2.PreferenceManager2
import app.lawnchair.preferences2.firstCached
import com.android.launcher3.Launcher
import com.android.launcher3.LauncherState
import com.android.launcher3.R
import com.android.launcher3.model.data.AppInfo
import com.android.launcher3.util.EdgeEffectCompat
/**
* Quick launch: a swipe on from the first home screen page, towards the page that is not there,
* opens an app the owner has chosen (or does another of the launcher's gesture actions); the
* same past the last page.
*
* The home screen already answers such a swipe by stretching and springing back. That stretch is
* an edge effect, one per side, and quick launch is an edge effect that also keeps count of how
* far the finger has pulled. When the choice is an app, there is no stretch: the pull brings in
* a page of the app's own ([QuickLaunchPage]), and the app opens on it. For the other actions
* the stretch stays, and far enough, or a flick, does the action when the finger lifts. The
* stretch also stays for an app that is no longer installed, or is disabled; letting go says so.
* The RSS reader comes in the same way as an app's page, and stays ([ReaderPage]).
* Launcher3 uses the same place for the Google feed on other phones (OverlayEdgeEffect).
*/
object QuickLaunch {
private const val TAG = "QuickLaunch"
/**
* A page that a pull past the first or the last home screen page brings in with the finger,
* moving the home screen aside: the app's page ([QuickLaunchPage]) or the RSS reader's
* ([ReaderPage]).
*/
interface EdgePage {
/** The page is going in, or in, and takes no new pull. */
val isBusy: Boolean
/** A pull begins at the left or the right edge; returned is how far the page is in already. */
fun begin(fromLeft: Boolean): Float
/** Puts the page [progress] of the way in, from 0 to 1, with the home screen beside it. */
fun show(progress: Float)
/**
* The finger has let go: the page goes all the way in ([open]) or back out, at least as
* fast as the finger was moving ([speed], pixels per second). [launch] is what the app's
* page runs once it is going in; the reader's page has nothing to start.
*/
fun settle(open: Boolean, speed: Float, launch: () -> Unit)
/** The home screen comes back. */
fun close()
}
/** How far the finger has to pull past the page, as a share of the screen's width. */
private const val ARM_DISTANCE = 0.14f
/** A flick counts from this much pull, at [FLICK_DP_PER_SECOND] or faster. */
private const val FLICK_DISTANCE = 0.02f
private const val FLICK_DP_PER_SECOND = 600f
/**
* The edge effect for one side of the home screen pages. [atLeftEdge] says which side of
* the screen; which page that is the end of depends on the reading direction ([rtl]).
*/
@JvmStatic
fun edgeEffect(workspace: View, launcher: Launcher, atLeftEdge: Boolean, rtl: Boolean): EdgeEffectCompat =
Effect(workspace, launcher, firstPage = atLeftEdge != rtl, atLeftEdge = atLeftEdge)
/** What the owner has chosen for a swipe past the first or the last page. */
private fun choice(context: Context, firstPage: Boolean): GestureHandlerConfig {
val prefs = PreferenceManager2.getInstance(context)
return if (firstPage) {
prefs.firstPageSwipeGestureHandler.firstCached()
} else {
prefs.lastPageSwipeGestureHandler.firstCached()
}
}
/** The app [choice] opens, if it opens one. */
private fun appOf(choice: GestureHandlerConfig): OpenAppTarget.App? =
(choice as? GestureHandlerConfig.OpenApp)?.target as? OpenAppTarget.App
/**
* Whether [target] is there to be opened, which it is not once it has been uninstalled or
* disabled. When that cannot be told, it counts as there, and starting it tells.
*/
private fun isThere(context: Context, target: OpenAppTarget.App): Boolean = try {
context.getSystemService(LauncherApps::class.java)
?.isActivityEnabled(target.key.componentName, target.key.user) ?: true
} catch (e: RuntimeException) {
Log.w(TAG, "Could not tell whether the quick launch app is there", e)
true
}
/**
* Says that [choice]'s app could not be opened; without a word, the swipe would seem to do
* nothing.
*/
private fun sayNotOpened(context: Context, choice: GestureHandlerConfig) {
val name = (choice as? GestureHandlerConfig.OpenApp)?.appName ?: return
Toast.makeText(
context,
context.getString(R.string.flexera_quick_launch_app_missing, name),
Toast.LENGTH_SHORT,
).show()
}
/** Opens [target]; false if it cannot be opened. */
private fun startApp(launcher: Launcher, target: OpenAppTarget.App, options: ActivityOptions): Boolean = try {
val apps = launcher.getSystemService(LauncherApps::class.java)
apps?.startMainActivity(target.key.componentName, target.key.user, null, options.toBundle())
apps != null
} catch (e: RuntimeException) {
// The chosen app is gone or cannot be started; nothing to open.
Log.w(TAG, "The quick launch app could not be opened", e)
false
}
private fun launch(launcher: Launcher, firstPage: Boolean, fromLeft: Boolean) {
val choice = choice(launcher, firstPage)
if (choice is GestureHandlerConfig.NoOp) return
val target = appOf(choice)
if (target != null) {
// The app opens out of the screen edge the finger pulled from, as near to a page
// sliding in as Android lets an ordinary app come: it plays a sideways slide of
// the launcher's own making only for the phone's built-in launcher.
val root = launcher.rootView
val options = ActivityOptions.makeClipRevealAnimation(
root,
if (fromLeft) 0 else root.width - 1,
0,
1,
root.height,
)
if (!startApp(launcher, target, options)) sayNotOpened(launcher, choice)
return
}
(launcher as? LawnchairLauncher)?.gestureController?.handle(choice)
}
/** The page is going all the way in: the app is started, or the home screen comes back. */
private fun launchOnPage(launcher: Launcher, firstPage: Boolean, page: QuickLaunchPage) {
val choice = choice(launcher, firstPage)
val target = appOf(choice)
if (target == null) {
page.close()
} else if (!startOnPage(launcher, target)) {
sayNotOpened(launcher, choice)
page.close()
}
}
/**
* Opens [target] without Android's opening animation: the app appears on the page the moment
* it has something to show. That is its last screen if it was still in memory, else its
* splash screen. (Android plays no other animation that a launcher of one's own may choose:
* asked for a plain fade, it still zooms the app in from the middle.)
*/
private fun startOnPage(launcher: Launcher, target: OpenAppTarget.App): Boolean {
val key = target.key
if (key.user != Process.myUserHandle()) {
// An app of another profile, such as a work profile, can only be started through
// LauncherApps, which takes no such flag; it opens with Android's usual animation.
return startApp(launcher, target, ActivityOptions.makeBasic())
}
// The same intent as the app's icon, so that it is the same task that comes up.
val intent = AppInfo.makeLaunchIntent(key.componentName)
.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
return try {
launcher.startActivity(intent)
true
} catch (e: RuntimeException) {
// The chosen app is gone or cannot be started; nothing to open.
Log.w(TAG, "The quick launch app could not be opened", e)
false
}
}
private class Effect(
private val workspace: View,
private val launcher: Launcher,
private val firstPage: Boolean,
private val atLeftEdge: Boolean,
) : EdgeEffectCompat(workspace.context) {
/** How far the finger has pulled in this touch, as a share of the screen's width. */
private var pulled = 0f
/** Whether there is anything to do on this side; looked up when a pull begins. */
private var active = false
private var armed = false
private var flicked = false
/**
* The page this pull brings in, when the choice is an app that is there or the RSS
* reader; then there is no stretch.
*/
private var paging: EdgePage? = null
/** How fast the finger was moving towards the missing page when it lifted, in px/s. */
private var outwardVelocity = 0f
private val flickVelocity = FLICK_DP_PER_SECOND * workspace.resources.displayMetrics.density
// While paging, the pull is the page's, not a stretch's: the pages ask these whether
// there is a pull to give back before they scroll the other way.
override fun getDistance(): Float = if (paging != null) pulled else super.getDistance()
override fun isFinished(): Boolean = if (paging != null) pulled <= 0f else super.isFinished()
override fun draw(canvas: Canvas): Boolean = if (paging != null) false else super.draw(canvas)
override fun onPullDistance(deltaDistance: Float, displacement: Float, ev: MotionEvent): Float {
if (pulled == 0f && deltaDistance > 0f) {
val choice = choice(workspace.context, firstPage)
active = choice !is GestureHandlerConfig.NoOp &&
launcher.isInState(LauncherState.NORMAL) &&
!launcher.dragController.isDragging
// An app that is no longer there gets no page, only the stretch, so that the
// home screen stays put; letting go far enough says why nothing opens.
val app = if (active) appOf(choice) else null
paging = when {
app != null && isThere(launcher, app) -> QuickLaunchPage.of(launcher)
active && choice is GestureHandlerConfig.OpenRssReader -> ReaderPage.of(launcher)
else -> null
}?.takeUnless { it.isBusy }
// The pull takes the page from where it is; a new touch has put back one that was
// still on its way back.
pulled = paging?.begin(fromLeft = atLeftEdge) ?: 0f
}
val page = paging
if (page != null) {
val before = pulled
pulled = (pulled + deltaDistance).coerceIn(0f, 1f)
page.show(pulled)
arm(pulled >= QuickLaunchPage.OPEN_DISTANCE)
return pulled - before
}
val consumed = super.onPullDistance(deltaDistance, displacement, ev)
pulled = (pulled + deltaDistance).coerceAtLeast(0f)
arm(active && pulled >= ARM_DISTANCE)
return consumed
}
override fun onFlingVelocity(velocity: Int) {
// A pull at the left side is a finger moving right, which is a positive speed.
outwardVelocity = (if (atLeftEdge) velocity else -velocity).toFloat()
flicked = active && pulled >= FLICK_DISTANCE && outwardVelocity >= flickVelocity
}
override fun onAbsorb(velocity: Int) {
if (paging == null) super.onAbsorb(velocity)
}
override fun onRelease(ev: MotionEvent) {
val lifted = ev.actionMasked == MotionEvent.ACTION_UP
val page = paging
if (page != null) {
// As with the pages themselves: a flick decides, else how far the page is in.
val open = lifted && when {
flicked -> true
outwardVelocity <= -flickVelocity -> false
else -> armed
}
val tickNow = open && !armed
val speed = if (open) outwardVelocity else -outwardVelocity
reset()
if (tickNow) tick()
// The app is started right after the pages have finished with this touch.
page.settle(open, speed) {
if (page is QuickLaunchPage) workspace.post { launchOnPage(launcher, firstPage, page) }
}
return
}
val fire = lifted && active && (armed || flicked)
val tickNow = fire && !armed
reset()
super.onRelease(ev)
if (fire) {
if (tickNow) tick()
// After the page has finished handling this touch.
workspace.post { launch(launcher, firstPage, fromLeft = atLeftEdge) }
}
}
override fun onRelease() {
val page = paging
reset()
if (page != null) page.close() else super.onRelease()
}
override fun finish() {
val page = paging
reset()
if (page != null) page.close() else super.finish()
}
private fun arm(nowArmed: Boolean) {
if (nowArmed != armed) {
armed = nowArmed
// A tick when the pull is far enough, and again when it is taken back.
tick()
}
}
private fun reset() {
pulled = 0f
active = false
armed = false
flicked = false
paging = null
outwardVelocity = 0f
}
private fun tick() {
val feedback = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
HapticFeedbackConstants.GESTURE_THRESHOLD_ACTIVATE
} else {
HapticFeedbackConstants.CLOCK_TICK
}
// The pages themselves have haptics switched off; the window's root has not.
launcher.rootView.performHapticFeedback(feedback)
}
}
}
@@ -0,0 +1,308 @@
package app.flexera.home
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Paint
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.animation.DecelerateInterpolator
import com.android.launcher3.BaseActivity
import com.android.launcher3.InsettableFrameLayout
import com.android.launcher3.Launcher
import com.android.launcher3.LauncherState
import com.android.launcher3.statemanager.StateManager
import com.android.launcher3.util.SystemUiController
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.roundToInt
/**
* Quick launch's page: when a swipe past the first or the last home screen page opens an app,
* the home screen does not stretch. It moves aside with the finger, as it does for a page that
* is there, and an empty black page comes in behind it. The home screen blurs and darkens the
* further it goes. Let go far enough, or flick, and the app is started there and then, while the
* page settles over the whole screen; it appears on the page as soon as it has drawn, with none
* of Android's opening animation. Let go early, and the home screen comes back.
*
* The home screen is moved by its drawing only ([View.setAnimationMatrix] on the drag layer),
* not by its position: the touch that moves it is still being read by the pages inside it, and
* moving their position would move the finger's position in them as well.
*
* [QuickLaunch]'s edge effect drives this with the finger, from 0 (home screen) to 1 (page).
*/
class QuickLaunchPage private constructor(private val launcher: Launcher) : QuickLaunch.EdgePage {
companion object {
/** How far the page has to come in for letting go to open it, as a share of the width. */
const val OPEN_DISTANCE = 0.4f
/** How dark the home screen gets beside a page that is all the way in. */
private const val HOME_DIM = 0.35f
/** The page settles at least this fast, in dp per second, and within these times. */
private const val MIN_SETTLE_DP_PER_SECOND = 1500f
private const val MIN_SETTLE_MS = 150L
private const val MAX_SETTLE_MS = 300L
/**
* Once the page is across, the launcher is paused as soon as the app starts. Still in
* the foreground after this long, it never will be: nothing came, and the home screen
* comes back.
*/
private const val LAUNCH_TIMEOUT_MS = 1500L
/**
* [launcher]'s page, made when first wanted; null while the launcher has no views. The
* page is found through its view among the launcher's own and is kept nowhere outside
* that launcher: it holds on to its launcher, so a reference from here would keep every
* launcher it was used in alive after that launcher is gone.
*/
fun of(launcher: Launcher): QuickLaunchPage? {
val root = launcher.rootView ?: return null
if (launcher.dragLayer == null) return null
return pageIn(root) ?: QuickLaunchPage(launcher)
}
/** Whether [launcher]'s page is on the screen, all or part of it. */
@JvmStatic
fun isShowing(launcher: Launcher): Boolean =
(launcher.rootView?.let { pageIn(it) }?.progress ?: 0f) > 0f
/** The page whose view is among [root]'s children, if one has been made. */
private fun pageIn(root: ViewGroup): QuickLaunchPage? {
for (i in 0 until root.childCount) {
(root.getChildAt(i) as? PageView)?.let { return it.page }
}
return null
}
/** The blur for how far the page is in: quick at first, so the home screen soon recedes. */
private fun blurFor(progress: Float): Float {
val left = 1f - progress
return 1f - left * left
}
}
/** How far the page is in, from 0 (not at all) to 1 (it fills the screen). */
var progress = 0f
private set
/** Whether the page comes in from the left edge of the screen, rather than the right. */
private var fromLeft = false
/** The page is on its way all the way in, or there, with the app to follow. */
private var opening = false
/** Changes whenever what an earlier opening waits for no longer counts. */
private var generation = 0
private var animator: ValueAnimator? = null
private val shift = Matrix()
private val view = PageView(launcher)
private val minSettleSpeed = MIN_SETTLE_DP_PER_SECOND * launcher.resources.displayMetrics.density
init {
view.visibility = View.INVISIBLE
// Over the whole window, the status and navigation bars included.
val params = InsettableFrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
).apply { ignoreInsets = true }
launcher.rootView.addView(view, params)
// Going home or to the recent apps from the app puts the launcher to use again. Should
// that come before the launcher was out of sight (PageView.onWindowVisibilityChanged),
// the home screen is put back for it at once.
launcher.stateManager.addStateListener(object : StateManager.StateListener<LauncherState> {
override fun onStateTransitionStart(toState: LauncherState) {
if (opening && toState != LauncherState.NORMAL) reset()
}
})
}
/** Whether the page is busy opening an app; it then takes no new pull. */
override val isBusy: Boolean
get() = opening
/** A pull begins at the left or the right edge; returned is how far the page is in already. */
override fun begin(fromLeft: Boolean): Float {
cancelAnimation()
if (this.fromLeft != fromLeft) {
show(0f)
this.fromLeft = fromLeft
}
return progress
}
/** Puts the page [progress] of the way in, from 0 to 1, with the home screen beside it. */
override fun show(progress: Float) {
this.progress = progress.coerceIn(0f, 1f)
apply()
}
/**
* The finger has let go: the page goes all the way in ([open]) or back out, at least as fast
* as the finger was moving that way ([speed], pixels per second). Going in, [launch] runs at
* once, so that the app is on its way while the page settles; it starts the app, or calls
* [close] if there is none to start.
*/
override fun settle(open: Boolean, speed: Float, launch: () -> Unit) {
cancelAnimation()
opening = open
val target = if (open) 1f else 0f
if (progress == target) {
apply()
} else {
val remaining = abs(target - progress) * view.rootWidth()
// A decelerating move starts at twice its average speed.
val duration = (2000f * remaining / max(speed, minSettleSpeed)).toLong()
val anim = ValueAnimator.ofFloat(progress, target)
anim.duration = duration.coerceIn(MIN_SETTLE_MS, MAX_SETTLE_MS)
anim.interpolator = DecelerateInterpolator()
anim.addUpdateListener { show(it.animatedValue as Float) }
anim.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
if (animator === anim) animator = null
}
})
animator = anim
anim.start()
}
if (open) opened(launch)
}
/** The home screen comes back, as after letting go too early. */
override fun close() {
generation++
settle(open = false, speed = 0f) {}
}
/** The home screen is back at once, with nothing to see on the way. */
fun reset() {
generation++
cancelAnimation()
opening = false
show(0f)
}
private fun opened(launch: () -> Unit) {
val token = ++generation
// Once the app is in front, the launcher stops; the next time it is seen, it is as it was.
// (Mostly the page has gone before that, as soon as the launcher was out of sight.)
launcher.addEventCallback(BaseActivity.EVENT_STOPPED) {
if (token == generation) reset()
}
// Starting an app pauses the launcher, resumes it for a moment and pauses it again, so
// being resumed only means something once the start has had its time.
view.postDelayed({
if (token != generation) return@postDelayed
if (launcher.hasBeenResumed()) {
// Still in front: nothing came.
close()
} else {
// Something is in front without hiding the launcher, or is still starting.
// Should the launcher come back without having stopped, the home screen does too.
launcher.addEventCallback(BaseActivity.EVENT_RESUMED) {
if (token == generation) close()
}
}
}, LAUNCH_TIMEOUT_MS)
launch()
}
private fun cancelAnimation() {
animator?.let {
animator = null
it.cancel()
}
}
private fun apply() {
val p = progress
view.visibility = if (p > 0f) View.VISIBLE else View.INVISIBLE
view.invalidate()
val dragLayer = launcher.dragLayer
if (p > 0f) {
shift.setTranslate((if (fromLeft) 1f else -1f) * p * view.rootWidth(), 0f)
dragLayer.setAnimationMatrix(shift)
} else {
dragLayer.setAnimationMatrix(null)
}
// As strong as behind a floating folder, at most.
launcher.depthController?.quickLaunchBlur?.value = blurFor(p) * FolderBlur.STRENGTH
// Light status bar icons once the page is most of what is seen.
launcher.systemUiController?.updateUiState(
SystemUiController.UI_STATE_QUICK_LAUNCH_PAGE,
if (p >= 0.5f) SystemUiController.FLAG_DARK_STATUS or SystemUiController.FLAG_DARK_NAV else 0,
)
}
/** The width the page and the home screen move across; known before this view's first layout. */
private fun View.rootWidth(): Int = if (width > 0) width else launcher.dragLayer.width
private inner class PageView(context: Context) : View(context) {
/** The page this view draws. */
val page: QuickLaunchPage get() = this@QuickLaunchPage
private val pagePaint = Paint().apply { color = Color.BLACK }
private val dimPaint = Paint().apply { color = Color.BLACK }
init {
importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
}
/**
* While the page opens and the app is on its way, a touch would land on the home screen
* behind it, where nothing is where it is drawn; the page keeps it. On its way back, a
* touch puts the home screen back in its place first. The home screen is moved by its
* drawing only, and a touch goes to what really is under the finger. Drawn aside by less
* than the room left on each side of an icon, every icon is still drawn within its own
* place, so the touch goes through, to the icon the finger came down on; further aside,
* it could reach the next one, and the page keeps the touch. Only while the page moves
* back on its own: during a pull, a second finger coming down reaches the page too, and
* must not break the pull off.
*/
override fun onTouchEvent(event: MotionEvent): Boolean {
if (opening) return true
if (event.actionMasked != MotionEvent.ACTION_DOWN || animator == null) return false
val aside = progress * width
reset()
return aside >= launcher.deviceProfile.cellHorizontalSpace / 2f
}
/**
* Once the launcher is out of sight, which it is as soon as the app is in front of it,
* the home screen is put back for the next time it is seen. Waiting for the launcher to
* stop would leave the page in until the app has settled, and going home before then
* would find the home screen black, taking every touch.
*/
override fun onWindowVisibilityChanged(visibility: Int) {
super.onWindowVisibilityChanged(visibility)
if (visibility != VISIBLE && opening) reset()
}
override fun onDraw(canvas: Canvas) {
val w = width.toFloat()
val h = height.toFloat()
val edge = progress * w
dimPaint.alpha = (HOME_DIM * progress * 255).roundToInt()
if (fromLeft) {
canvas.drawRect(0f, 0f, edge, h, pagePaint)
canvas.drawRect(edge, 0f, w, h, dimPaint)
} else {
canvas.drawRect(w - edge, 0f, w, h, pagePaint)
canvas.drawRect(0f, 0f, w - edge, h, dimPaint)
}
}
}
}
@@ -0,0 +1,413 @@
package app.flexera.reader
import android.content.Context
import android.text.TextUtils
import android.util.Log
import app.lawnchair.util.kotlinxJson
import java.io.ByteArrayInputStream
import java.io.File
import java.security.MessageDigest
import java.util.Locale
import java.util.concurrent.TimeUnit
import kotlin.math.max
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.jsoup.safety.Safelist
/**
* The text of the RSS reader's posts, for the article view ([ArticleView]).
*
* A feed carries some of each post as HTML, often only its start. That is kept as it comes, a
* file per post, when the feed is fetched ([saveFeedText]). Opening a post shows it at once
* ([fromFeed]); when it is short of a whole article, the post's web page is fetched and its
* article found in it ([fromPage]): the element whose paragraphs hold the most text, after the
* parts that are plainly not the article (menus, sharing, related stories, comments) are taken
* out, as reading modes do. Whatever is shown is cleaned first: only text, pictures, links and
* plain structure stay; no scripts, frames, forms or styles of the site's own. The files are
* in the cache, which Android may empty; a post is then fetched again when opened.
*/
object ArticleStore {
private const val TAG = "ArticleStore"
private const val DIR = "flexera_rss_articles"
/** A feed's text this long, in characters, is taken for the whole article. */
private const val WHOLE_TEXT = 2500
/** An article found in a page is believed only from this length on. */
private const val MIN_FOUND_TEXT = 400
/** Kept files go after this many days. */
private const val KEEP_DAYS = 21L
/** What the article view shows of a post: cleaned HTML, and whether it is all of it. */
class Readable(val html: String, val whole: Boolean)
private val safelist: Safelist = Safelist.relaxed()
.addTags("figure", "figcaption", "hr", "mark", "s", "del", "ins", "abbr", "time", "small")
.removeAttributes("img", "width", "height", "align")
private fun dir(context: Context) = File(context.cacheDir, DIR)
private fun file(context: Context, id: String, kind: String) = File(dir(context), "${hash(id)}.$kind")
private fun hash(id: String): String =
MessageDigest.getInstance("SHA-1").digest(id.toByteArray()).joinToString("") { "%02x".format(it) }
/** Keeps what the feed carries of a post, unless it is kept already. For a background thread. */
fun saveFeedText(context: Context, articleId: String, html: String) {
if (html.isBlank()) return
try {
val target = file(context, articleId, "feed")
if (target.exists()) return
target.parentFile?.mkdirs()
target.writeText(html)
} catch (e: Exception) {
Log.w(TAG, "Could not keep a post's text", e)
}
}
/**
* What there is of [item] without going online: the article found in its page before, or
* the feed's text, or at least the summary. For a background thread.
*/
fun fromFeed(context: Context, item: RssReader.Item): Readable {
val article = item.article
readOrNull(file(context, article.id, "page"))?.let { return Readable(it, whole = true) }
val feedHtml = readOrNull(file(context, article.id, "feed"))?.let { clean(it, base(article), article.imageUrl) }
if (feedHtml != null && textLength(feedHtml) >= WHOLE_TEXT) return Readable(feedHtml, whole = true)
val html = feedHtml?.takeIf { textLength(it) > 0 }
?: article.summary.takeIf { it.isNotEmpty() }?.let { "<p>${TextUtils.htmlEncode(it)}</p>" }
?: ""
return Readable(html, whole = false)
}
/**
* Fetches [item]'s web page and finds the article in it. Null when that is no longer than
* [knownLength] characters of text already shown; the page is then no help. For a background
* thread; throws [RssFetcher.FetchException] when the page cannot be fetched.
*/
fun fromPage(context: Context, item: RssReader.Item, knownLength: Int): String? {
val article = item.article
if (article.link.isEmpty()) return null
val page = RssFetcher.fetchPage(context, article.link)
val document = Jsoup.parse(ByteArrayInputStream(page.body), charsetOf(page.contentType), page.url)
val found = Extractor.articleOf(document, article.title) ?: return null
val html = clean(found, page.url, article.imageUrl)
val length = textLength(html)
if (length < MIN_FOUND_TEXT || length <= knownLength) return null
try {
val target = file(context, article.id, "page")
target.parentFile?.mkdirs()
target.writeText(html)
} catch (e: Exception) {
Log.w(TAG, "Could not keep an article", e)
}
return html
}
/** How many characters of text [html] shows. */
fun textLength(html: String): Int = Jsoup.parseBodyFragment(html).text().length
/** Deletes kept texts older than [KEEP_DAYS]. For a background thread. */
fun prune(context: Context) {
val cutoff = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(KEEP_DAYS)
dir(context).listFiles()?.forEach { if (it.lastModified() < cutoff) it.delete() }
}
private fun base(article: RssArticle) = article.link.ifEmpty { article.feedUrl }
private fun readOrNull(file: File): String? = try {
if (file.exists()) file.readText() else null
} catch (e: Exception) {
null
}
private fun charsetOf(contentType: String?): String? =
contentType?.substringAfter("charset=", "")?.trim(' ', '"', ';')?.takeIf { it.isNotEmpty() }
?.takeIf { runCatching { charset(it) }.isSuccess }
/**
* [html] with only what is safe and plain left: no scripts, styles, frames or forms, links
* and pictures made whole addresses, and pictures fetched encrypted. The post's own picture
* ([hero]), which the view shows above the title, is taken out where the text starts with it.
*/
private fun clean(html: String, base: String, hero: String?): String {
val raw = Jsoup.parseBodyFragment(html, base)
useLazyPictures(raw)
val cleaned = Jsoup.parseBodyFragment(Jsoup.clean(raw.body().html(), base, safelist), base)
for (img in cleaned.select("img")) {
val src = img.attr("src")
when {
src.isBlank() -> img.remove()
src.startsWith("http://") -> img.attr("src", "https://" + src.removePrefix("http://"))
}
}
if (hero != null) {
cleaned.select("img").firstOrNull { sameImage(it.attr("src"), hero) }?.let { same ->
val figure = same.closest("figure")
if (figure != null && figure.select("img").size == 1) figure.remove() else same.remove()
}
}
cleaned.select("h1").remove()
// Paragraphs left empty by the cleaning.
for (el in cleaned.select("p, div, span, figure, a")) {
if (!el.hasText() && el.select("img, hr, br").isEmpty()) el.remove()
}
return cleaned.body().html()
}
/** Pages often load their pictures only when scrolled to; their real address is elsewhere. */
private fun useLazyPictures(document: Document) {
for (img in document.select("img")) {
val src = img.attr("src")
if (src.isNotBlank() && !src.startsWith("data:")) continue
val lazy = listOf("data-src", "data-lazy-src", "data-original", "data-url", "data-hi-res-src")
.map { img.attr(it) }.firstOrNull { it.isNotBlank() }
?: firstOfSrcset(img.attr("srcset").ifBlank { img.attr("data-srcset") })
?: img.parent()?.takeIf { it.tagName() == "picture" }
?.select("source")?.firstNotNullOfOrNull { firstOfSrcset(it.attr("srcset")) }
if (lazy != null) img.attr("src", lazy) else img.remove()
}
}
private fun firstOfSrcset(srcset: String): String? =
srcset.split(',').map { it.trim().substringBefore(' ') }.lastOrNull { it.isNotBlank() }
/** Whether two picture addresses name the same picture, perhaps at another size. */
private fun sameImage(a: String, b: String): Boolean {
fun name(url: String) = url.substringBefore('?').substringAfterLast('/')
.lowercase(Locale.ROOT)
.replace(Regex("""-\d+x\d+(?=\.\w+$)"""), "")
.substringBeforeLast('.')
val left = name(a)
return left.isNotEmpty() && left == name(b)
}
/** Finds the article in a web page. */
private object Extractor {
/** Class and id words of the parts of a page that are not the article. */
private val UNLIKELY = Regex(
"""(?i)(^|[-_\s])(ad|ads|advert\w*|banner|breadcrumbs?|comments?|community|cookie|consent|disqus|footer|gdpr|header|menu|modal|nav\w*|newsletter|outbrain|pagination|popup|promo\w*|recirc\w*|related|share|sharing|sidebar|signup|social|sponsor\w*|subscribe|subscription|taboola|toolbar|trending|most-popular|read-more|more-stories|author-bio|tags?)([-_\s]|$)""",
)
/** Words that make a part likely to be the article after all. */
private val LIKELY = Regex("""(?i)article|body|content|main|story|entry|post-?text|prose""")
private val TEXT_TAGS = setOf("p", "pre", "td", "blockquote", "li")
/**
* Lines of the page that are about the site rather than the article: commission notices,
* invitations to follow or subscribe.
*/
private val PROMO = Regex(
"""(?i)earns? (a )?commission|affiliate links?|ethics statement|follow topics|receive email updates|sign up for|subscribe (to|for)|all rights reserved|support our journalism|share this (article|story)""",
)
/**
* A paragraph this long, in characters, is the article's own text; a page's subtitle and
* byline are shorter.
*/
private const val REAL_PARAGRAPH = 100
/** Blocks this short, in characters, around a date or an author's picture are a byline. */
private const val BYLINE_LENGTH = 160
private const val AUTHOR_BOX_LENGTH = 400
/** A short line that names the writer: "by Jane Doe", "By Jane Doe and John Roe". */
private val BY = Regex("""(?i)^\s*by\s+\S.{0,60}$""")
fun articleOf(document: Document, title: String): String? {
val fromJson = articleBodyFromJson(document)
document.select(
"script, style, noscript, iframe, form, nav, header, footer, aside, button, svg, input, " +
"select, textarea, template, dialog, canvas, object, embed, video, audio",
).remove()
val body = document.body()
for (el in body.getAllElements().toList()) {
if (el === body || el.tagName() == "article" || el.tagName() == "main") continue
val words = el.className() + " " + el.id()
if (UNLIKELY.containsMatchIn(words) && !LIKELY.containsMatchIn(words)) el.remove()
}
val scores = HashMap<Element, Double>()
for (el in body.select("p, pre, td, blockquote")) {
val text = el.text()
if (text.length < 25) continue
val score = 1.0 + text.count { it == ',' } + minOf(text.length / 100, 3)
val parent = el.parent() ?: continue
scores[parent] = (scores[parent] ?: initial(parent)) + score
parent.parent()?.let { grand -> scores[grand] = (scores[grand] ?: initial(grand)) + score / 2 }
}
val best = scores.maxByOrNull { (el, score) -> score * (1 - linkDensity(el)) }?.key
val found = best?.let { withSiblings(promote(it), scores, scores[it] ?: 0.0) }
// Measured before the tidying, which takes the page's own header off: the page keeps
// the links and the pictures that the structured data, plain text, does not have.
val foundLength = found?.text()?.length ?: 0
if (fromJson != null && Jsoup.parseBodyFragment(fromJson).text().length > foundLength * 1.3) return fromJson
return found?.also { tidy(it, title) }?.html()
}
/**
* Takes what the page puts around the article out of [root]: its own copy of the title
* (the view shows the title once, above), and everything before the first real paragraph
* (kicker, title, byline, date, the author's box, the lead picture) and after the last
* one (the author again, invitations to follow), and the site's notices in between.
*/
private fun tidy(root: Element, title: String) {
root.select("h1").remove()
val wanted = comparable(title)
if (wanted.isNotEmpty()) {
root.select("h2, h3, p, div, span").filter { comparable(it.text()) == wanted }.forEach { it.remove() }
}
root.select("p, div, span, aside, section, small")
.filter { el -> el.text().let { it.length < 300 && PROMO.containsMatchIn(it) } && el.select("p").size <= 1 }
.forEach { it.remove() }
// A subtitle the page has twice, for small and large screens: neither copy is text.
root.select("p, h2, h3").groupBy { comparable(it.text()) }
.filter { (text, copies) -> copies.size > 1 && text.length in 20..300 }
.values.flatten().forEach { it.remove() }
// The byline: the date with what is around it, a "by" line, the author's picture and note.
for (time in root.select("time")) outermostShort(time, root, BYLINE_LENGTH)?.takeIf { it !== time }?.remove()
root.select("p, div, span").filter { BY.matches(it.text()) && it.select("p").size <= 1 }.forEach { it.remove() }
for (img in root.select("a[href*=/author] img, a[href*=/people/] img, a[href*=/staff/] img")) {
outermostShort(img, root, AUTHOR_BOX_LENGTH)?.takeIf { it !== img }?.remove()
}
val paragraphs = root.select("p").filter { it.text().length >= REAL_PARAGRAPH }
paragraphs.firstOrNull()?.let { removeAround(it, root, before = true) }
paragraphs.lastOrNull()?.let { removeAround(it, root, before = false) }
}
/**
* The article's text where a page splits it into blocks side by side, with advertising
* between them: [top] with the blocks beside it that are of the same kind (the same
* classes) or hold a fair share of the text themselves, in their order. [top] alone
* when there are none.
*/
private fun withSiblings(top: Element, scores: Map<Element, Double>, bestScore: Double): Element {
val parent = top.parent() ?: return top
if (parent.tagName() == "body") return top
val threshold = max(10.0, bestScore * 0.2)
val kind = top.className()
// A block's score is that of its best-scoring part: the paragraphs' own container
// may lie a few wrappers deep.
val within = HashMap<Element, Double>()
for ((el, score) in scores) {
var node: Element? = el
while (node != null && node.parent() !== parent) node = node.parent()
if (node != null) within[node] = max(within[node] ?: 0.0, score)
}
val parts = parent.children().filter { sibling ->
sibling === top ||
(kind.isNotEmpty() && sibling.className() == kind) ||
(within[sibling] ?: 0.0) >= threshold && linkDensity(sibling) < 0.3 ||
(sibling.tagName() == "p" && sibling.text().length >= REAL_PARAGRAPH && linkDensity(sibling) < 0.25)
}
if (parts.size <= 1) return top
val joined = Element("div")
parts.toList().forEach { joined.appendChild(it) }
return joined
}
/** The largest element around [el], inside [root], with less than [limit] characters of text. */
private fun outermostShort(el: Element, root: Element, limit: Int): Element? {
var found: Element? = null
var current: Element? = el
while (current != null && current !== root && current.text().length < limit) {
found = current
current = current.parent()
}
return found
}
/** Removes everything in [root] before (or after) [el], keeping the elements around it. */
private fun removeAround(el: Element, root: Element, before: Boolean) {
var current: Element = el
while (current !== root) {
var node = if (before) current.previousSibling() else current.nextSibling()
while (node != null) {
val next = if (before) node.previousSibling() else node.nextSibling()
// After the text, a closing list, picture, quote or line still belongs to it;
// what goes is short: the author's name, a lone link.
if (before || !(node is Element && endsArticle(node))) node.remove()
node = next
}
current = current.parent() ?: return
}
}
private fun endsArticle(el: Element): Boolean =
el.select("ul, ol, figure, blockquote, table, img").isNotEmpty() ||
el.select("p").any { it.text().length >= 40 } ||
(el.tagName() == "p" && el.text().length >= 40)
/** Text reduced to its letters and digits, for telling whether two say the same. */
private fun comparable(text: String): String =
text.lowercase(Locale.ROOT).filter { it.isLetterOrDigit() }
/** Some kinds of element are likelier to hold the article than others. */
private fun initial(el: Element): Double = when {
el.attr("itemprop") == "articleBody" -> 25.0
el.tagName() == "article" -> 10.0
el.tagName() == "main" || el.tagName() == "div" -> 5.0
el.tagName() in TEXT_TAGS -> 3.0
el.tagName() in setOf("ul", "ol", "dl", "form") -> -3.0
el.tagName().matches(Regex("h[1-6]")) -> -5.0
else -> 0.0
}
/** An article element around the best text, when the text is one part of it. */
private fun promote(el: Element): Element {
var current = el
while (true) {
val parent = current.parent() ?: return current
if (parent.tagName() == "body") return current
val isArticle = parent.tagName() == "article" || parent.attr("itemprop") == "articleBody"
if (isArticle && parent.text().length < current.text().length * 2) return parent
if (parent.text().length > current.text().length * 1.25) return current
current = parent
}
}
/** The share of an element's text that is in links: menus and lists of stories are mostly that. */
private fun linkDensity(el: Element): Double {
val text = el.text().length
if (text == 0) return 1.0
val inLinks = el.select("a").sumOf { it.text().length }
return inLinks.toDouble() / text
}
/** Plain text as HTML: a paragraph per line, and lines that start with "* " or "- " as a list. */
private fun paragraphsOf(text: String): String {
val html = StringBuilder()
var inList = false
for (line in text.split('\n').map { it.trim() }.filter { it.isNotEmpty() }) {
val item = line.startsWith("* ") || line.startsWith("- ") || line.startsWith("• ")
if (item && !inList) html.append("<ul>")
if (!item && inList) html.append("</ul>")
inList = item
if (item) {
html.append("<li>").append(TextUtils.htmlEncode(line.drop(2).trim())).append("</li>")
} else {
html.append("<p>").append(TextUtils.htmlEncode(line)).append("</p>")
}
}
if (inList) html.append("</ul>")
return html.toString()
}
/** The article's text from the page's structured data, where a site gives it there. */
private fun articleBodyFromJson(document: Document): String? {
for (script in document.select("script[type=application/ld+json]")) {
val match = Regex(""""articleBody"\s*:\s*"((?:[^"\\]|\\.)*)"""").find(script.data()) ?: continue
val text = runCatching { kotlinxJson.decodeFromString<String>("\"${match.groupValues[1]}\"") }.getOrNull()
?: continue
if (text.length < MIN_FOUND_TEXT) continue
return paragraphsOf(text)
}
return null
}
}
}
@@ -0,0 +1,488 @@
package app.flexera.reader
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.Rect
import android.graphics.Typeface
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.RippleDrawable
import android.net.Uri
import android.text.TextUtils
import android.text.format.DateUtils
import android.util.TypedValue
import android.view.Gravity
import android.view.MotionEvent
import android.view.VelocityTracker
import android.view.View
import android.view.ViewConfiguration
import android.view.animation.DecelerateInterpolator
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.android.launcher3.Insettable
import com.android.launcher3.Launcher
import com.android.launcher3.R
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.roundToInt
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* A post of the RSS reader, read inside the reader instead of on its site. It slides in over
* the list from the side where text ends, with the post's picture, title, feed, date and author
* above its text. That is at first what the feed carries; when that is only the start of the
* article, the article's page is fetched and its text found in it ([ArticleStore]), and the
* view shows the whole of it as soon as it is there. The site itself is one tap away, on the
* "Visit article" button that stays at the bottom, within reach of the thumb.
*
* The text is shown by a [WebView] with no JavaScript and no access to files, given only
* cleaned HTML; a link in it opens in the browser. Back, the arrow at the top, or a swipe
* towards the side it came from takes the article away again.
*/
@SuppressLint("ViewConstructor")
internal class ArticleView(
private val launcher: Launcher,
private val onShare: (RssReader.Item) -> Unit,
/** How much of the list the article covers, from 0 to 1, whenever that changes. */
private val onCover: (Float) -> Unit,
) : FrameLayout(launcher), Insettable {
private companion object {
/** All but opaque: the list beneath is blurred away, and the text is read on near black. */
const val BACKGROUND = 0xFA0C0C0E.toInt()
const val BUTTON = 0xFFE8EAED.toInt()
const val BUTTON_TEXT = 0xFF202124.toInt()
const val PRESSED = 0x26FFFFFF
const val SLIDE_MS = 280L
/** Swiped this far, as a share of the width, letting go takes the article away. */
const val CLOSE_DISTANCE = 0.3f
const val FLICK_DP_PER_SECOND = 600f
/** How far Android's back preview draws the article aside before Back is let go. */
const val BACK_PEEK = 0.2f
}
private val density = resources.displayMetrics.density
private var web: WebView? = null
private val topShade = View(launcher)
private val bottomShade = View(launcher)
private val back = ImageView(launcher)
private val share = ImageView(launcher)
private val visit = TextView(launcher)
private var insets = Rect()
private var scope: CoroutineScope? = null
private var loading: Job? = null
private var animator: ValueAnimator? = null
/** The post shown, while the view is open. */
var item: RssReader.Item? = null
private set
val isOpen: Boolean get() = item != null
/** +1 when the article comes from the right, -1 from the left (right-to-left reading). */
private val side: Float get() = if (layoutDirection == LAYOUT_DIRECTION_RTL) -1f else 1f
private val touchSlop = ViewConfiguration.get(launcher).scaledTouchSlop
private var downX = 0f
private var downY = 0f
private var dragFrom = 0f
private var dragging = false
private var tracker: VelocityTracker? = null
init {
visibility = GONE
setBackgroundColor(BACKGROUND)
// Its own touches only: none goes through to the list beneath.
isClickable = true
topShade.background = GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, intArrayOf(BACKGROUND, Color.TRANSPARENT))
bottomShade.background = GradientDrawable(GradientDrawable.Orientation.BOTTOM_TOP, intArrayOf(BACKGROUND, Color.TRANSPARENT))
for (shade in listOf(topShade, bottomShade)) shade.importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO
addView(topShade, LayoutParams(LayoutParams.MATCH_PARENT, 0, Gravity.TOP))
addView(bottomShade, LayoutParams(LayoutParams.MATCH_PARENT, 0, Gravity.BOTTOM))
setUpIcon(back, R.drawable.ic_flexera_back, R.string.flexera_rss_back) { close(animate = true) }
setUpIcon(share, R.drawable.ic_flexera_share, R.string.flexera_rss_share) { item?.let(onShare) }
addView(back, LayoutParams(dp(48), dp(48), Gravity.TOP or Gravity.START))
addView(share, LayoutParams(dp(48), dp(48), Gravity.TOP or Gravity.END))
visit.setText(R.string.flexera_rss_visit_article)
visit.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f)
visit.setTextColor(BUTTON_TEXT)
visit.typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
visit.gravity = Gravity.CENTER
visit.minHeight = dp(48)
visit.setPadding(dp(20), dp(12), dp(24), dp(12))
visit.compoundDrawablePadding = dp(10)
visit.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_flexera_open_in_new, 0, 0, 0)
visit.compoundDrawableTintList = ColorStateList.valueOf(BUTTON_TEXT)
visit.compoundDrawableTintMode = PorterDuff.Mode.SRC_IN
visit.background = RippleDrawable(
ColorStateList.valueOf(0x33000000),
GradientDrawable().apply {
cornerRadius = dp(24).toFloat()
setColor(BUTTON)
},
null,
)
visit.elevation = dp(4).toFloat()
visit.setOnClickListener { item?.let { openOnSite(it.article.link) } }
addView(visit, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL))
}
override fun setTranslationX(translationX: Float) {
super.setTranslationX(translationX)
reportCover()
}
override fun setVisibility(visibility: Int) {
super.setVisibility(visibility)
reportCover()
}
private fun reportCover() {
val across = if (width > 0) width else (parent as? View)?.width ?: 0
val cover = when {
visibility != VISIBLE -> 0f
across <= 0 -> 1f
else -> (1f - abs(translationX) / across).coerceIn(0f, 1f)
}
// Called from the constructor too, before the callback is set.
@Suppress("SENSELESS_COMPARISON")
if (onCover != null) onCover(cover)
}
private fun setUpIcon(view: ImageView, icon: Int, description: Int, onClick: () -> Unit) {
view.setImageResource(icon)
view.contentDescription = resources.getString(description)
view.scaleType = ImageView.ScaleType.CENTER
view.background = RippleDrawable(ColorStateList.valueOf(PRESSED), null, ColorDrawable(Color.WHITE)).apply { radius = dp(24) }
view.setOnClickListener { onClick() }
}
override fun setInsets(insets: Rect) {
this.insets.set(insets)
(back.layoutParams as LayoutParams).apply {
topMargin = insets.top + dp(8)
marginStart = insets.left + dp(8)
}
(share.layoutParams as LayoutParams).apply {
topMargin = insets.top + dp(8)
marginEnd = insets.right + dp(8)
}
(visit.layoutParams as LayoutParams).bottomMargin = insets.bottom + dp(20)
topShade.layoutParams.height = insets.top + dp(72)
bottomShade.layoutParams.height = insets.bottom + dp(110)
requestLayout()
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
scope = MainScope()
}
override fun onDetachedFromWindow() {
scope?.cancel()
scope = null
web?.let {
removeView(it)
it.destroy()
}
web = null
item = null
visibility = GONE
super.onDetachedFromWindow()
}
/** Slides [post] in, showing what there is of it at once and the rest when it has come. */
fun open(post: RssReader.Item) {
item = post
loading?.cancel()
val view = webView()
view.scrollTo(0, 0)
show(post, ArticleStore.Readable(placeholderHtml(post), whole = false), loadingMore = false)
visibility = VISIBLE
bringToFront()
// Not laid out yet the first time: as wide as what it lies over.
val across = if (width > 0) width else (parent as? View)?.width ?: resources.displayMetrics.widthPixels
slideTo(0f, from = side * across)
val scope = scope ?: return
loading = scope.launch {
val first = withContext(Dispatchers.IO) { ArticleStore.fromFeed(launcher, post) }
if (item !== post) return@launch
val online = !first.whole && post.article.link.isNotEmpty()
show(post, first, loadingMore = online)
if (!online) return@launch
val whole = withContext(Dispatchers.IO) {
runCatching { ArticleStore.fromPage(launcher, post, ArticleStore.textLength(first.html)) }.getOrNull()
}
if (item !== post) return@launch
if (whole != null) {
show(post, ArticleStore.Readable(whole, whole = true), loadingMore = false, keepScroll = true)
} else {
show(post, first, loadingMore = false, keepScroll = true)
}
}
}
/** Takes the article away, sliding it out when [animate]. */
fun close(animate: Boolean) {
if (!isOpen) return
item = null
loading?.cancel()
loading = null
if (animate && isShown) {
slideTo(side * width, from = translationX) { finishClose() }
} else {
cancelAnimation()
finishClose()
}
}
private fun finishClose() {
if (isOpen) return
visibility = GONE
translationX = 0f
// Frees the page and stops pictures still loading.
web?.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
}
fun onBackStarted() = cancelAnimation()
fun onBackProgressed(progress: Float) {
translationX = side * BACK_PEEK * progress * width
}
fun onBackCancelled() {
if (isOpen) slideTo(0f, from = translationX)
}
private fun slideTo(target: Float, from: Float, then: (() -> Unit)? = null) {
cancelAnimation()
translationX = from
val anim = ValueAnimator.ofFloat(from, target)
anim.duration = SLIDE_MS
anim.interpolator = DecelerateInterpolator(1.5f)
anim.addUpdateListener { translationX = it.animatedValue as Float }
anim.addListener(object : AnimatorListenerAdapter() {
private var cancelled = false
override fun onAnimationCancel(animation: Animator) {
cancelled = true
}
override fun onAnimationEnd(animation: Animator) {
if (animator === anim) animator = null
if (!cancelled) then?.invoke()
}
})
animator = anim
anim.start()
}
private fun cancelAnimation() {
animator?.let {
animator = null
it.cancel()
}
}
@SuppressLint("SetJavaScriptEnabled")
private fun webView(): WebView {
web?.let { return it }
val view = WebView(launcher)
view.setBackgroundColor(Color.TRANSPARENT)
view.settings.apply {
javaScriptEnabled = false
allowFileAccess = false
allowContentAccess = false
domStorageEnabled = false
setSupportZoom(false)
builtInZoomControls = false
mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW
textZoom = (resources.configuration.fontScale * 100).roundToInt()
}
view.isVerticalScrollBarEnabled = false
view.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
openOnSite(request.url.toString())
return true
}
override fun onPageFinished(view: WebView, url: String?) {
val scroll = pendingScroll
pendingScroll = -1
if (scroll > 0) view.scrollTo(0, scroll)
}
}
addView(view, 0, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
web = view
return view
}
private var pendingScroll = -1
private fun show(post: RssReader.Item, readable: ArticleStore.Readable, loadingMore: Boolean, keepScroll: Boolean = false) {
val view = webView()
pendingScroll = if (keepScroll) view.scrollY else -1
val note = when {
loadingMore -> resources.getString(R.string.flexera_rss_loading_article)
!readable.whole -> resources.getString(R.string.flexera_rss_article_partial)
else -> null
}
val base = post.article.link.ifEmpty { post.article.feedUrl }
view.loadDataWithBaseURL(base, document(post, readable.html, note), "text/html", "utf-8", null)
}
/** Before anything is read: the summary, which is always there. */
private fun placeholderHtml(post: RssReader.Item): String =
post.article.summary.takeIf { it.isNotEmpty() }?.let { "<p>${TextUtils.htmlEncode(it)}</p>" }.orEmpty()
/** The page the view shows: the post's picture, title and details, then its text. */
private fun document(post: RssReader.Item, body: String, note: String?): String {
val article = post.article
val top = (insets.top / density).roundToInt() + 64
val bottom = (insets.bottom / density).roundToInt() + 112
val hero = article.imageUrl?.replaceFirst("http://", "https://")
val date = DateUtils.formatDateTime(
launcher,
article.published,
DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_TIME or DateUtils.FORMAT_ABBREV_MONTH,
)
val details = listOfNotNull(post.source, date, article.author).joinToString(" · ") { TextUtils.htmlEncode(it) }
val icon = post.iconUrl?.let { """<img class="icon" src="${TextUtils.htmlEncode(it)}" alt="">""" }.orEmpty()
return """<!doctype html><html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="dark">
<style>
html,body{margin:0;padding:0;background:transparent}
body{padding:${top}px 22px ${bottom}px;color:rgba(255,255,255,.87);font-family:sans-serif;font-size:17px;line-height:1.65;overflow-wrap:anywhere;-webkit-text-size-adjust:100%}
.hero{display:block;width:100%;aspect-ratio:16/9;object-fit:cover;border-radius:20px;margin:0 0 22px;background:rgba(255,255,255,.06)}
h1.title{font-size:27px;line-height:1.25;font-weight:600;color:#fff;margin:0 0 14px}
.details{display:flex;align-items:center;gap:10px;color:rgba(255,255,255,.6);font-size:14px;line-height:1.4;margin:0 0 26px}
.details .icon{width:22px;height:22px;border-radius:50%;flex:none;background:rgba(255,255,255,.1)}
a{color:#8ab4f8;text-decoration:none}
img,video{max-width:100%;height:auto;border-radius:14px}
figure{margin:26px 0}figcaption{font-size:13px;line-height:1.45;color:rgba(255,255,255,.55);margin-top:8px}
blockquote{margin:22px 0;padding:0 0 0 16px;border-left:3px solid rgba(255,255,255,.3);color:rgba(255,255,255,.75)}
h2,h3,h4,h5,h6{color:#fff;line-height:1.3;margin:30px 0 12px}h2{font-size:22px}h3{font-size:19px}h4,h5,h6{font-size:17px}
pre{white-space:pre-wrap;background:rgba(255,255,255,.08);padding:12px 14px;border-radius:12px;font-size:14px}
code{font-size:.9em}
table{display:block;overflow-x:auto;border-collapse:collapse;font-size:15px}td,th{border:1px solid rgba(255,255,255,.15);padding:6px 8px}
hr{border:0;border-top:1px solid rgba(255,255,255,.15);margin:30px 0}
ul,ol{padding-left:22px}
.note{margin:30px 0 0;padding:14px 16px;border-radius:16px;background:rgba(255,255,255,.08);color:rgba(255,255,255,.7);font-size:15px;line-height:1.5}
</style></head><body>
${hero?.let { """<img class="hero" src="${TextUtils.htmlEncode(it)}" alt="">""" }.orEmpty()}
<h1 class="title">${TextUtils.htmlEncode(article.title)}</h1>
<div class="details">$icon<span>$details</span></div>
<div class="body">$body</div>
${note?.let { """<p class="note">${TextUtils.htmlEncode(it)}</p>""" }.orEmpty()}
</body></html>"""
}
private fun openOnSite(link: String) {
if (link.isEmpty()) return
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
try {
launcher.startActivity(intent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(launcher, R.string.flexera_rss_no_app, Toast.LENGTH_SHORT).show()
}
}
// A swipe towards the side the article came from takes it away, as Back does.
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
track(ev)
when (ev.actionMasked) {
MotionEvent.ACTION_DOWN -> {
downX = ev.x
downY = ev.y
dragging = false
}
MotionEvent.ACTION_MOVE -> if (startsDrag(ev)) return true
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> stopTracking()
}
return false
}
override fun onTouchEvent(ev: MotionEvent): Boolean {
track(ev)
when (ev.actionMasked) {
MotionEvent.ACTION_MOVE -> {
if (!dragging) startsDrag(ev)
if (dragging) translationX = side * max(0f, side * (ev.rawX - dragFrom))
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
if (dragging) {
dragging = false
val velocity = tracker?.let {
it.computeCurrentVelocity(1000)
it.xVelocity * side
} ?: 0f
val flick = FLICK_DP_PER_SECOND * density
val away = ev.actionMasked == MotionEvent.ACTION_UP && when {
velocity >= flick -> true
velocity <= -flick -> false
else -> abs(translationX) > width * CLOSE_DISTANCE
}
if (away) close(animate = true) else slideTo(0f, from = translationX)
}
stopTracking()
}
}
return true
}
private fun startsDrag(ev: MotionEvent): Boolean {
if (!isOpen || animator != null) return false
val dx = (ev.x - downX) * side
val dy = ev.y - downY
if (dx > touchSlop && dx > abs(dy) * 1.5f) {
dragging = true
dragFrom = ev.rawX - translationX
parent?.requestDisallowInterceptTouchEvent(true)
return true
}
return false
}
private fun track(ev: MotionEvent) {
if (ev.actionMasked == MotionEvent.ACTION_DOWN) stopTracking()
// Raw positions: the view itself moves under the finger.
val raw = MotionEvent.obtain(ev).apply { setLocation(ev.rawX, ev.rawY) }
(tracker ?: VelocityTracker.obtain().also { tracker = it }).addMovement(raw)
raw.recycle()
}
private fun stopTracking() {
tracker?.recycle()
tracker = null
}
private fun dp(value: Int): Int = (value * density + 0.5f).toInt()
}
@@ -0,0 +1,70 @@
package app.flexera.reader
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.ColorFilter
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.widget.ImageView
import java.util.Locale
/** A picture as wide as it is laid out, and [ratio] times less high. */
internal class RatioImageView(context: Context, private val ratio: Float) : ImageView(context) {
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val width = MeasureSpec.getSize(widthMeasureSpec)
super.onMeasure(
MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec((width / ratio).toInt(), MeasureSpec.EXACTLY),
)
}
}
/**
* A feed's first letter on a round patch of colour, for a feed whose site has no icon, and
* while the icon loads. The colour comes from the name, so a feed always has the same one.
*/
internal class LetterDrawable(name: String) : Drawable() {
private companion object {
/** Muted colours that white reads well on, over the reader's dark backdrop. */
val COLORS = intArrayOf(
0xFF5C6BC0.toInt(), 0xFF26A69A.toInt(), 0xFFEF6C00.toInt(), 0xFF8E24AA.toInt(),
0xFF43A047.toInt(), 0xFFD81B60.toInt(), 0xFF1E88E5.toInt(), 0xFF6D4C41.toInt(),
)
}
private val letter = name.trim().firstOrNull { it.isLetterOrDigit() }?.toString()?.uppercase(Locale.getDefault()) ?: "•"
private val circle = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = COLORS[Math.floorMod(name.hashCode(), COLORS.size)]
}
private val text = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.WHITE
textAlign = Paint.Align.CENTER
typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
}
override fun draw(canvas: Canvas) {
val b = bounds
val radius = minOf(b.width(), b.height()) / 2f
canvas.drawCircle(b.exactCenterX(), b.exactCenterY(), radius, circle)
text.textSize = radius * 1.1f
val y = b.exactCenterY() - (text.descent() + text.ascent()) / 2
canvas.drawText(letter, b.exactCenterX(), y, text)
}
override fun setAlpha(alpha: Int) {
circle.alpha = alpha
text.alpha = alpha
}
override fun setColorFilter(colorFilter: ColorFilter?) {
circle.colorFilter = colorFilter
text.colorFilter = colorFilter
}
@Deprecated("Deprecated in Java")
override fun getOpacity(): Int = PixelFormat.TRANSLUCENT
}
@@ -0,0 +1,526 @@
package app.flexera.reader
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Rect
import android.view.MotionEvent
import android.view.VelocityTracker
import android.view.View
import android.view.ViewConfiguration
import android.view.ViewGroup
import android.view.animation.DecelerateInterpolator
import android.widget.FrameLayout
import android.window.BackEvent
import app.flexera.drawer.FlexeraDrawer
import app.flexera.home.FolderBlur
import app.flexera.home.QuickLaunch
import app.lawnchair.gestures.config.GestureHandlerConfig
import app.lawnchair.preferences2.PreferenceManager2
import app.lawnchair.preferences2.firstCached
import com.android.launcher3.AbstractFloatingView
import com.android.launcher3.Insettable
import com.android.launcher3.InsettableFrameLayout
import com.android.launcher3.Launcher
import com.android.launcher3.LauncherState
import com.android.launcher3.Utilities
import com.android.launcher3.statemanager.StateManager
import com.android.launcher3.util.SystemUiController
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.roundToInt
/**
* The RSS reader's page. It comes in as quick launch's app page does: a swipe past the first or
* the last home screen page moves the home screen aside with the finger, and the page follows
* from that edge ([QuickLaunch]); another gesture brings it in on its own ([open]). The home
* screen blurs and darkens on its way out, and the page has the app drawer's backdrop: the
* blurred wallpaper under the drawer's dark tint, with white text. Unlike the app page, it
* stays: the owner reads, opens posts, and comes back to it.
*
* It leaves by a swipe back towards the home screen, by Back (with Android's back preview), by
* Home, by the home gesture, and whenever the launcher goes to another state. Launcher3 closes
* its floating views at all those moments, but the page cannot be one: it lies over the drag
* layer, which moves aside under it. So while the page is in, a stand-in floating view of no
* size is in the drag layer ([Sentinel], [AbstractFloatingView.TYPE_FLEXERA_READER]), which
* Launcher3 closes there, and its closing takes the page out. Opening a post leaves it in:
* that type survives the launcher's stop and its return by Back.
*
* The home screen is moved by its drawing only, as for the app page
* ([View.setAnimationMatrix] on the drag layer), so that the pull still reaches the pages.
*/
class ReaderPage private constructor(private val launcher: Launcher) : QuickLaunch.EdgePage {
companion object {
/** How dark the home screen gets beside a page that is all the way in. */
private const val HOME_DIM = 0.35f
/** Swiped back out this far, as a share of the width, letting go closes the page. */
private const val CLOSE_DISTANCE = 0.3f
/** How far Android's back preview draws the page aside before Back is let go. */
private const val BACK_PEEK = 0.12f
private const val FLICK_DP_PER_SECOND = 600f
/** The page settles at least this fast, in dp per second, and within these times. */
private const val MIN_SETTLE_DP_PER_SECOND = 1500f
private const val MIN_SETTLE_MS = 160L
private const val MAX_SETTLE_MS = 320L
/**
* [launcher]'s page, made when first wanted; null while the launcher has no views. Found
* through its view among the launcher's own, never kept here, as for the app page.
*/
fun of(launcher: Launcher): ReaderPage? {
val root = launcher.rootView ?: return null
if (launcher.dragLayer == null) return null
return pageIn(root) ?: ReaderPage(launcher)
}
/** Whether [launcher]'s page is on the screen, all or part of it. */
@JvmStatic
fun isShowing(launcher: Launcher): Boolean =
(launcher.rootView?.let { pageIn(it) }?.progress ?: 0f) > 0f
/** Brings the page in on its own, for a gesture other than the swipe past a page. */
fun open(launcher: Launcher) {
if (!launcher.isInState(LauncherState.NORMAL)) return
of(launcher)?.openOnItsOwn()
}
private fun pageIn(root: ViewGroup): ReaderPage? {
for (i in 0 until root.childCount) {
(root.getChildAt(i) as? PageView)?.let { return it.page }
}
return null
}
/** The blur for how far the page is in: quick at first, so the home screen soon recedes. */
private fun blurFor(progress: Float): Float {
val left = 1f - progress
return 1f - left * left
}
}
/** How far the page is in, from 0 (not at all) to 1 (it fills the screen). */
var progress = 0f
private set
/** Whether the page comes in from the left edge of the screen, rather than the right. */
private var fromLeft = true
/** Where the page is going, or is: 1 in, 0 out. */
private var target = 0f
private var animator: ValueAnimator? = null
private var sentinel: Sentinel? = null
private var backFrom = 1f
/** Whether the back gesture under way takes away an open post rather than the page. */
private var backOnArticle = false
private val shift = Matrix()
private val view = PageView(launcher)
private val content = ReaderView(launcher)
private val density = launcher.resources.displayMetrics.density
init {
view.visibility = View.INVISIBLE
view.addView(content, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
// Over the whole window, the status and navigation bars included; it pads itself.
val params = InsettableFrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT,
).apply { ignoreInsets = true }
launcher.rootView.addView(view, params)
// The app drawer, the recent apps and the like are in the drag layer, which the page
// keeps aside; they must not come up there. Closing by the stand-in does this too,
// animated; this makes it at once.
launcher.stateManager.addStateListener(object : StateManager.StateListener<LauncherState> {
override fun onStateTransitionStart(toState: LauncherState) {
if (toState != LauncherState.NORMAL && progress > 0f) reset()
}
})
}
override val isBusy: Boolean
get() = target == 1f
override fun begin(fromLeft: Boolean): Float {
cancelAnimation()
if (this.fromLeft != fromLeft) {
show(0f)
this.fromLeft = fromLeft
}
return progress
}
override fun show(progress: Float) {
this.progress = progress.coerceIn(0f, 1f)
apply()
}
override fun settle(open: Boolean, speed: Float, launch: () -> Unit) = settleTo(open, speed)
override fun close() = settleTo(open = false, speed = 0f)
/** Out at once, with nothing to see on the way. */
fun reset() {
cancelAnimation()
target = 0f
removeSentinel()
show(0f)
content.onClosed()
}
private fun openOnItsOwn() {
if (target == 1f) return
begin(fromLeft = sideForGestures())
settleTo(open = true, speed = 0f)
}
/**
* The side the page comes in from for other gestures: that of the swipe past a page that
* opens the reader, the first page's when both or neither do.
*/
private fun sideForGestures(): Boolean {
val prefs = PreferenceManager2.getInstance(launcher)
val firstOpens = prefs.firstPageSwipeGestureHandler.firstCached() is GestureHandlerConfig.OpenRssReader
val lastOpens = prefs.lastPageSwipeGestureHandler.firstCached() is GestureHandlerConfig.OpenRssReader
val firstPage = firstOpens || !lastOpens
// The first page's missing neighbour is on the left, or on the right when reading from
// right to left.
return firstPage != Utilities.isRtl(launcher.resources)
}
private fun settleTo(open: Boolean, speed: Float) {
cancelAnimation()
target = if (open) 1f else 0f
if (open) {
addSentinel()
content.onOpening()
RssReader.refreshIfStale(launcher)
} else {
removeSentinel()
}
if (progress == target) {
settled()
return
}
val remaining = abs(target - progress) * view.rootWidth()
val minSpeed = MIN_SETTLE_DP_PER_SECOND * density
// A decelerating move starts at twice its average speed.
val duration = (2000f * remaining / max(speed, minSpeed)).toLong()
val anim = ValueAnimator.ofFloat(progress, target)
anim.duration = duration.coerceIn(MIN_SETTLE_MS, MAX_SETTLE_MS)
anim.interpolator = DecelerateInterpolator()
anim.addUpdateListener { show(it.animatedValue as Float) }
anim.addListener(object : AnimatorListenerAdapter() {
private var cancelled = false
override fun onAnimationCancel(animation: Animator) {
cancelled = true
}
override fun onAnimationEnd(animation: Animator) {
if (animator === anim) animator = null
if (!cancelled) settled()
}
})
animator = anim
anim.start()
}
private fun settled() {
if (target == 0f) content.onClosed()
}
private fun cancelAnimation() {
animator?.let {
animator = null
it.cancel()
}
}
private fun addSentinel() {
if (sentinel != null) return
val stand = Sentinel(launcher, this)
launcher.dragLayer.addView(stand, 0, 0)
sentinel = stand
}
private fun removeSentinel() {
val stand = sentinel ?: return
sentinel = null
stand.close(false)
}
/** Launcher3 has closed the stand-in: the page goes too, [animate]d if it is seen. */
private fun onSentinelClosed(stand: Sentinel, animate: Boolean) {
if (sentinel !== stand) return
sentinel = null
if (animate && view.isShown && launcher.hasWindowFocus()) {
settleTo(open = false, speed = 0f)
} else {
reset()
}
}
private fun onBackStarted() {
backOnArticle = content.isArticleOpen
if (backOnArticle) {
content.onArticleBackStarted()
return
}
cancelAnimation()
backFrom = progress
}
private fun onBackProgressed(backProgress: Float) {
if (backOnArticle) {
content.onArticleBackProgressed(backProgress)
return
}
show(backFrom - BACK_PEEK * backProgress)
}
private fun onBackCancelled() {
if (backOnArticle) {
backOnArticle = false
content.onArticleBackCancelled()
return
}
if (target == 1f) settleTo(open = true, speed = 0f)
}
/** Back: an open post goes first, then the page. True when it was a post. */
private fun onBackInvoked(): Boolean {
backOnArticle = false
if (!content.isArticleOpen) return false
content.closeArticle(animate = true)
return true
}
private fun apply() {
val p = progress
view.visibility = if (p > 0f) View.VISIBLE else View.INVISIBLE
val width = view.rootWidth().toFloat()
content.translationX = (if (fromLeft) -1f else 1f) * (1f - p) * width
view.invalidate()
val dragLayer = launcher.dragLayer
if (p > 0f) {
shift.setTranslate((if (fromLeft) 1f else -1f) * p * width, 0f)
dragLayer.setAnimationMatrix(shift)
} else {
dragLayer.setAnimationMatrix(null)
}
// As strong as behind the app drawer, which the page looks like.
launcher.depthController?.quickLaunchBlur?.value = blurFor(p) * FolderBlur.FULL_SCREEN_STRENGTH
// Light status bar icons once the page is most of what is seen.
launcher.systemUiController?.updateUiState(
SystemUiController.UI_STATE_RSS_READER,
if (p >= 0.5f) SystemUiController.FLAG_DARK_STATUS or SystemUiController.FLAG_DARK_NAV else 0,
)
}
/** The width the page and the home screen move across; known before this view's first layout. */
private fun View.rootWidth(): Int = if (width > 0) width else launcher.dragLayer.width
/**
* The page's view: the backdrop and the dimmed home screen beside it, the reader's content
* over them, and the swipe that takes the page back out.
*/
private inner class PageView(context: Context) : FrameLayout(context), Insettable {
val page: ReaderPage get() = this@ReaderPage
private val backdropPaint = Paint().apply { color = FlexeraDrawer.BACKDROP_COLOR }
private val dimPaint = Paint().apply { color = android.graphics.Color.BLACK }
private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop
private val flickSpeed = FLICK_DP_PER_SECOND * density
private var downX = 0f
private var downY = 0f
private var dragFrom = 0f
private var dragging = false
/** A sideways move away from the home screen: kept from the posts, and does nothing. */
private var swallowing = false
private var tracker: VelocityTracker? = null
init {
setWillNotDraw(false)
}
override fun setInsets(insets: Rect) {
content.setInsets(insets)
}
override fun onDraw(canvas: Canvas) {
val w = width.toFloat()
val h = height.toFloat()
val edge = progress * w
dimPaint.alpha = (HOME_DIM * progress * 255).roundToInt()
if (fromLeft) {
canvas.drawRect(0f, 0f, edge, h, backdropPaint)
canvas.drawRect(edge, 0f, w, h, dimPaint)
} else {
canvas.drawRect(w - edge, 0f, w, h, backdropPaint)
canvas.drawRect(0f, 0f, w - edge, h, dimPaint)
}
}
/**
* While the page moves on its own, a touch does not wait for it. Going in, the page is
* put all the way in and takes the touch. Going out, the home screen is put back at
* once, and the touch goes through to it when the home screen was drawn so little
* aside that every icon was still within its own place, as for the app page.
*/
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
if (ev.actionMasked == MotionEvent.ACTION_DOWN && animator != null) {
if (target == 1f) {
cancelAnimation()
show(1f)
} else {
val aside = progress * width
reset()
return aside >= launcher.deviceProfile.cellHorizontalSpace / 2f
}
}
return super.dispatchTouchEvent(ev)
}
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
track(ev)
when (ev.actionMasked) {
MotionEvent.ACTION_DOWN -> {
downX = ev.x
downY = ev.y
dragging = false
swallowing = false
}
MotionEvent.ACTION_MOVE -> if (startsDrag(ev)) return true
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> stopTracking()
}
return false
}
/** Every touch on the page is the page's, so that none reaches the home screen behind. */
override fun onTouchEvent(ev: MotionEvent): Boolean {
track(ev)
when (ev.actionMasked) {
MotionEvent.ACTION_DOWN -> {
downX = ev.x
downY = ev.y
dragging = false
swallowing = false
}
MotionEvent.ACTION_MOVE -> {
if (!dragging && !swallowing) startsDrag(ev)
if (dragging) {
val back = if (fromLeft) dragFrom - ev.x else ev.x - dragFrom
show(1f - max(0f, back) / max(1, width))
}
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
if (dragging) {
dragging = false
val velocity = tracker?.let {
it.computeCurrentVelocity(1000)
it.xVelocity
} ?: 0f
val backSpeed = if (fromLeft) -velocity else velocity
val open = ev.actionMasked == MotionEvent.ACTION_CANCEL || when {
backSpeed >= flickSpeed -> false
backSpeed <= -flickSpeed -> true
else -> progress > 1f - CLOSE_DISTANCE
}
settleTo(open, abs(velocity))
}
stopTracking()
}
}
return true
}
/**
* A sideways move towards the home screen, while the page is in, takes the page out.
* Not while a post is open over the list: the post has a swipe of its own.
*/
private fun startsDrag(ev: MotionEvent): Boolean {
if (target != 1f || content.isArticleOpen) return false
val dx = ev.x - downX
val dy = ev.y - downY
val back = if (fromLeft) -dx else dx
if (back > touchSlop && back > abs(dy) * 1.5f) {
dragging = true
dragFrom = ev.x
cancelAnimation()
parent?.requestDisallowInterceptTouchEvent(true)
return true
}
// The other way, a sideways swipe would end as a tap on the post under it.
if (-back > touchSlop && -back > abs(dy) * 1.5f) {
swallowing = true
return true
}
return false
}
private fun track(ev: MotionEvent) {
if (ev.actionMasked == MotionEvent.ACTION_DOWN) stopTracking()
val t = tracker ?: VelocityTracker.obtain().also { tracker = it }
t.addMovement(ev)
}
private fun stopTracking() {
tracker?.recycle()
tracker = null
}
}
/**
* Stands in for the page among Launcher3's floating views while the page is in; see the
* class comment. It has no size and draws nothing.
*/
private class Sentinel(context: Context, private val page: ReaderPage) :
AbstractFloatingView(context, null) {
init {
mIsOpen = true
}
override fun handleClose(animate: Boolean) {
(parent as? ViewGroup)?.removeView(this)
page.onSentinelClosed(this, animate)
}
override fun isOfType(type: Int): Boolean = type and AbstractFloatingView.TYPE_FLEXERA_READER != 0
override fun onControllerInterceptTouchEvent(ev: MotionEvent?): Boolean = false
override fun onBackStarted(backEvent: BackEvent) {
page.onBackStarted()
}
override fun onBackProgressed(backEvent: BackEvent) {
page.onBackProgressed(backEvent.progress)
}
override fun onBackCancelled() {
page.onBackCancelled()
}
override fun onBackInvoked() {
if (!page.onBackInvoked()) super.onBackInvoked()
}
}
}
@@ -0,0 +1,670 @@
package app.flexera.reader
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.Outline
import android.graphics.Rect
import android.graphics.RenderEffect
import android.graphics.Shader
import android.graphics.Typeface
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.RippleDrawable
import android.os.Build
import android.text.TextUtils
import android.text.format.DateUtils
import android.util.TypedValue
import android.view.Gravity
import android.view.HapticFeedbackConstants
import android.view.View
import android.view.ViewGroup
import android.view.ViewOutlineProvider
import android.view.animation.LinearInterpolator
import android.widget.EdgeEffect
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import app.flexera.update.FlexeraUpdater
import app.lawnchair.ui.preferences.PreferenceActivity
import app.lawnchair.ui.preferences.navigation.GesturesRssReader
import coil.ImageLoader
import coil.disk.DiskCache
import coil.memory.MemoryCache
import coil.request.ImageRequest
import coil.util.CoilUtils
import com.android.launcher3.BaseActivity
import com.android.launcher3.Insettable
import com.android.launcher3.Launcher
import com.android.launcher3.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
/**
* What the RSS reader's page shows ([ReaderPage]): a heading that scrolls away with the list,
* with refresh and the feeds' settings beside it, and every feed's posts together, the newest
* first, each on a card ([PostHolder]). A tap opens the post in the reader itself
* ([ArticleView]), and it is shown dimmed from then on; the share button or a long press shares
* its link. Pulling the list down at the top fetches the feeds anew.
*/
internal class ReaderView(private val launcher: Launcher) : FrameLayout(launcher), Insettable {
private companion object {
/** Pulled down this far, as a share of the list's height, letting go fetches anew. */
const val REFRESH_PULL = 0.12f
const val SIDE_DP = 20
const val CARD_SIDE_DP = 12
const val CARD_CORNER_DP = 24
const val ICON_DP = 20
/** A card's picture is this many times as wide as it is high. */
const val PICTURE_RATIO = 16f / 9f
/** A card: a little lighter than the backdrop it lies on. */
const val CARD = 0x1FFFFFFF
const val PRIMARY = Color.WHITE
const val SECONDARY = 0x99FFFFFF.toInt()
const val READ_PRIMARY = 0x80FFFFFF.toInt()
const val READ_SECONDARY = 0x59FFFFFF.toInt()
const val PRESSED = 0x26FFFFFF
const val PILL = 0x26FFFFFF
/** The status bar's shade over posts that scroll under it. */
const val TOP_SHADE = 0xCC000000.toInt()
const val REQUEST_LOCAL_NETWORK = 0x5253
@Volatile
var loader: ImageLoader? = null
/** One picture loader for the reader, with its own small caches. */
fun images(context: Context): ImageLoader = loader ?: synchronized(this) {
loader ?: ImageLoader.Builder(context.applicationContext)
.memoryCache { MemoryCache.Builder(context.applicationContext).maxSizePercent(0.05).build() }
.diskCache {
DiskCache.Builder()
.directory(context.applicationContext.cacheDir.resolve("flexera_rss_pictures"))
.maxSizeBytes(40L * 1024 * 1024)
.build()
}
.crossfade(true)
.build()
.also { loader = it }
}
}
private sealed class Row {
data class Header(
val subtitle: String,
val refreshing: Boolean,
val askLocalNetwork: Boolean,
) : Row()
data class Message(val kind: Kind, val detail: String = "") : Row()
data class Post(val item: RssReader.Item) : Row()
}
private enum class Kind { NO_FEEDS, LOADING, FAILED, NOTHING }
private val density = resources.displayMetrics.density
private val list = RecyclerView(launcher)
private val shade = View(launcher)
private val adapter = Adapter()
private val article = ArticleView(launcher, onShare = { sharePost(it) }, onCover = ::coverList)
/** How far the list is blurred behind an open post: as strong as behind the app drawer. */
private val maxListBlur = 40f * resources.displayMetrics.density
/**
* The list beneath a post that slides in blurs and dims the more of it the post covers, and
* is not drawn at all once covered: the post's text is read on its own.
*/
private fun coverList(cover: Float) {
val hidden = cover >= 1f
list.visibility = if (hidden) View.INVISIBLE else View.VISIBLE
shade.visibility = list.visibility
list.alpha = 1f - 0.5f * cover
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val radius = maxListBlur * cover
list.setRenderEffect(
if (radius < 1f || hidden) null else RenderEffect.createBlurEffect(radius, radius, Shader.TileMode.CLAMP),
)
}
}
private var scope: CoroutineScope? = null
private var state = RssReader.State()
private var topInset = 0
init {
list.layoutManager = LinearLayoutManager(launcher)
list.adapter = adapter
list.clipToPadding = false
// A pull at the top fetches anew, also when the posts do not fill the screen.
list.overScrollMode = View.OVER_SCROLL_ALWAYS
list.edgeEffectFactory = RefreshEdgeFactory()
(list.itemAnimator as? SimpleItemAnimator)?.supportsChangeAnimations = false
addView(list, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
shade.background = GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, intArrayOf(TOP_SHADE, Color.TRANSPARENT))
shade.importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO
addView(shade, LayoutParams(LayoutParams.MATCH_PARENT, 0))
addView(article, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
}
/** Whether a post is open over the list. */
val isArticleOpen: Boolean get() = article.isOpen
/** Back while a post is open takes the post away, with Android's back preview. */
fun onArticleBackStarted() = article.onBackStarted()
fun onArticleBackProgressed(progress: Float) = article.onBackProgressed(progress)
fun onArticleBackCancelled() = article.onBackCancelled()
fun closeArticle(animate: Boolean) = article.close(animate)
override fun setInsets(insets: Rect) {
topInset = insets.top
list.setPadding(insets.left, 0, insets.right, insets.bottom + dp(24))
shade.layoutParams = (shade.layoutParams as LayoutParams).apply { height = insets.top + dp(12) }
adapter.notifyItemChanged(0)
article.setInsets(insets)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
val newScope = MainScope()
scope = newScope
newScope.launch { RssReader.state(launcher).collect { bind(it) } }
}
override fun onDetachedFromWindow() {
scope?.cancel()
scope = null
super.onDetachedFromWindow()
}
/** The page is going in: the ages shown are brought up to date. */
fun onOpening() {
bind(state)
adapter.notifyItemRangeChanged(0, adapter.itemCount)
}
/** The page is out; so is any post that was open. */
fun onClosed() = article.close(animate = false)
private fun bind(newState: RssReader.State) {
state = newState
val rows = ArrayList<Row>()
rows += Row.Header(
subtitle = subtitle(newState),
refreshing = newState.refreshing,
askLocalNetwork = newState.failures.any { it.problem == RssProblem.LOCAL_NETWORK },
)
when {
!newState.loaded -> Unit
newState.feeds.isEmpty() -> rows += Row.Message(Kind.NO_FEEDS)
newState.items.isNotEmpty() -> newState.items.mapTo(rows) { Row.Post(it) }
newState.refreshing -> rows += Row.Message(Kind.LOADING)
newState.failures.isNotEmpty() ->
rows += Row.Message(Kind.FAILED, problemText(context, newState.failures.first().problem))
else -> rows += Row.Message(Kind.NOTHING)
}
val atTop = !list.canScrollVertically(-1)
adapter.submitList(rows) { if (atTop) list.scrollToPosition(0) }
}
private fun subtitle(state: RssReader.State): String {
val res = resources
if (state.feeds.isEmpty()) return ""
if (state.refreshing) return res.getString(R.string.flexera_rss_updating)
val parts = ArrayList<String>()
if (state.lastRefresh > 0) {
val ago = System.currentTimeMillis() - state.lastRefresh
parts += if (ago < DateUtils.MINUTE_IN_MILLIS) {
res.getString(R.string.flexera_rss_just_updated)
} else {
res.getString(R.string.flexera_rss_updated, age(state.lastRefresh).replaceFirstChar { it.lowercase() })
}
}
if (state.failures.isNotEmpty() && state.items.isNotEmpty()) {
parts += res.getQuantityString(R.plurals.flexera_rss_failed_feeds, state.failures.size, state.failures.size)
}
return parts.joinToString(" · ")
}
private fun age(millis: Long): String {
val now = System.currentTimeMillis()
if (now - millis < DateUtils.MINUTE_IN_MILLIS) return resources.getString(R.string.flexera_rss_just_now)
return DateUtils.getRelativeTimeSpanString(millis, now, DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE).toString()
}
private fun openPost(item: RssReader.Item) {
RssReader.markRead(launcher, item.article)
article.open(item)
}
private fun sharePost(item: RssReader.Item) {
val link = item.article.link
if (link.isEmpty()) return
val send = Intent(Intent.ACTION_SEND)
.setType("text/plain")
.putExtra(Intent.EXTRA_SUBJECT, item.article.title)
.putExtra(Intent.EXTRA_TEXT, link)
try {
launcher.startActivity(Intent.createChooser(send, null).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
} catch (e: ActivityNotFoundException) {
Toast.makeText(launcher, R.string.flexera_rss_no_app, Toast.LENGTH_SHORT).show()
}
}
private fun openSettings() {
launcher.startActivity(PreferenceActivity.createIntent(launcher, GesturesRssReader))
}
/**
* Asks Android to let the app reach the phone's own network, where one of the feeds is;
* the feeds are fetched again as soon as the owner has said yes.
*/
private fun askForLocalNetwork() {
launcher.requestPermissions(arrayOf(FlexeraUpdater.LOCAL_NETWORK_PERMISSION), REQUEST_LOCAL_NETWORK)
launcher.addEventCallback(BaseActivity.EVENT_RESUMED) {
if (launcher.checkSelfPermission(FlexeraUpdater.LOCAL_NETWORK_PERMISSION) == PackageManager.PERMISSION_GRANTED) {
RssReader.refresh(launcher)
}
}
}
private fun dp(value: Int): Int = (value * density + 0.5f).toInt()
private fun text(sizeSp: Float, color: Int, bold: Boolean = false): TextView = TextView(context).apply {
setTextSize(TypedValue.COMPLEX_UNIT_SP, sizeSp)
setTextColor(color)
if (bold) typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
includeFontPadding = false
}
/** A round, slightly lit button with a white label, as in the app drawer's search field. */
private fun pill(label: Int, onClick: () -> Unit): TextView = text(15f, PRIMARY, bold = true).apply {
setText(label)
gravity = Gravity.CENTER
minHeight = dp(44)
setPadding(dp(22), dp(12), dp(22), dp(12))
val shape = GradientDrawable().apply {
cornerRadius = dp(22).toFloat()
setColor(PILL)
}
background = RippleDrawable(ColorStateList.valueOf(PRESSED), shape, null)
setOnClickListener { onClick() }
}
private fun iconButton(icon: Int, description: Int, onClick: () -> Unit): ImageView = ImageView(context).apply {
setImageResource(icon)
contentDescription = resources.getString(description)
scaleType = ImageView.ScaleType.CENTER
background = RippleDrawable(ColorStateList.valueOf(PRESSED), null, ColorDrawable(Color.WHITE)).apply {
radius = dp(24)
}
setOnClickListener { onClick() }
}
private inner class Adapter : ListAdapter<Row, RecyclerView.ViewHolder>(Diff) {
override fun getItemViewType(position: Int): Int = when (getItem(position)) {
is Row.Header -> 0
is Row.Message -> 1
is Row.Post -> 2
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder = when (viewType) {
0 -> HeaderHolder()
1 -> MessageHolder()
else -> PostHolder()
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (val row = getItem(position)) {
is Row.Header -> (holder as HeaderHolder).bind(row)
is Row.Message -> (holder as MessageHolder).bind(row)
is Row.Post -> (holder as PostHolder).bind(row.item)
}
}
}
private object Diff : DiffUtil.ItemCallback<Row>() {
override fun areItemsTheSame(oldItem: Row, newItem: Row): Boolean = when {
oldItem is Row.Header && newItem is Row.Header -> true
oldItem is Row.Message && newItem is Row.Message -> oldItem.kind == newItem.kind
oldItem is Row.Post && newItem is Row.Post -> oldItem.item.article.id == newItem.item.article.id
else -> false
}
override fun areContentsTheSame(oldItem: Row, newItem: Row): Boolean = oldItem == newItem
}
private inner class HeaderHolder : RecyclerView.ViewHolder(LinearLayout(context)) {
private val root = itemView as LinearLayout
private val title = text(32f, PRIMARY, bold = true)
private val subtitle = text(13f, SECONDARY)
private val refresh = iconButton(R.drawable.ic_flexera_refresh, R.string.flexera_rss_refresh) {
RssReader.refresh(launcher)
}
private val allow = pill(R.string.flexera_rss_allow_local_network) { askForLocalNetwork() }
private var spin: ObjectAnimator? = null
init {
root.orientation = LinearLayout.VERTICAL
root.layoutParams = RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT)
val top = LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
}
title.setText(R.string.flexera_rss_page_title)
title.isSingleLine = true
title.ellipsize = TextUtils.TruncateAt.END
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) title.isAccessibilityHeading = true
top.addView(title, LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f))
top.addView(refresh, LinearLayout.LayoutParams(dp(48), dp(48)))
val settings = iconButton(R.drawable.ic_flexera_tune, R.string.flexera_rss_settings) { openSettings() }
top.addView(settings, LinearLayout.LayoutParams(dp(48), dp(48)))
root.addView(top)
root.addView(subtitle, LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply {
topMargin = dp(6)
})
root.addView(allow, LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply {
topMargin = dp(14)
})
}
fun bind(row: Row.Header) {
root.setPadding(dp(SIDE_DP), topInset + dp(28), dp(SIDE_DP - 8), dp(16))
subtitle.text = row.subtitle
subtitle.visibility = if (row.subtitle.isEmpty()) View.GONE else View.VISIBLE
allow.visibility = if (row.askLocalNetwork) View.VISIBLE else View.GONE
if (row.refreshing) {
if (spin == null) {
spin = ObjectAnimator.ofFloat(refresh, View.ROTATION, 0f, 360f).apply {
duration = 900
repeatCount = ValueAnimator.INFINITE
interpolator = LinearInterpolator()
start()
}
}
} else {
spin?.cancel()
spin = null
refresh.rotation = 0f
}
}
}
private inner class MessageHolder : RecyclerView.ViewHolder(LinearLayout(context)) {
private val root = itemView as LinearLayout
private val title = text(20f, PRIMARY, bold = true)
private val body = text(15f, SECONDARY)
private var kind = Kind.NOTHING
private val action = pill(R.string.flexera_rss_add_feeds) {
if (kind == Kind.NO_FEEDS) openSettings() else RssReader.refresh(launcher)
}
init {
root.orientation = LinearLayout.VERTICAL
root.layoutParams = RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT)
root.setPadding(dp(SIDE_DP), dp(40), dp(SIDE_DP), dp(24))
body.setLineSpacing(0f, 1.2f)
root.addView(title)
root.addView(body, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply {
topMargin = dp(10)
})
root.addView(action, LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply {
topMargin = dp(22)
})
}
fun bind(row: Row.Message) {
kind = row.kind
val res = resources
when (row.kind) {
Kind.NO_FEEDS -> {
title.setText(R.string.flexera_rss_no_feeds)
body.text = res.getString(R.string.flexera_rss_no_feeds_body)
action.setText(R.string.flexera_rss_add_feeds)
}
Kind.LOADING -> {
title.setText(R.string.flexera_rss_loading)
body.text = ""
}
Kind.FAILED -> {
title.setText(R.string.flexera_rss_failed)
body.text = row.detail
action.setText(R.string.flexera_rss_try_again)
}
Kind.NOTHING -> {
title.setText(R.string.flexera_rss_nothing)
body.text = ""
}
}
body.visibility = if (body.text.isEmpty()) View.GONE else View.VISIBLE
action.visibility = if (row.kind == Kind.NO_FEEDS || row.kind == Kind.FAILED) View.VISIBLE else View.GONE
}
}
/**
* A post as a card, as in the feeds of the phone makers' launchers: its picture across the
* top, its title under it, then the feed's icon, name and the post's age, and a share
* button. A post without a picture shows three lines of its text instead.
*/
private inner class PostHolder : RecyclerView.ViewHolder(FrameLayout(context)) {
private val card = LinearLayout(context)
private val picture = RatioImageView(context, PICTURE_RATIO)
private val title = text(18f, PRIMARY, bold = true)
private val summary = text(14f, SECONDARY)
private val icon = ImageView(context)
private val meta = text(13f, SECONDARY)
private val share = ImageView(context)
private var item: RssReader.Item? = null
init {
val frame = itemView as FrameLayout
frame.layoutParams = RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT)
frame.setPadding(dp(CARD_SIDE_DP), dp(6), dp(CARD_SIDE_DP), dp(6))
card.orientation = LinearLayout.VERTICAL
val cardShape = GradientDrawable().apply {
cornerRadius = dp(CARD_CORNER_DP).toFloat()
setColor(CARD)
}
card.background = RippleDrawable(ColorStateList.valueOf(PRESSED), cardShape, null)
card.outlineProvider = object : ViewOutlineProvider() {
override fun getOutline(view: View, outline: Outline) {
outline.setRoundRect(0, 0, view.width, view.height, dp(CARD_CORNER_DP).toFloat())
}
}
card.clipToOutline = true
frame.addView(card, FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT))
picture.scaleType = ImageView.ScaleType.CENTER_CROP
picture.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
card.addView(picture, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT))
title.maxLines = 3
title.ellipsize = TextUtils.TruncateAt.END
title.setLineSpacing(0f, 1.15f)
card.addView(title, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply {
setMargins(dp(18), dp(16), dp(18), 0)
})
summary.maxLines = 3
summary.ellipsize = TextUtils.TruncateAt.END
summary.setLineSpacing(0f, 1.2f)
card.addView(summary, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply {
setMargins(dp(18), dp(8), dp(18), 0)
})
val footer = LinearLayout(context).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
setPaddingRelative(dp(18), dp(4), dp(6), dp(6))
}
icon.scaleType = ImageView.ScaleType.CENTER_CROP
icon.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
icon.outlineProvider = ViewOutlineProvider.BACKGROUND
icon.background = GradientDrawable().apply {
shape = GradientDrawable.OVAL
setColor(0x1AFFFFFF)
}
icon.clipToOutline = true
footer.addView(icon, LinearLayout.LayoutParams(dp(ICON_DP), dp(ICON_DP)).apply { marginEnd = dp(10) })
meta.isSingleLine = true
meta.ellipsize = TextUtils.TruncateAt.END
footer.addView(meta, LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f))
share.setImageResource(R.drawable.ic_flexera_share)
share.imageAlpha = 0xB3
share.scaleType = ImageView.ScaleType.CENTER
share.contentDescription = resources.getString(R.string.flexera_rss_share)
share.background = RippleDrawable(ColorStateList.valueOf(PRESSED), null, ColorDrawable(Color.WHITE)).apply { radius = dp(22) }
share.setOnClickListener { item?.let { sharePost(it) } }
footer.addView(share, LinearLayout.LayoutParams(dp(44), dp(44)))
card.addView(footer, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT).apply {
topMargin = dp(6)
})
card.setOnClickListener { item?.let { openPost(it) } }
card.setOnLongClickListener {
val post = item ?: return@setOnLongClickListener false
it.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
sharePost(post)
true
}
}
fun bind(post: RssReader.Item) {
item = post
val article = post.article
meta.text = "${post.source} · ${shortAge(article.published)}"
title.text = article.title
title.setTextColor(if (post.read) READ_PRIMARY else PRIMARY)
meta.setTextColor(if (post.read) READ_SECONDARY else SECONDARY)
summary.setTextColor(if (post.read) READ_SECONDARY else SECONDARY)
card.contentDescription = listOf(article.title, post.source, age(article.published)).joinToString(", ")
val url = article.imageUrl
if (url == null) {
CoilUtils.dispose(picture)
picture.setImageDrawable(null)
picture.visibility = View.GONE
} else {
picture.visibility = View.VISIBLE
images(context).enqueue(
ImageRequest.Builder(context)
.data(url)
.placeholder(ColorDrawable(0x14FFFFFF))
.target(picture)
.listener(onError = { _, _ -> if (item === post) picture.visibility = View.GONE })
.build(),
)
}
// Without a picture, the start of the text fills the card instead.
summary.text = article.summary
summary.visibility = if (url == null && article.summary.isNotEmpty()) View.VISIBLE else View.GONE
val letter = LetterDrawable(post.source)
val iconUrl = post.iconUrl
if (iconUrl == null) {
CoilUtils.dispose(icon)
icon.setImageDrawable(letter)
} else {
images(context).enqueue(
ImageRequest.Builder(context)
.data(iconUrl)
.size(dp(ICON_DP) * 2)
.crossfade(false)
.placeholder(letter)
.error(letter)
.target(icon)
.build(),
)
}
}
}
/** The age of a post in the fewest letters: "now", "5m", "3h", "2d", then its date. */
private fun shortAge(millis: Long): String {
val res = resources
val ago = System.currentTimeMillis() - millis
return when {
ago < DateUtils.MINUTE_IN_MILLIS -> res.getString(R.string.flexera_rss_age_now)
ago < DateUtils.HOUR_IN_MILLIS -> res.getString(R.string.flexera_rss_age_minutes, ago / DateUtils.MINUTE_IN_MILLIS)
ago < DateUtils.DAY_IN_MILLIS -> res.getString(R.string.flexera_rss_age_hours, ago / DateUtils.HOUR_IN_MILLIS)
ago < 7 * DateUtils.DAY_IN_MILLIS -> res.getString(R.string.flexera_rss_age_days, ago / DateUtils.DAY_IN_MILLIS)
else -> DateUtils.formatDateTime(context, millis, DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_ABBREV_MONTH)
}
}
private inner class RefreshEdgeFactory : RecyclerView.EdgeEffectFactory() {
override fun createEdgeEffect(view: RecyclerView, direction: Int): EdgeEffect =
if (direction == RecyclerView.EdgeEffectFactory.DIRECTION_TOP) RefreshEdge(view) else super.createEdgeEffect(view, direction)
}
/**
* The list's stretch at its top, which also counts how far it is pulled: far enough, and
* letting go fetches the feeds anew, with a tick when that point is passed either way.
*/
private inner class RefreshEdge(private val view: RecyclerView) : EdgeEffect(view.context) {
private var pulled = 0f
private var armed = false
override fun onPull(deltaDistance: Float, displacement: Float) {
super.onPull(deltaDistance, displacement)
pulled = (pulled + deltaDistance).coerceAtLeast(0f)
val nowArmed = pulled >= REFRESH_PULL
if (nowArmed != armed) {
armed = nowArmed
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
}
}
override fun onRelease() {
super.onRelease()
if (armed) RssReader.refresh(launcher)
pulled = 0f
armed = false
}
override fun finish() {
super.finish()
pulled = 0f
armed = false
}
}
}
/** What a feed's problem is called on the page and in the settings. */
internal fun problemText(context: Context, problem: RssProblem): String = context.getString(
when (problem) {
RssProblem.OFFLINE -> R.string.flexera_rss_problem_offline
RssProblem.TIMEOUT -> R.string.flexera_rss_problem_timeout
RssProblem.LOCAL_NETWORK -> R.string.flexera_rss_problem_local_network
RssProblem.NOT_FOUND -> R.string.flexera_rss_problem_not_found
RssProblem.SERVER -> R.string.flexera_rss_problem_server
RssProblem.NOT_A_FEED -> R.string.flexera_rss_problem_not_a_feed
RssProblem.NOT_SECURE -> R.string.flexera_rss_problem_not_secure
RssProblem.BAD_ADDRESS -> R.string.flexera_rss_problem_bad_address
},
)
@@ -0,0 +1,265 @@
package app.flexera.reader
import android.content.Context
import android.util.Log
import app.flexera.update.FlexeraUpdater
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.net.ConnectException
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.NoRouteToHostException
import java.net.SocketTimeoutException
import java.net.URL
import java.net.UnknownHostException
import java.net.UnknownServiceException
import java.util.Locale
/**
* Fetches feeds over HTTPS, and finds the feed of a site from its address: from the feed links
* in its page, or at the places sites usually keep one.
*/
object RssFetcher {
private const val TAG = "RssFetcher"
private const val CONNECT_TIMEOUT_MS = 15_000
private const val READ_TIMEOUT_MS = 20_000
private const val MAX_REDIRECTS = 5
/** No feed is larger than this; a larger answer is something else. */
private const val MAX_BYTES = 8 * 1024 * 1024
// Android's own User-Agent would tell every site the phone's model and its exact Android
// build. This one names only the app.
private const val USER_AGENT = "FlexeraLauncher (RSS reader)"
private const val ACCEPT = "application/rss+xml, application/atom+xml, application/rdf+xml, " +
"application/xml;q=0.9, text/xml;q=0.9, text/html;q=0.5, */*;q=0.1"
private const val PAGE_ACCEPT = "text/html, application/xhtml+xml;q=0.9, */*;q=0.1"
/** Where sites without a feed link in their page often have their feed. */
private val USUAL_PLACES = listOf("/feed", "/rss", "/feed.xml", "/rss.xml", "/atom.xml", "/index.xml")
private val LINK_TAG = Regex("""<link\b[^>]*>""", RegexOption.IGNORE_CASE)
private val ATTRIBUTE = Regex("""([\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))""")
private val FEED_TYPES = setOf("application/rss+xml", "application/atom+xml", "application/rdf+xml")
/** What a fetch brought: a feed, or word that it has not changed since the last time. */
sealed class Result {
class Fetched(val url: String, val feed: RssParser.Feed, val etag: String?, val lastModified: String?) : Result()
object NotModified : Result()
}
/** A fetch that failed, with the reason the owner is told. */
class FetchException(val problem: RssProblem, message: String, cause: Throwable? = null) :
IOException(message, cause)
private class Answer(
val url: String,
val status: Int,
val body: ByteArray?,
val contentType: String?,
val etag: String?,
val lastModified: String?,
)
/**
* Fetches the feed at [url]; [etag] and [lastModified] from the last fetch let the server
* say it has nothing new instead of sending it all again.
*/
fun fetch(context: Context, url: String, etag: String?, lastModified: String?): Result {
val answer = get(context, url, etag, lastModified)
if (answer.status == HttpURLConnection.HTTP_NOT_MODIFIED) return Result.NotModified
val body = answer.body ?: throw FetchException(RssProblem.NOT_A_FEED, "Empty answer")
val feed = try {
RssParser.parse(body, answer.url)
} catch (e: Exception) {
throw FetchException(RssProblem.NOT_A_FEED, "Not a feed: ${e.message}", e)
}
return Result.Fetched(answer.url, feed, answer.etag, answer.lastModified)
}
/**
* Finds the feed for what the owner typed: a feed's address, or a site's (with or without
* "https://"). Returned is the feed with the address it was found at.
*/
fun discover(context: Context, typed: String): Result.Fetched {
val answer = get(context, normalize(typed), null, null)
val body = answer.body ?: throw FetchException(RssProblem.NOT_A_FEED, "Empty answer")
if (!RssParser.looksLikeHtml(body)) {
try {
return Result.Fetched(answer.url, RssParser.parse(body, answer.url), answer.etag, answer.lastModified)
} catch (e: RssParser.NotAFeedException) {
if (!e.html) throw FetchException(RssProblem.NOT_A_FEED, e.message.orEmpty(), e)
} catch (e: Exception) {
throw FetchException(RssProblem.NOT_A_FEED, "Not a feed: ${e.message}", e)
}
}
// A web page: the feed it names, or one at the usual places on the same site.
val page = String(body, Charsets.UTF_8)
val named = feedLinks(page, answer.url)
val site = URL(answer.url).let { "${it.protocol}://${it.authority}" }
for (candidate in (named + USUAL_PLACES.map { site + it }).distinct()) {
try {
val found = get(context, candidate, null, null)
val feedBody = found.body ?: continue
if (RssParser.looksLikeHtml(feedBody)) continue
return Result.Fetched(found.url, RssParser.parse(feedBody, found.url), found.etag, found.lastModified)
} catch (e: Exception) {
Log.d(TAG, "No feed at $candidate: ${e.message}")
}
}
throw FetchException(RssProblem.NOT_A_FEED, "The page names no feed")
}
/** The feeds a web page names in its head, in its order. */
private fun feedLinks(page: String, base: String): List<String> =
LINK_TAG.findAll(page.take(200_000)).mapNotNull { tag ->
val attributes = ATTRIBUTE.findAll(tag.value).associate { match ->
match.groupValues[1].lowercase(Locale.ROOT) to
(match.groups[2] ?: match.groups[3] ?: match.groups[4])?.value.orEmpty()
}
val rel = attributes["rel"].orEmpty().lowercase(Locale.ROOT).split(' ')
val type = attributes["type"].orEmpty().lowercase(Locale.ROOT)
val href = attributes["href"]
if ("alternate" in rel && type in FEED_TYPES && !href.isNullOrBlank()) {
RssParser.resolve(base, android.text.Html.fromHtml(href, android.text.Html.FROM_HTML_MODE_LEGACY).toString())
} else {
null
}
}.toList()
/** An address as typed made whole: "https://" in front when it has no scheme. */
fun normalize(typed: String): String {
val text = typed.trim()
if (text.isEmpty() || text.any { it.isWhitespace() }) {
throw FetchException(RssProblem.BAD_ADDRESS, "Not an address: $typed")
}
val withScheme = when {
text.startsWith("https://", ignoreCase = true) || text.startsWith("http://", ignoreCase = true) -> text
text.startsWith("feed://", ignoreCase = true) -> "https://" + text.substring(7)
text.contains("://") -> throw FetchException(RssProblem.BAD_ADDRESS, "Not a web address: $typed")
else -> "https://$text"
}
try {
val url = URL(withScheme)
if (url.host.isNullOrEmpty() || !url.host.contains('.') && url.host != "localhost") {
throw FetchException(RssProblem.BAD_ADDRESS, "No host in $typed")
}
} catch (e: MalformedURLException) {
throw FetchException(RssProblem.BAD_ADDRESS, "Not an address: $typed", e)
}
return withScheme
}
/** A web page as fetched: where it ended up after redirects, and its bytes and type. */
class Page(val url: String, val body: ByteArray, val contentType: String?)
/** Fetches the web page at [url], an article's, for the article view. */
fun fetchPage(context: Context, url: String): Page {
val answer = get(context, url, null, null, PAGE_ACCEPT)
val body = answer.body ?: throw FetchException(RssProblem.SERVER, "Empty answer")
return Page(answer.url, body, answer.contentType)
}
private fun get(
context: Context,
url: String,
etag: String?,
lastModified: String?,
accept: String = ACCEPT,
): Answer {
var address = upgrade(url)
for (hop in 0..MAX_REDIRECTS) {
val connection = try {
URL(address).openConnection() as HttpURLConnection
} catch (e: MalformedURLException) {
throw FetchException(RssProblem.BAD_ADDRESS, "Not an address: $address", e)
} catch (e: IOException) {
throw problemOf(context, address, e)
}
try {
connection.instanceFollowRedirects = false
connection.connectTimeout = CONNECT_TIMEOUT_MS
connection.readTimeout = READ_TIMEOUT_MS
connection.setRequestProperty("User-Agent", USER_AGENT)
connection.setRequestProperty("Accept", accept)
if (hop == 0) {
etag?.let { connection.setRequestProperty("If-None-Match", it) }
lastModified?.let { connection.setRequestProperty("If-Modified-Since", it) }
}
val status = connection.responseCode
when {
status == HttpURLConnection.HTTP_NOT_MODIFIED ->
return Answer(address, status, null, null, etag, lastModified)
status in 300..399 -> {
val location = connection.getHeaderField("Location")
?: throw FetchException(RssProblem.SERVER, "Redirect without a location")
address = upgrade(RssParser.resolve(address, location))
continue
}
status == HttpURLConnection.HTTP_NOT_FOUND || status == 410 ->
throw FetchException(RssProblem.NOT_FOUND, "HTTP $status")
status != HttpURLConnection.HTTP_OK ->
throw FetchException(RssProblem.SERVER, "HTTP $status")
}
val body = connection.inputStream.use { readCapped(it) }
return Answer(
url = address,
status = status,
body = body,
contentType = connection.contentType,
etag = connection.getHeaderField("ETag"),
lastModified = connection.getHeaderField("Last-Modified"),
)
} catch (e: FetchException) {
throw e
} catch (e: IOException) {
throw problemOf(context, address, e)
} catch (e: SecurityException) {
// No INTERNET permission: as good as offline.
throw FetchException(RssProblem.OFFLINE, "No network permission", e)
} finally {
connection.disconnect()
}
}
throw FetchException(RssProblem.SERVER, "Too many redirects")
}
/**
* "http://" made "https://", which nearly every site serves as well: Android does not let
* the app fetch anything unencrypted, so plain "http://" would fail for certain.
*/
private fun upgrade(address: String): String =
if (address.startsWith("http://", ignoreCase = true)) "https://" + address.substring(7) else address
private fun readCapped(input: InputStream): ByteArray {
val out = ByteArrayOutputStream()
val buffer = ByteArray(16 * 1024)
while (true) {
val read = input.read(buffer)
if (read < 0) break
out.write(buffer, 0, read)
if (out.size() > MAX_BYTES) throw FetchException(RssProblem.NOT_A_FEED, "Too large for a feed")
}
return out.toByteArray()
}
private fun problemOf(context: Context, address: String, e: IOException): FetchException {
val host = runCatching { URL(address).host }.getOrNull()
val problem = when {
(e is SocketTimeoutException || e is ConnectException || e is NoRouteToHostException) &&
host != null && FlexeraUpdater.blocksLocalNetwork(context, host) -> RssProblem.LOCAL_NETWORK
e is UnknownServiceException || e is javax.net.ssl.SSLException -> RssProblem.NOT_SECURE
e is SocketTimeoutException -> RssProblem.TIMEOUT
e is UnknownHostException || e is ConnectException || e is NoRouteToHostException -> RssProblem.OFFLINE
else -> RssProblem.OFFLINE
}
Log.w(TAG, "Could not fetch $address: $problem (${e.javaClass.simpleName}: ${e.message})")
return FetchException(problem, e.message.orEmpty(), e)
}
}
@@ -0,0 +1,57 @@
package app.flexera.reader
import kotlinx.serialization.Serializable
/**
* A feed the owner follows: its address and the name it goes by in the reader, which is the
* feed's own title when it was added.
*/
@Serializable
data class RssFeed(val url: String, val title: String)
/** One post of a feed, as the reader keeps it. */
@Serializable
data class RssArticle(
/** The feed's address and the post's own id, so that two feeds' ids never clash. */
val id: String,
val feedUrl: String,
val title: String,
/** The post's page; empty when the feed gives none. */
val link: String,
/** The start of the post as plain text, for two lines under its title. */
val summary: String = "",
val imageUrl: String? = null,
/** When it was published, in milliseconds; when the feed does not say, when first seen. */
val published: Long,
val author: String? = null,
)
/** Why a feed could not be fetched, in terms the owner can act on. */
enum class RssProblem {
/** No connection, or the name of the server could not be looked up. */
OFFLINE,
/** The server did not answer in time. */
TIMEOUT,
/** Android 17 keeps the app from the phone's own network until the owner allows it. */
LOCAL_NETWORK,
/** The address leads nowhere (HTTP 404 or 410). */
NOT_FOUND,
/** The server answered with an error. */
SERVER,
/** What came back is not a feed, and names none. */
NOT_A_FEED,
/**
* No secure connection could be made: the site serves its feed unencrypted only, which
* Android does not allow the app, or its certificate is not valid.
*/
NOT_SECURE,
/** Not an address at all. */
BAD_ADDRESS,
}
+436
View File
@@ -0,0 +1,436 @@
package app.flexera.reader
import android.text.Html
import android.text.TextUtils
import android.util.Xml
import java.io.ByteArrayInputStream
import java.net.URL
import java.text.ParsePosition
import java.text.SimpleDateFormat
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.OffsetDateTime
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.util.Locale
import org.xmlpull.v1.XmlPullParser
/**
* Reads the three kinds of feed in use: RSS 2.0, Atom and RSS 1.0 (RDF), with the usual
* additions for dates (Dublin Core), full text (content:encoded) and pictures (Media RSS,
* enclosures, iTunes, or the first picture in the post).
*/
object RssParser {
/** A feed as read, before the reader makes its articles of it. */
class Feed(
val title: String,
val entries: List<Entry>,
/** The site's page, when the feed names it. */
val siteLink: String? = null,
/** The feed's own small picture (Atom icon or logo, RSS channel image), if any. */
val iconUrl: String? = null,
)
class Entry(
val id: String?,
val title: String,
val link: String?,
val summary: String,
val imageUrl: String?,
/** Milliseconds, or null when the feed gives no date it could read. */
val date: Long?,
/** The post as HTML, as much of it as the feed carries; the article view shows it. */
val contentHtml: String = "",
val author: String? = null,
)
/** Raised when what was read is no feed; [html] when it is a web page instead. */
class NotAFeedException(val html: Boolean, message: String) : Exception(message)
private const val ATOM = "http://www.w3.org/2005/Atom"
private const val MEDIA = "http://search.yahoo.com/mrss/"
private const val ITUNES = "http://www.itunes.com/dtds/podcast-1.0.dtd"
/** Longest summary kept, in characters; two lines need far fewer. */
private const val SUMMARY_LENGTH = 300
/** Most of a post's HTML kept for the article view; a whole long article fits. */
private const val MAX_CONTENT_LENGTH = 400_000
/** How much of a post's HTML is looked at for its summary and its first picture. */
private const val HTML_LOOK_LENGTH = 20_000
/**
* HTML's names for characters, which feeds use although XML knows only five of its own.
* Without them such a feed would not be read at all.
*/
private val HTML_ENTITIES = mapOf(
"nbsp" to " ", "ndash" to "–", "mdash" to "—", "hellip" to "…",
"lsquo" to "‘", "rsquo" to "’", "ldquo" to "“", "rdquo" to "”",
"laquo" to "«", "raquo" to "»", "bull" to "•", "middot" to "·",
"copy" to "©", "reg" to "®", "trade" to "™", "euro" to "€",
"pound" to "£", "deg" to "°", "times" to "×", "eacute" to "é",
"egrave" to "è", "aacute" to "á", "agrave" to "à", "ouml" to "ö",
"auml" to "ä", "uuml" to "ü", "szlig" to "ß", "ccedil" to "ç",
"iacute" to "í", "oacute" to "ó", "uacute" to "ú", "ntilde" to "ñ",
)
private val IMG_SRC = Regex("""<img\b[^>]*?\bsrc\s*=\s*["']([^"']+)["'][^>]*>""", RegexOption.IGNORE_CASE)
private val TINY = Regex("""\b(width|height)\s*=\s*["']?1["'\s/>]""", RegexOption.IGNORE_CASE)
private val SCRIPT_OR_STYLE = Regex("""<(script|style)\b[^>]*>.*?</\1\s*>""", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))
private val TAG = Regex("""<[^>]*>""")
private val SPACES = Regex("""\s+""")
/**
* Whether [body] looks like a web page rather than a feed: it starts as HTML does. Some
* pages have an XML declaration first, so that alone says nothing.
*/
fun looksLikeHtml(body: ByteArray): Boolean {
val start = String(body, 0, minOf(body.size, 1024), Charsets.ISO_8859_1).lowercase(Locale.ROOT)
val html = listOf("<!doctype html", "<html").map { start.indexOf(it) }.filter { it >= 0 }.minOrNull()
?: return false
val feed = listOf("<rss", "<feed", "<rdf:rdf").map { start.indexOf(it) }.filter { it >= 0 }.minOrNull()
return feed == null || html < feed
}
/** Reads the feed in [body], fetched from [base], against which its links are resolved. */
fun parse(body: ByteArray, base: String): Feed {
if (looksLikeHtml(body)) throw NotAFeedException(html = true, "A web page, not a feed")
val parser = Xml.newPullParser()
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true)
// Android's parser processes a DOCTYPE, which forbids defining the names below; feeds
// have no use for one.
runCatching { parser.setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, false) }
// Leading blanks before the XML declaration make it unreadable.
var offset = if (body.size >= 3 && body[0] == 0xEF.toByte() && body[1] == 0xBB.toByte() && body[2] == 0xBF.toByte()) 3 else 0
while (offset < body.size && body[offset].toInt().toChar().isWhitespace()) offset++
parser.setInput(ByteArrayInputStream(body, offset, body.size - offset), null)
for ((name, text) in HTML_ENTITIES) {
try {
parser.defineEntityReplacementText(name, text)
} catch (e: Exception) {
// A parser that takes none: a feed that uses them is not read, the others are.
break
}
}
var event = parser.next()
while (event != XmlPullParser.START_TAG && event != XmlPullParser.END_DOCUMENT) event = parser.next()
val root = if (event == XmlPullParser.START_TAG) parser.name.lowercase(Locale.ROOT) else ""
if (root != "rss" && root != "feed" && root != "rdf") {
throw NotAFeedException(html = root == "html", "Not a feed: <$root>")
}
var title: String? = null
var siteLink: String? = null
var icon: String? = null
var logo: String? = null
val entries = ArrayList<Entry>()
while (event != XmlPullParser.END_DOCUMENT) {
if (event == XmlPullParser.START_TAG) {
when (parser.name) {
"item", "entry" -> {
readEntry(parser, siteLink ?: base)?.let(entries::add)
}
// rss > channel > title, feed > title, RDF > channel > title
"title" -> if (title == null && parser.depth <= 3 && parser.namespace != MEDIA) {
title = plain(readInner(parser, null))
}
"link" -> if (siteLink == null && parser.depth <= 3) {
siteLink = linkOf(parser)?.let { resolve(base, it) }
}
// A channel's picture, with a title and a link of its own besides its address.
"image" -> if (parser.namespace == ITUNES) {
if (logo == null) logo = parser.getAttributeValue(null, "href")
} else if (parser.depth <= 3) {
val url = imageUrlOf(parser)
if (icon == null) icon = url
} else {
skip(parser)
}
"icon" -> if (parser.namespace == ATOM && parser.depth == 2) icon = readInner(parser, null).trim()
"logo" -> if (parser.namespace == ATOM && parser.depth == 2) logo = readInner(parser, null).trim()
}
}
event = parser.next()
}
val picture = (icon?.takeIf { it.isNotEmpty() } ?: logo?.takeIf { it.isNotEmpty() })
?.let { resolve(siteLink ?: base, it) }?.takeIf { it.startsWith("http") }
return Feed(title.orEmpty(), entries, siteLink, picture)
}
/**
* The address a link element names: an Atom link's href when it is the page's own
* (alternate, or no rel), an RSS link's text. Leaves the parser at the element's end only
* when it read its text.
*/
private fun linkOf(parser: XmlPullParser): String? {
if (parser.namespace == ATOM) {
val rel = parser.getAttributeValue(null, "rel")
if (rel != null && rel != "alternate") return null
return parser.getAttributeValue(null, "href")?.trim()?.takeIf { it.isNotEmpty() }
}
return readInner(parser, null).trim().takeIf { it.isNotEmpty() }
}
/** The address in an RSS channel's image element, which the parser is at; leaves it at its end. */
private fun imageUrlOf(parser: XmlPullParser): String? {
val depth = parser.depth
var url: String? = null
while (true) {
when (parser.next()) {
XmlPullParser.START_TAG -> if (parser.name == "url" && url == null) url = readInner(parser, null).trim()
XmlPullParser.END_TAG -> if (parser.depth == depth) return url
XmlPullParser.END_DOCUMENT -> return url
}
}
}
private fun readEntry(parser: XmlPullParser, base: String): Entry? {
val depth = parser.depth
var id: String? = null
var title: String? = null
var link: String? = null
var guidLink: String? = null
var description: String? = null
var content: String? = null
var published: String? = null
var updated: String? = null
var mediaThumbnail: String? = null
var mediaImage: String? = null
var enclosureImage: String? = null
var itunesImage: String? = null
var author: String? = null
val inlineImages = ArrayList<String>()
var event = parser.next()
while (event != XmlPullParser.END_DOCUMENT && !(event == XmlPullParser.END_TAG && parser.depth == depth)) {
if (event == XmlPullParser.START_TAG) {
val ns = parser.namespace
when (parser.name) {
"title" -> if (ns != MEDIA && title == null) title = readInner(parser, null)
"link" -> {
val rel = parser.getAttributeValue(null, "rel")
val type = parser.getAttributeValue(null, "type").orEmpty()
if (ns == ATOM && rel == "enclosure" && type.startsWith("image/")) {
if (enclosureImage == null) enclosureImage = parser.getAttributeValue(null, "href")
} else if (link == null) {
link = linkOf(parser)
}
}
"guid" -> {
val permalink = parser.getAttributeValue(null, "isPermaLink") != "false"
val text = readInner(parser, null).trim()
if (text.isNotEmpty()) {
id = text
if (permalink && text.startsWith("http")) guidLink = text
}
}
"id" -> if (ns == ATOM) id = readInner(parser, null).trim()
"pubDate", "published", "issued" -> published = readInner(parser, null)
"date" -> if (published == null) published = readInner(parser, null)
"updated", "modified" -> updated = readInner(parser, null)
"description", "summary" -> if (ns != MEDIA && description == null) {
description = readBody(parser, inlineImages)
}
"encoded" -> if (content == null) content = readInner(parser, inlineImages)
// Dublin Core's creator in RSS; the name in an Atom author.
"creator" -> if (author == null) author = plain(readInner(parser, null))
"name" -> if (ns == ATOM && author == null) author = plain(readInner(parser, null))
"content" -> when (ns) {
MEDIA -> {
val medium = parser.getAttributeValue(null, "medium")
val type = parser.getAttributeValue(null, "type").orEmpty()
val url = parser.getAttributeValue(null, "url")
if (mediaImage == null && url != null &&
(medium == "image" || type.startsWith("image/") || looksLikeImage(url))
) {
mediaImage = url
}
}
else -> if (content == null) content = readBody(parser, inlineImages)
}
"thumbnail" -> if (ns == MEDIA && mediaThumbnail == null) {
mediaThumbnail = parser.getAttributeValue(null, "url")
}
"enclosure" -> {
val type = parser.getAttributeValue(null, "type").orEmpty()
val url = parser.getAttributeValue(null, "url")
if (enclosureImage == null && url != null && (type.startsWith("image/") || looksLikeImage(url))) {
enclosureImage = url
}
}
"image" -> if (ns == ITUNES && itunesImage == null) {
itunesImage = parser.getAttributeValue(null, "href")
}
}
}
event = parser.next()
}
val html = (description ?: content).orEmpty()
val cleanTitle = plain(title.orEmpty())
val summary = plain(html).take(SUMMARY_LENGTH)
val page = (link ?: guidLink)?.let { resolve(base, it) }
if (cleanTitle.isEmpty() && page == null) return null
// The largest first: the reader shows it across a whole card.
val picture = mediaImage ?: enclosureImage ?: mediaThumbnail ?: itunesImage
?: inlineImages.firstOrNull()
?: firstImage(content.orEmpty()) ?: firstImage(description.orEmpty())
// The longer of the two is the more of the post.
val body = listOfNotNull(content, description).maxByOrNull { it.length }.orEmpty()
return Entry(
id = id?.takeIf { it.isNotEmpty() } ?: page ?: cleanTitle,
title = cleanTitle.ifEmpty { summary.take(80) },
link = page,
summary = if (summary == cleanTitle) "" else summary,
imageUrl = picture?.let { resolve(base, it.trim()) }?.takeIf { it.startsWith("http") },
date = parseDate(published) ?: parseDate(updated),
contentHtml = body.take(MAX_CONTENT_LENGTH),
author = author?.takeIf { it.isNotEmpty() },
)
}
/**
* The text of the element the parser is at, nested elements' text included (an Atom post's
* XHTML), and the pictures named in such nested markup added to [images]. Leaves the parser
* at the element's end.
*/
private fun readInner(parser: XmlPullParser, images: MutableList<String>?): String {
val depth = parser.depth
val text = StringBuilder()
while (true) {
when (parser.next()) {
XmlPullParser.TEXT -> text.append(parser.text)
XmlPullParser.START_TAG -> {
if (images != null && parser.name.equals("img", ignoreCase = true)) {
parser.getAttributeValue(null, "src")?.let(images::add)
}
text.append(' ')
}
XmlPullParser.END_TAG -> if (parser.depth == depth) return text.toString()
XmlPullParser.END_DOCUMENT -> return text.toString()
}
}
}
/**
* A post's text as HTML: escaped HTML as it is, or an Atom post's XHTML written out again
* as markup, its pictures added to [images]. Leaves the parser at the element's end.
*/
private fun readBody(parser: XmlPullParser, images: MutableList<String>): String {
if (parser.getAttributeValue(null, "type") != "xhtml") return readInner(parser, images)
val depth = parser.depth
val html = StringBuilder()
while (true) {
when (parser.next()) {
XmlPullParser.TEXT -> html.append(TextUtils.htmlEncode(parser.text))
XmlPullParser.START_TAG -> {
val name = parser.name
if (name.equals("img", ignoreCase = true)) parser.getAttributeValue(null, "src")?.let(images::add)
html.append('<').append(name)
for (i in 0 until parser.attributeCount) {
html.append(' ').append(parser.getAttributeName(i)).append("=\"")
.append(TextUtils.htmlEncode(parser.getAttributeValue(i))).append('"')
}
html.append('>')
}
XmlPullParser.END_TAG -> {
if (parser.depth == depth) return html.toString()
html.append("</").append(parser.name).append('>')
}
XmlPullParser.END_DOCUMENT -> return html.toString()
}
}
}
private fun skip(parser: XmlPullParser) {
val depth = parser.depth
while (true) {
when (parser.next()) {
XmlPullParser.END_TAG -> if (parser.depth == depth) return
XmlPullParser.END_DOCUMENT -> return
}
}
}
/** The first real picture in a post's HTML; tracking pixels, one pixel big, do not count. */
private fun firstImage(html: String): String? =
IMG_SRC.findAll(html.take(HTML_LOOK_LENGTH))
.firstOrNull { !TINY.containsMatchIn(it.value) }
?.groupValues?.get(1)
?.let { Html.fromHtml(it, Html.FROM_HTML_MODE_LEGACY).toString() }
private fun looksLikeImage(url: String): Boolean {
val path = url.substringBefore('?').lowercase(Locale.ROOT)
return path.endsWith(".jpg") || path.endsWith(".jpeg") || path.endsWith(".png") ||
path.endsWith(".webp") || path.endsWith(".gif")
}
/** HTML or text as plain text on one line: no tags, no character names, single spaces. */
fun plain(html: String): String {
if (html.isBlank()) return ""
var text = html.take(HTML_LOOK_LENGTH)
if (text.indexOf('<') >= 0 || text.indexOf('&') >= 0) {
text = SCRIPT_OR_STYLE.replace(text, " ")
text = TAG.replace(text, " ")
text = Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY).toString()
}
return SPACES.replace(text.replace('', ' '), " ").trim()
}
fun resolve(base: String, address: String): String = try {
URL(URL(base), address).toString()
} catch (e: Exception) {
address
}
/** RFC 822 dates as feeds write them, which Java's own RFC 1123 reader does not all take. */
private val RFC822_PATTERNS = listOf(
"EEE, d MMM yyyy HH:mm:ss Z",
"EEE, d MMM yyyy HH:mm:ss zzz",
"EEE, d MMM yyyy HH:mm Z",
"EEE, d MMM yyyy HH:mm zzz",
"d MMM yyyy HH:mm:ss Z",
"d MMM yyyy HH:mm:ss zzz",
"EEE, d MMM yy HH:mm:ss Z",
"EEE, d MMM yyyy HH:mm:ss",
)
/** A feed's date as milliseconds, whichever of the usual ways it is written; null if none. */
fun parseDate(value: String?): Long? {
val text = value?.trim()?.replace(SPACES, " ")?.takeIf { it.isNotEmpty() } ?: return null
val millis = if (text.length >= 10 && text[0].isDigit() && text[4] == '-') {
iso(text)
} else {
rfc822(text)
}
// A date far in the future is a mistake of the feed's; it would stay on top for ever.
return millis?.let { minOf(it, System.currentTimeMillis()) }
}
private fun iso(text: String): Long? {
var t = text.replace(' ', 'T')
// "+0100" for "+01:00".
Regex("""([+-]\d{2})(\d{2})$""").find(t)?.let { t = t.substring(0, it.range.first) + it.groupValues[1] + ":" + it.groupValues[2] }
return runCatching { OffsetDateTime.parse(t).toInstant().toEpochMilli() }.getOrNull()
?: runCatching { Instant.parse(t).toEpochMilli() }.getOrNull()
?: runCatching { LocalDateTime.parse(t).toInstant(ZoneOffset.UTC).toEpochMilli() }.getOrNull()
?: runCatching { LocalDate.parse(t.take(10)).atStartOfDay().toInstant(ZoneOffset.UTC).toEpochMilli() }.getOrNull()
}
private fun rfc822(text: String): Long? {
runCatching {
return OffsetDateTime.parse(text, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant().toEpochMilli()
}
for (pattern in RFC822_PATTERNS) {
val format = SimpleDateFormat(pattern, Locale.US).apply { isLenient = false }
val position = ParsePosition(0)
val date = format.parse(text, position)
if (date != null && position.index > 0) return date.time
}
return null
}
}
+390
View File
@@ -0,0 +1,390 @@
package app.flexera.reader
import android.content.Context
import android.util.Log
import app.lawnchair.preferences2.PreferenceManager2
import app.lawnchair.util.kotlinxJson
import java.io.File
import java.net.URL
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
/**
* The RSS reader's store: the feeds the owner follows (kept with the other settings, so that
* a backup carries them), the posts last fetched from them and which of those were opened (in
* a file of the reader's own), and fetching them anew.
*
* The reader's page ([ReaderPage]) shows [state]; the settings screen ([RssReaderSettings])
* adds and removes feeds. Feeds are fetched when the page opens and the last time is more than
* [STALE_MS] ago, when the owner pulls the list down or taps refresh, and as soon as one is
* added. Nothing is fetched in the background.
*/
object RssReader {
private const val TAG = "RssReader"
private const val FILE = "flexera_rss.json"
/** Posts older than this, seen when the page opens, are fetched anew. */
private const val STALE_MS = 15 * 60_000L
private const val MAX_PER_FEED = 50
private const val MAX_ARTICLES = 300
private const val MAX_READ = 3000
private const val PARALLEL_FETCHES = 4
/**
* A post as the page shows it: with its feed's name, the feed's small picture (or the site's
* own icon) and whether it was opened.
*/
data class Item(val article: RssArticle, val source: String, val read: Boolean, val iconUrl: String? = null)
/** A feed that could not be fetched the last time it was tried. */
data class Failure(val feed: RssFeed, val problem: RssProblem)
data class State(
/** False until the stored posts have been read; the page shows nothing until then. */
val loaded: Boolean = false,
val feeds: List<RssFeed> = emptyList(),
/** Every feed's posts together, the newest first. */
val items: List<Item> = emptyList(),
val refreshing: Boolean = false,
/** When all feeds were last fetched, in milliseconds; 0 for never. */
val lastRefresh: Long = 0,
val failures: List<Failure> = emptyList(),
)
/** What adding a feed came to. */
sealed class AddResult {
data class Added(val feed: RssFeed) : AddResult()
data class AlreadyThere(val feed: RssFeed) : AddResult()
data class Failed(val problem: RssProblem) : AddResult()
}
@Serializable
private data class FeedCache(
val url: String,
val articles: List<RssArticle> = emptyList(),
val etag: String? = null,
val lastModified: String? = null,
val iconUrl: String? = null,
val siteUrl: String? = null,
)
@Serializable
private data class Stored(
val feeds: List<FeedCache> = emptyList(),
val read: List<String> = emptyList(),
val lastRefresh: Long = 0,
)
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
/** Guards [stored], [feeds] and [failures]. */
private val lock = Mutex()
private val mutableState = MutableStateFlow(State())
@Volatile
private var appContext: Context? = null
private var stored = Stored()
private var feeds: List<RssFeed> = emptyList()
private val failures = LinkedHashMap<String, RssProblem>()
private var refreshJob: Job? = null
/** What the page shows; reading the stored posts and following the feed list begins here. */
fun state(context: Context): StateFlow<State> {
start(context)
return mutableState.asStateFlow()
}
private fun start(context: Context) {
if (appContext != null) return
synchronized(this) {
if (appContext != null) return
appContext = context.applicationContext
}
val app = context.applicationContext
scope.launch {
lock.withLock { stored = load(app) }
PreferenceManager2.getInstance(app).rssFeeds.get().distinctUntilChanged().collect { list ->
val fresh = lock.withLock {
feeds = list
publish()
// A feed new to the list, with nothing stored yet, is fetched at once.
list.filter { feed -> stored.feeds.none { it.url == feed.url } }
}
if (fresh.isNotEmpty()) fetchFeeds(fresh)
}
}
}
/** Fetches every feed when the last time is more than [STALE_MS] ago. */
fun refreshIfStale(context: Context) {
start(context)
val state = mutableState.value
if (!state.loaded) {
scope.launch {
mutableState.first { it.loaded }
if (System.currentTimeMillis() - mutableState.value.lastRefresh > STALE_MS) fetchFeeds(null)
}
} else if (System.currentTimeMillis() - state.lastRefresh > STALE_MS || state.failures.isNotEmpty()) {
fetchFeeds(null)
}
}
/** Fetches every feed now. */
fun refresh(context: Context) {
start(context)
scope.launch {
mutableState.first { it.loaded }
fetchFeeds(null)
}
}
/** Remembers that [article] was opened; the page shows it dimmed from then on. */
fun markRead(context: Context, article: RssArticle) {
start(context)
scope.launch {
lock.withLock {
if (article.id in stored.read) return@withLock
stored = stored.copy(read = (stored.read + article.id).takeLast(MAX_READ))
publish()
save()
}
}
}
/**
* Finds the feed for what the owner typed, a feed's or a site's address, and adds it to the
* end of the list. Its posts are stored at once, so that the page has them before any
* other fetch.
*/
suspend fun addFeed(context: Context, typed: String): AddResult = withContext(Dispatchers.IO) {
start(context)
val found = try {
RssFetcher.discover(context, typed)
} catch (e: RssFetcher.FetchException) {
return@withContext AddResult.Failed(e.problem)
}
val prefs = PreferenceManager2.getInstance(context).rssFeeds
val list = prefs.get().first()
list.firstOrNull { it.url == found.url }?.let { return@withContext AddResult.AlreadyThere(it) }
val title = found.feed.title.ifBlank { runCatching { URL(found.url).host.removePrefix("www.") }.getOrDefault(found.url) }
val feed = RssFeed(found.url, title)
keepTexts(context, feed.url, found.feed)
// Not while holding the lock: the stored posts are read with it.
mutableState.first { it.loaded }
lock.withLock {
stored = stored.copy(
feeds = stored.feeds.filter { it.url != feed.url } + FeedCache(
url = feed.url,
articles = articlesOf(feed.url, found.feed, emptyList()),
etag = found.etag,
lastModified = found.lastModified,
iconUrl = found.feed.iconUrl,
siteUrl = found.feed.siteLink,
),
)
failures.remove(feed.url)
save()
}
prefs.set(list + feed)
AddResult.Added(feed)
}
/** Stops following [feed]; its stored posts go with it. */
suspend fun removeFeed(context: Context, feed: RssFeed) {
start(context)
val prefs = PreferenceManager2.getInstance(context).rssFeeds
prefs.set(prefs.get().first().filter { it.url != feed.url })
lock.withLock {
stored = stored.copy(feeds = stored.feeds.filter { it.url != feed.url })
failures.remove(feed.url)
save()
}
}
/**
* Fetches [only] those feeds, or all. One fetch of all at a time: asked again meanwhile,
* the running one is enough.
*/
private fun fetchFeeds(only: List<RssFeed>?) {
synchronized(this) {
if (only == null && refreshJob?.isActive == true) return
val job = scope.launch { fetch(only) }
if (only == null) refreshJob = job
}
}
private suspend fun fetch(only: List<RssFeed>?) {
val app = appContext ?: return
val targets = lock.withLock {
val list = only ?: feeds
if (list.isNotEmpty()) mutableState.value = mutableState.value.copy(refreshing = true)
list.map { feed -> feed to stored.feeds.firstOrNull { it.url == feed.url } }
}
if (targets.isEmpty()) {
if (only == null) lock.withLock {
stored = stored.copy(lastRefresh = System.currentTimeMillis())
publish()
}
return
}
val permits = Semaphore(PARALLEL_FETCHES)
val results = coroutineScope {
targets.map { (feed, cached) ->
async {
permits.withPermit {
feed to runCatching { RssFetcher.fetch(app, feed.url, cached?.etag, cached?.lastModified) }
}
}
}.awaitAll()
}
// The posts' text, for the article view; files, so not while holding the lock.
for ((feed, outcome) in results) {
(outcome.getOrNull() as? RssFetcher.Result.Fetched)?.let { keepTexts(app, feed.url, it.feed) }
}
if (only == null) ArticleStore.prune(app)
lock.withLock {
var all = stored.feeds
for ((feed, outcome) in results) {
if (feeds.none { it.url == feed.url }) continue // removed meanwhile
val result = outcome.getOrElse { error ->
failures[feed.url] = (error as? RssFetcher.FetchException)?.problem ?: RssProblem.OFFLINE
null
} ?: continue
failures.remove(feed.url)
if (result is RssFetcher.Result.Fetched) {
val before = all.firstOrNull { it.url == feed.url }
val articles = articlesOf(feed.url, result.feed, before?.articles.orEmpty())
all = all.filter { it.url != feed.url } + FeedCache(
url = feed.url,
articles = articles,
etag = result.etag,
lastModified = result.lastModified,
iconUrl = result.feed.iconUrl,
siteUrl = result.feed.siteLink,
)
}
}
stored = stored.copy(
feeds = all,
lastRefresh = if (only == null) System.currentTimeMillis() else stored.lastRefresh,
)
save()
publish(refreshing = refreshJob?.isActive == true && only != null)
}
}
/**
* The posts of a fetched [feed], the newest first. A post the feed gives no date keeps the
* one it had in [before], when it was first seen, so that it does not come back to the top
* with every fetch.
*/
private fun articlesOf(feedUrl: String, feed: RssParser.Feed, before: List<RssArticle>): List<RssArticle> {
val now = System.currentTimeMillis()
val earlier = before.associateBy { it.id }
return feed.entries.asSequence()
.map { entry ->
val id = articleId(feedUrl, entry)
RssArticle(
id = id,
feedUrl = feedUrl,
title = entry.title,
link = entry.link.orEmpty(),
summary = entry.summary,
imageUrl = entry.imageUrl,
published = entry.date ?: earlier[id]?.published ?: now,
author = entry.author,
)
}
.distinctBy { it.id }
.sortedByDescending { it.published }
.take(MAX_PER_FEED)
.toList()
}
private fun articleId(feedUrl: String, entry: RssParser.Entry) = "$feedUrl|${entry.id}"
/** Keeps what [feed] carries of each post, for the article view. For a background thread. */
private fun keepTexts(context: Context, feedUrl: String, feed: RssParser.Feed) {
for (entry in feed.entries.take(MAX_PER_FEED * 2)) {
ArticleStore.saveFeedText(context, articleId(feedUrl, entry), entry.contentHtml)
}
}
/**
* The small picture beside a feed's posts: the feed's own, or else the site's icon, where
* sites keep it.
*/
private fun iconOf(cache: FeedCache): String? {
cache.iconUrl?.let { return it }
val page = cache.siteUrl ?: cache.articles.firstOrNull { it.link.isNotEmpty() }?.link ?: cache.url
return runCatching { URL(page).let { "https://${it.host}/favicon.ico" } }.getOrNull()
}
/** Puts what is stored before the page. Called with [lock] held. */
private fun publish(refreshing: Boolean = mutableState.value.refreshing) {
val names = feeds.associate { it.url to it.title }
val read = stored.read.toHashSet()
val items = stored.feeds.asSequence()
.filter { it.url in names }
.flatMap { cache ->
val icon = iconOf(cache)
cache.articles.asSequence().map { Item(it, names.getValue(cache.url), it.id in read, icon) }
}
.sortedByDescending { it.article.published }
.take(MAX_ARTICLES)
.toList()
mutableState.value = State(
loaded = true,
feeds = feeds,
items = items,
refreshing = refreshing,
lastRefresh = stored.lastRefresh,
failures = feeds.mapNotNull { feed -> failures[feed.url]?.let { Failure(feed, it) } },
)
}
private fun file(context: Context) = File(context.filesDir, FILE)
private fun load(context: Context): Stored = try {
val file = file(context)
if (file.exists()) kotlinxJson.decodeFromString(Stored.serializer(), file.readText()) else Stored()
} catch (e: Exception) {
Log.w(TAG, "Could not read the stored posts; starting afresh", e)
Stored()
}
/** Writes what is stored. Called with [lock] held. */
private fun save() {
val context = appContext ?: return
try {
val file = file(context)
val temp = File(file.parentFile, "$FILE.tmp")
temp.writeText(kotlinxJson.encodeToString(Stored.serializer(), stored))
if (!temp.renameTo(file)) {
file.delete()
temp.renameTo(file)
}
} catch (e: Exception) {
Log.w(TAG, "Could not store the posts", e)
}
}
}
@@ -0,0 +1,162 @@
package app.flexera.reader
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Delete
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import app.lawnchair.preferences2.asState
import app.lawnchair.preferences2.preferenceManager2
import app.lawnchair.ui.preferences.LocalIsExpandedScreen
import app.lawnchair.ui.preferences.components.layout.PreferenceGroup
import app.lawnchair.ui.preferences.components.layout.PreferenceLayout
import app.lawnchair.ui.preferences.components.layout.PreferenceTemplate
import com.android.launcher3.R
import kotlinx.coroutines.launch
/**
* The RSS reader's settings: adding a feed by a site's or a feed's address, and the feeds
* followed, each with a button that removes it. Reached under Settings, Gestures, and from the
* reader's page.
*/
@Composable
fun RssReaderSettings(modifier: Modifier = Modifier) {
val context = LocalContext.current
val focus = LocalFocusManager.current
val scope = rememberCoroutineScope()
val feeds by preferenceManager2().rssFeeds.asState()
var address by rememberSaveable { mutableStateOf("") }
var adding by remember { mutableStateOf(false) }
var note by remember { mutableStateOf<String?>(null) }
fun add() {
val typed = address.trim()
if (typed.isEmpty() || adding) return
focus.clearFocus()
adding = true
note = null
scope.launch {
val result = RssReader.addFeed(context, typed)
adding = false
note = when (result) {
is RssReader.AddResult.Added -> {
address = ""
context.getString(R.string.flexera_rss_added, result.feed.title)
}
is RssReader.AddResult.AlreadyThere -> context.getString(R.string.flexera_rss_already_there, result.feed.title)
is RssReader.AddResult.Failed -> problemText(context, result.problem)
}
}
}
PreferenceLayout(
label = stringResource(id = R.string.flexera_rss_reader),
backArrowVisible = !LocalIsExpandedScreen.current,
modifier = modifier,
) {
PreferenceGroup(
heading = stringResource(id = R.string.flexera_rss_add_heading),
description = stringResource(id = R.string.flexera_rss_add_description),
) {
PreferenceTemplate(
title = {
Column {
Row(verticalAlignment = Alignment.CenterVertically) {
OutlinedTextField(
value = address,
onValueChange = {
address = it
note = null
},
label = { Text(text = stringResource(id = R.string.flexera_rss_address)) },
singleLine = true,
enabled = !adding,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { add() }),
modifier = Modifier.weight(1f),
)
Spacer(modifier = Modifier.width(12.dp))
Button(onClick = { add() }, enabled = !adding && address.isNotBlank()) {
Text(text = stringResource(id = R.string.flexera_rss_add))
}
}
if (adding) {
LinearProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.padding(top = 12.dp),
)
}
// Read out by TalkBack, so that it hears what came of the address.
note?.let {
Text(
text = it,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier
.padding(top = 12.dp)
.semantics { liveRegion = LiveRegionMode.Polite },
)
}
}
},
)
}
PreferenceGroup(
heading = stringResource(id = R.string.flexera_rss_feeds_heading),
description = stringResource(id = R.string.flexera_rss_feeds_description),
) {
if (feeds.isEmpty()) {
PreferenceTemplate(
title = { Text(text = stringResource(id = R.string.flexera_rss_no_feeds)) },
enabled = false,
)
}
feeds.forEach { feed ->
PreferenceTemplate(
title = { Text(text = feed.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
description = { Text(text = feed.url, maxLines = 1, overflow = TextOverflow.Ellipsis) },
endWidget = {
IconButton(onClick = { scope.launch { RssReader.removeFeed(context, feed) } }) {
Icon(
imageVector = Icons.Rounded.Delete,
contentDescription = stringResource(id = R.string.flexera_rss_remove, feed.title),
)
}
},
)
}
}
}
}
+386 -50
View File
@@ -1,10 +1,16 @@
package app.flexera.ui
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.provider.Settings
import android.text.format.Formatter
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -12,27 +18,49 @@ import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Download
import androidx.compose.material.icons.rounded.InstallMobile
import androidx.compose.material.icons.rounded.Refresh
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
@@ -40,6 +68,7 @@ import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import app.flexera.update.CheckProblem
import app.flexera.update.FlexeraRelease
import app.flexera.update.FlexeraUpdater
import app.flexera.update.UpdateFailure
@@ -54,6 +83,9 @@ import app.lawnchair.ui.preferences.components.layout.PreferenceTemplate
import app.lawnchair.ui.preferences.navigation.AboutLicenses
import com.android.launcher3.BuildConfig
import com.android.launcher3.R
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import com.google.zxing.qrcode.encoder.Encoder
import kotlin.math.floor
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@@ -62,6 +94,12 @@ private const val LAWNCHAIR_SOURCE_URL = "https://github.com/LawnchairLauncher/l
/** Release notes longer than this are cut off; the full text is on the release page. */
private const val MAX_NOTES_LENGTH = 600
/** Large enough to scan from another phone held at arm's length. */
private val QR_CODE_SIZE = 220.dp
/** The blank border around a QR code, in modules; the standard asks for four. */
private const val QR_QUIET_ZONE_MODULES = 4
/**
* Flexera Launcher's About screen.
*
@@ -93,7 +131,7 @@ fun FlexeraAbout(modifier: Modifier = Modifier) {
val updateRows = buildList<@Composable () -> Unit> {
if (FlexeraUpdater.isSupported) {
add { UpdateStatusRow(updateState) }
add { UpdateCard(updateState) }
val notes = updateState.release()?.notes.orEmpty()
if (notes.isNotBlank()) {
add {
@@ -178,6 +216,13 @@ fun FlexeraAbout(modifier: Modifier = Modifier) {
item { PreferenceGroupHeading(stringResource(id = R.string.flexera_update_heading)) }
groupRows(updateRows)
item { PreferenceGroupHeading(stringResource(id = R.string.flexera_about_share)) }
item {
PreferenceGroupItem {
ShareCard(scanUrl = FlexeraUpdater.LATEST_APK_URL, pageUrl = FlexeraUpdater.RELEASES_PAGE_URL)
}
}
item { PreferenceGroupHeading(stringResource(id = R.string.flexera_about_built_on)) }
groupRows(
listOf<@Composable () -> Unit>(
@@ -219,80 +264,353 @@ fun FlexeraAbout(modifier: Modifier = Modifier) {
}
}
/** What the update card shows; every part may be missing. */
private class UpdateCardContent(
val title: String? = null,
val body: String? = null,
/** From 0 to 1, while a download runs. */
val progress: Float? = null,
val action: UpdateAction? = null,
)
/** The button at the bottom of the update card. */
private class UpdateAction(
val label: String,
val icon: ImageVector?,
val onClick: () -> Unit,
/** Shown as a disabled button with a spinner while something is already under way. */
val busy: Boolean = false,
)
/**
* The row that says where the updater stands and, when there is something to do, does it on tap:
* check, download, or install.
* The card that says where the updater stands and offers the next step as a large button: check,
* download (which goes on to the installation by itself), or install.
*/
@Composable
private fun UpdateStatusRow(state: UpdateState) {
private fun UpdateCard(state: UpdateState) {
val context = LocalContext.current
when (state) {
UpdateState.Idle -> ClickablePreference(
label = stringResource(id = R.string.flexera_update_check),
subtitle = stringResource(id = R.string.flexera_update_check_idle),
onClick = { FlexeraUpdater.check(context) },
// How many checks and downloads the owner has started from the card; TalkBack reads out how
// they went (see announce below). A download that is under way when the card appears was
// started from it too.
var asked by remember { mutableIntStateOf(if (state is UpdateState.Downloading) 1 else 0) }
// Android 17 asks the owner before an app may reach devices on the local network, and an
// update server at home is one. The answer starts again what Android kept from the server,
// the download or the check; a "no" that Android no longer asks about leads to the app's
// page in the phone's settings instead.
val askForLocalNetwork = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission(),
) { granted ->
val activity = context.findActivity()
if (granted || activity == null ||
activity.shouldShowRequestPermissionRationale(FlexeraUpdater.LOCAL_NETWORK_PERMISSION)
) {
asked++
// A failed download still knows its release, so it needs no new check first.
if (state is UpdateState.Failed && state.release != null) {
FlexeraUpdater.download(context)
} else {
FlexeraUpdater.check(context)
}
} else {
openAppSettings(context)
}
}
val check = UpdateAction(
label = stringResource(id = R.string.flexera_update_check),
icon = Icons.Rounded.Refresh,
onClick = {
asked++
FlexeraUpdater.check(context)
},
)
val download = UpdateAction(
label = stringResource(id = R.string.flexera_update_download),
icon = Icons.Rounded.Download,
onClick = {
asked++
FlexeraUpdater.download(context)
},
)
val allowLocalNetwork = UpdateAction(
label = stringResource(id = R.string.flexera_update_allow_local_network),
icon = null,
onClick = { askForLocalNetwork.launch(FlexeraUpdater.LOCAL_NETWORK_PERMISSION) },
)
val content = when (state) {
UpdateState.Idle -> UpdateCardContent(
body = stringResource(id = R.string.flexera_update_check_idle),
action = check,
)
UpdateState.Checking -> PreferenceTemplate(
title = { Text(text = stringResource(id = R.string.flexera_update_checking)) },
UpdateState.Checking -> UpdateCardContent(
body = stringResource(id = R.string.flexera_update_check_idle),
action = UpdateAction(
label = stringResource(id = R.string.flexera_update_checking),
icon = null,
onClick = {},
busy = true,
),
)
UpdateState.UpToDate -> ClickablePreference(
label = stringResource(id = R.string.flexera_update_check),
subtitle = stringResource(id = R.string.flexera_update_up_to_date),
onClick = { FlexeraUpdater.check(context) },
UpdateState.UpToDate -> UpdateCardContent(
title = stringResource(id = R.string.flexera_update_up_to_date),
body = stringResource(id = R.string.flexera_update_check_idle),
action = check,
)
is UpdateState.Available -> ClickablePreference(
label = stringResource(id = R.string.flexera_update_download, state.release.versionName),
subtitle = downloadSizeText(context, state.release),
onClick = { FlexeraUpdater.download(context) },
is UpdateState.Available -> UpdateCardContent(
title = stringResource(id = R.string.flexera_update_available, state.release.versionName),
body = downloadSizeText(context, state.release),
action = download,
)
is UpdateState.Downloading -> PreferenceTemplate(
title = { Text(text = stringResource(id = R.string.flexera_update_downloading, state.release.versionName)) },
description = {
Column {
Text(text = stringResource(id = R.string.flexera_update_progress, (state.progress * 100).toInt()))
LinearProgressIndicator(
progress = { state.progress },
modifier = Modifier
.fillMaxWidth()
.padding(top = 8.dp),
)
}
},
is UpdateState.Downloading -> UpdateCardContent(
title = stringResource(id = R.string.flexera_update_downloading, state.release.versionName),
body = stringResource(id = R.string.flexera_update_progress, (state.progress * 100).toInt()),
progress = state.progress,
// The button stays, disabled, so that TalkBack keeps its place on it until the
// download ends and the button offers what comes next.
action = UpdateAction(
label = stringResource(id = R.string.flexera_update_downloading_button),
icon = null,
onClick = {},
busy = true,
),
)
is UpdateState.ReadyToInstall -> ClickablePreference(
label = stringResource(id = R.string.flexera_update_install, state.release.versionName),
subtitle = stringResource(id = R.string.flexera_update_install_hint),
onClick = { FlexeraUpdater.install(context) },
is UpdateState.ReadyToInstall -> UpdateCardContent(
title = stringResource(id = R.string.flexera_update_ready, state.release.versionName),
body = stringResource(id = R.string.flexera_update_install_hint),
action = UpdateAction(
label = stringResource(id = R.string.flexera_update_install),
icon = Icons.Rounded.InstallMobile,
onClick = { FlexeraUpdater.install(context) },
),
)
is UpdateState.Failed -> {
val release = state.release
if (release == null) {
ClickablePreference(
label = stringResource(id = R.string.flexera_update_check),
subtitle = stringResource(id = R.string.flexera_update_check_failed),
onClick = { FlexeraUpdater.check(context) },
UpdateCardContent(
title = stringResource(id = R.string.flexera_update_failed_title),
body = checkFailureText(state),
action = if (state.problem == CheckProblem.LOCAL_NETWORK) {
allowLocalNetwork
} else {
UpdateAction(
label = stringResource(id = R.string.flexera_update_try_again),
icon = Icons.Rounded.Refresh,
onClick = check.onClick,
)
},
)
} else {
ClickablePreference(
label = stringResource(id = R.string.flexera_update_download, release.versionName),
subtitle = stringResource(
id = if (state.failure == UpdateFailure.WRONG_FILE) {
R.string.flexera_update_wrong_file
} else {
R.string.flexera_update_download_failed
},
),
onClick = { FlexeraUpdater.download(context) },
// A download that Android kept from the server would only fail again until the
// owner allows local network access, so that is what the button asks for.
val blocked = state.problem == CheckProblem.LOCAL_NETWORK
UpdateCardContent(
title = stringResource(id = R.string.flexera_update_available, release.versionName),
body = when {
state.failure == UpdateFailure.WRONG_FILE -> stringResource(id = R.string.flexera_update_wrong_file)
blocked -> stringResource(
id = R.string.flexera_update_download_failed_local_network,
FlexeraUpdater.SERVER_HOST,
)
else -> stringResource(id = R.string.flexera_update_download_failed)
},
action = if (blocked) {
allowLocalNetwork
} else {
UpdateAction(
label = stringResource(id = R.string.flexera_update_try_again),
icon = Icons.Rounded.Download,
onClick = download.onClick,
)
},
)
}
}
}
// Once the owner has started a check or a download from the card, TalkBack reads out each
// outcome it shows, so that they hear how it went, also when it went as the time before. Not
// what the card says when the screen opens, which is read with the rest of the screen, and
// not the steps in between: a download would be read out at every percent.
val announce = asked > 0 && when (state) {
UpdateState.Idle, UpdateState.Checking, is UpdateState.Downloading -> false
UpdateState.UpToDate, is UpdateState.Available, is UpdateState.ReadyToInstall, is UpdateState.Failed -> true
}
val title = content.title
val body = content.body
val progress = content.progress
val action = content.action
Column(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.surfaceContainer)
.padding(16.dp),
) {
// The title and the body are read as one. The region is made anew each time it starts or
// stops being read out: Compose tells TalkBack about a new region once, as it is laid
// out, but about one that turns live as its text changes once for each change, and
// TalkBack could read it out twice. It is made anew for each step the owner starts as
// well: a step that fails as the one before did may change nothing on the card, since
// offline a check can be over before "Checking" is ever drawn.
key(announce, asked) {
Column(
modifier = Modifier.semantics(mergeDescendants = true) {
if (announce) liveRegion = LiveRegionMode.Polite
},
) {
if (title != null) {
Text(
text = title,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
)
}
if (body != null) {
if (title != null) Spacer(Modifier.height(4.dp))
Text(
text = body,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
if (progress != null) {
Spacer(Modifier.height(16.dp))
LinearProgressIndicator(
progress = { progress },
modifier = Modifier.fillMaxWidth(),
)
}
if (action != null) {
Spacer(Modifier.height(16.dp))
UpdateButton(action)
}
}
}
/** A full-width filled button, so the next step stands out from the settings rows around it. */
@Composable
private fun UpdateButton(action: UpdateAction) {
val icon = action.icon
Button(
onClick = action.onClick,
enabled = !action.busy,
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 56.dp),
contentPadding = ButtonDefaults.ButtonWithIconContentPadding,
) {
if (action.busy) {
CircularProgressIndicator(
modifier = Modifier.size(ButtonDefaults.IconSize),
strokeWidth = 2.dp,
color = LocalContentColor.current,
)
Spacer(Modifier.width(ButtonDefaults.IconSpacing))
} else if (icon != null) {
Icon(
imageVector = icon,
contentDescription = null,
modifier = Modifier.size(ButtonDefaults.IconSize),
)
Spacer(Modifier.width(ButtonDefaults.IconSpacing))
}
Text(text = action.label, style = MaterialTheme.typography.titleSmall)
}
}
/**
* What the owner holds up for someone who wants the app: a QR code that downloads the newest
* APK ([scanUrl]), with the address of the release page under it for anyone who would rather
* type one ([pageUrl]); that one is shorter and shows all versions.
*/
@Composable
private fun ShareCard(scanUrl: String, pageUrl: String) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 20.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
QrCode(
text = scanUrl,
description = stringResource(id = R.string.flexera_about_share_qr_description),
modifier = Modifier.size(QR_CODE_SIZE),
)
Spacer(Modifier.height(16.dp))
Text(
text = stringResource(id = R.string.flexera_about_share_title),
style = MaterialTheme.typography.titleMedium,
textAlign = TextAlign.Center,
)
Spacer(Modifier.height(4.dp))
Text(
text = pageUrl.removePrefix("https://"),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
)
}
}
/**
* A QR code for [text], made on the phone. It is black on white in every theme, with the blank
* border the standard asks for, because that is what scanners read most reliably.
*/
@Composable
private fun QrCode(text: String, description: String, modifier: Modifier = Modifier) {
val modules = remember(text) { Encoder.encode(text, ErrorCorrectionLevel.M).matrix }
Canvas(
modifier = modifier
.clip(RoundedCornerShape(12.dp))
.semantics { contentDescription = description },
) {
drawRect(Color.White)
// Whole pixels per module, so neighbouring modules join without a seam.
val count = modules.width + 2 * QR_QUIET_ZONE_MODULES
val module = floor(size.minDimension / count)
val left = floor((size.width - module * count) / 2f) + module * QR_QUIET_ZONE_MODULES
val top = floor((size.height - module * count) / 2f) + module * QR_QUIET_ZONE_MODULES
for (y in 0 until modules.height) {
for (x in 0 until modules.width) {
if (modules.get(x, y).toInt() == 1) {
drawRect(
color = Color.Black,
topLeft = Offset(left + x * module, top + y * module),
size = Size(module, module),
)
}
}
}
}
}
/**
* Says why a check for updates failed and what to do about it, then the error's own words, which
* are what someone looking for the cause will ask for.
*/
@Composable
private fun checkFailureText(state: UpdateState.Failed): String {
val host = FlexeraUpdater.SERVER_HOST
val reason = when (state.problem) {
CheckProblem.NO_PERMISSION -> stringResource(id = R.string.flexera_update_failed_no_permission)
CheckProblem.SERVER_NOT_FOUND -> stringResource(id = R.string.flexera_update_failed_not_found, host)
CheckProblem.NOT_SECURE -> stringResource(id = R.string.flexera_update_failed_not_secure, host)
CheckProblem.SERVER_ERROR -> stringResource(id = R.string.flexera_update_failed_server_error, host)
CheckProblem.BAD_ANSWER -> stringResource(id = R.string.flexera_update_failed_bad_answer, host)
CheckProblem.LOCAL_NETWORK -> stringResource(id = R.string.flexera_update_failed_local_network, host)
CheckProblem.NO_ANSWER, null -> stringResource(id = R.string.flexera_update_failed_no_answer, host)
}
val detail = state.detail ?: return reason
return reason + "\n" + stringResource(id = R.string.flexera_update_failed_detail, detail)
}
@Composable
@@ -341,3 +659,21 @@ private fun openNotificationSettings(context: Context) {
context.startActivity(intent)
}
}
/** Opens this app's page in the phone's settings, where its permissions are. */
private fun openAppSettings(context: Context) {
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, "package:${context.packageName}".toUri())
if (intent.resolveActivity(context.packageManager) != null) {
context.startActivity(intent)
}
}
/** The activity this context belongs to, if it belongs to one. */
private fun Context.findActivity(): Activity? {
var current: Context? = this
while (current != null) {
if (current is Activity) return current
current = (current as? ContextWrapper)?.baseContext
}
return null
}
@@ -4,11 +4,14 @@ import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import app.flexera.drawer.FlexeraDrawer
import app.lawnchair.preferences.getAdapter
import app.lawnchair.preferences.preferenceManager
import app.lawnchair.preferences2.preferenceManager2
import app.lawnchair.ui.preferences.LocalIsExpandedScreen
import app.lawnchair.ui.preferences.components.NavigationActionPreference
import app.lawnchair.ui.preferences.components.controls.ListPreference
import app.lawnchair.ui.preferences.components.controls.ListPreferenceEntry
import app.lawnchair.ui.preferences.components.controls.SwitchPreference
import app.lawnchair.ui.preferences.components.layout.PreferenceGroup
import app.lawnchair.ui.preferences.components.layout.PreferenceLayout
@@ -49,6 +52,11 @@ fun FlexeraDrawerSettings(modifier: Modifier = Modifier) {
label = stringResource(id = R.string.suggestion_pref_screen_title),
destination = Predictions,
)
SwitchPreference(
label = stringResource(id = R.string.flexera_notification_previews),
description = stringResource(id = R.string.flexera_notification_previews_description),
adapter = prefs.flexeraNotificationPreviews.getAdapter(),
)
SwitchPreference(
label = stringResource(id = R.string.pref_all_apps_remember_position_title),
description = stringResource(id = R.string.pref_all_apps_remember_position_description),
@@ -70,6 +78,18 @@ fun FlexeraDrawerSettings(modifier: Modifier = Modifier) {
// No background colour or opacity here: the drawer is transparent with white text, and a
// light panel behind white text would make the list unreadable.
PreferenceGroup(heading = stringResource(id = R.string.style)) {
ListPreference(
adapter = prefs.flexeraDrawerRowSize.getAdapter(),
entries = listOf(
ListPreferenceEntry(FlexeraDrawer.RowSize.COMPACT.key) {
stringResource(id = R.string.flexera_row_size_compact)
},
ListPreferenceEntry(FlexeraDrawer.RowSize.COMFY.key) {
stringResource(id = R.string.flexera_row_size_comfy)
},
),
label = stringResource(id = R.string.flexera_row_size),
)
SwitchPreference(
label = stringResource(id = R.string.pref_all_apps_search_bar_background),
adapter = prefs2.appDrawerSearchBarBackground.getAdapter(),
+384 -29
View File
@@ -1,5 +1,6 @@
package app.flexera.update
import android.Manifest
import android.app.Activity
import android.app.Application
import android.app.Notification
@@ -9,8 +10,12 @@ import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.util.Log
import androidx.core.content.FileProvider
@@ -22,8 +27,14 @@ import com.android.launcher3.BuildConfig
import com.android.launcher3.R
import java.io.File
import java.io.IOException
import java.lang.ref.WeakReference
import java.net.HttpURLConnection
import java.net.InetAddress
import java.net.NetworkInterface
import java.net.SocketTimeoutException
import java.net.URL
import java.net.UnknownHostException
import javax.net.ssl.SSLException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
@@ -31,6 +42,7 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import org.json.JSONException
import org.json.JSONObject
/** One published version of Flexera Launcher. */
@@ -56,6 +68,39 @@ enum class UpdateFailure {
WRONG_FILE,
}
/**
* Why a check for updates failed, as far as the phone can tell. The About screen says it in
* words, because "could not reach the server" alone leaves the owner guessing between the
* connection, a VPN, the server and the phone's own settings.
*/
enum class CheckProblem {
/** Android does not let this app use the network (a per-app switch on some systems). */
NO_PERMISSION,
/** The server's name could not be looked up. */
SERVER_NOT_FOUND,
/** The server was found but did not answer in time, or refused the connection. */
NO_ANSWER,
/**
* The server's address is on the network the phone itself is on (a server at home, reached
* over the home Wi-Fi), and Android has not been told to let this app reach devices there.
* Since Android 17 that takes a permission of its own; without it the connection is
* dropped without a word and looks like a server that does not answer.
*/
LOCAL_NETWORK,
/** The encrypted connection could not be set up. */
NOT_SECURE,
/** The server answered, with an error. */
SERVER_ERROR,
/** The server answered with something that is not a release. */
BAD_ANSWER,
}
/** Where the updater currently stands. The About screen shows one row per state. */
sealed interface UpdateState {
/** Nothing has been checked since the launcher started. */
@@ -72,8 +117,18 @@ sealed interface UpdateState {
data class ReadyToInstall(val release: FlexeraRelease, val file: File) : UpdateState
/** [release] is set when the failure happened after a newer version had been found. */
data class Failed(val failure: UpdateFailure, val release: FlexeraRelease? = null) : UpdateState
/**
* [release] is set when the failure happened after a newer version had been found. For a
* failed check, [problem] says why and [detail] carries the error's own words, for
* whoever has to find the cause. A failed download sets [problem] only to
* [CheckProblem.LOCAL_NETWORK], the one cause the owner can remove from the About screen.
*/
data class Failed(
val failure: UpdateFailure,
val release: FlexeraRelease? = null,
val problem: CheckProblem? = null,
val detail: String? = null,
) : UpdateState
}
/**
@@ -86,8 +141,10 @@ sealed interface UpdateState {
* app, so a file from anywhere else cannot replace the launcher.
*
* It checks on its own at most once a day, when the home screen or settings come to the front,
* and posts a notification when it finds a newer version. This is the only thing in the app that
* uses the network (see [FlexeraNetwork]).
* and posts a notification when it finds a newer version. On Android 13 and newer an app may not
* post one until the owner allows it, so the first time a check finds an update without that, it
* asks ([askToNotify]). This is the only thing in the app that uses the network (see
* [FlexeraNetwork]).
*/
object FlexeraUpdater {
@@ -100,6 +157,13 @@ object FlexeraUpdater {
/** The page listing every release, for the About screen's "All versions" link. */
const val RELEASES_PAGE_URL = "$SERVER/$RELEASE_REPOSITORY/releases"
/**
* Always the APK of the newest release: the server sends "latest" on to the newest release,
* and every release carries its APK under this one name as well (flexera/release.ps1). What
* the QR code on the About screen holds, so that scanning it starts the download.
*/
const val LATEST_APK_URL = "$SERVER/$RELEASE_REPOSITORY/releases/download/latest/FlexeraLauncher.apk"
private const val CONNECT_TIMEOUT_MS = 15_000
private const val READ_TIMEOUT_MS = 30_000
@@ -111,8 +175,34 @@ object FlexeraUpdater {
private const val KEY_LAST_ATTEMPT_OK = "last_attempt_ok"
private const val KEY_NOTIFIED_VERSION = "notified_version"
/** How many times the owner was asked to allow notifications. */
private const val KEY_NOTIFY_ASKS = "notify_asks"
/** The most times the owner is asked to allow notifications: as often as Android lets an app ask. */
private const val MAX_NOTIFY_ASKS = 2
private const val REQUEST_NOTIFICATIONS = 0xF1F
/**
* When the owner last asked for the update to be installed: by tapping Download, or Install
* while Android still had to be told to let this app install apps. Kept on disk, because
* Android may end the launcher's process while the owner is in that setting.
*/
private const val KEY_INSTALL_REQUESTED_AT = "install_requested_at"
/** True while the owner was sent to Android's "Install unknown apps" setting. */
private const val KEY_AWAITING_INSTALL_PERMISSION = "awaiting_install_permission"
/**
* How long after such a request the installer may still open by itself. An installer that
* pops up hours after the owner tapped Download would come as a surprise.
*/
private const val AUTO_INSTALL_WINDOW_MS = 30L * 60 * 1000
private const val UPDATES_DIR = "updates"
private const val APK_PREFIX = "FlexeraLauncher-"
/** Added to the APK's name while it downloads, so that only a finished file ends in ".apk". */
private const val PARTIAL_SUFFIX = ".part"
private const val CHANNEL_ID = "flexera_updates"
private const val NOTIFICATION_ID = 0xF1E
@@ -133,17 +223,49 @@ object FlexeraUpdater {
private var nextAutomaticCheckAt = 0L
/**
* Starts the once-a-day automatic check. Called once, from the application's onCreate.
* The activity of this app that is in front (home screen or settings), if one is. The
* installer opens from it; Android does not let an app in the background open one.
*/
@Volatile
private var frontActivity: WeakReference<Activity>? = null
/** The release whose notification waits for the owner to allow notifications. */
@Volatile
private var waitingToNotify: FlexeraRelease? = null
private val mainHandler = Handler(Looper.getMainLooper())
/**
* Starts the once-a-day automatic check, and lets a requested install go ahead whenever one
* of the app's screens comes to the front. Called once, from the application's onCreate.
*/
@JvmStatic
fun start(app: Application) {
if (!isSupported) return
scope.launch { restoreDownload(app) }
scope.launch {
// A half-written APK at this point is one that an earlier process did not finish: this
// process has only just started, so no download can be running yet.
updatesDir(app)
.listFiles { file -> file.name.startsWith(APK_PREFIX) && file.name.endsWith(PARTIAL_SUFFIX) }
?.forEach { it.delete() }
restoreDownload(app)
// The process may have been restarted while the owner was allowing installs.
installIfRequested()
}
app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
override fun onActivityResumed(activity: Activity) = checkIfDue(activity.applicationContext)
override fun onActivityResumed(activity: Activity) {
frontActivity = WeakReference(activity)
notifyIfAllowedNow(activity.applicationContext)
checkIfDue(activity.applicationContext)
installIfRequested()
}
override fun onActivityPaused(activity: Activity) {
if (frontActivity?.get() === activity) frontActivity = null
}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit
override fun onActivityStarted(activity: Activity) = Unit
override fun onActivityPaused(activity: Activity) = Unit
override fun onActivityStopped(activity: Activity) = Unit
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
override fun onActivityDestroyed(activity: Activity) = Unit
@@ -179,7 +301,12 @@ object FlexeraUpdater {
nextAutomaticCheckAt = System.currentTimeMillis() + RETRY_INTERVAL_MS
scope.launch {
val result = runCatching { fetchLatestRelease(app) }
val result = runCatching {
// Android drops a connection it does not allow without a word, and the check
// would wait out its time limit. Say at once what is needed instead.
if (blockedFromLocalNetwork(app)) throw LocalNetworkBlockedException()
fetchLatestRelease(app)
}
prefs(app).edit()
.putLong(KEY_LAST_ATTEMPT, System.currentTimeMillis())
.putBoolean(KEY_LAST_ATTEMPT_OK, result.isSuccess)
@@ -190,11 +317,11 @@ object FlexeraUpdater {
Log.w(TAG, "Update check failed", error)
// A background check that fails stays quiet: the About screen keeps what it showed
// before, including an update that is already waiting. It tries again in an hour.
mutableState.value = if (automatic) before else UpdateState.Failed(UpdateFailure.CHECK)
mutableState.value = if (automatic) before else failedCheck(app, error)
return@launch
}
if (release == null || !isNewer(release.versionName, BuildConfig.VERSION_NAME)) {
if (!isNewer(release.versionName, BuildConfig.VERSION_NAME)) {
clearDownloads(app)
mutableState.value = UpdateState.UpToDate
return@launch
@@ -210,7 +337,10 @@ object FlexeraUpdater {
}
}
/** Downloads the APK of the release that the last check found. */
/**
* Downloads the APK of the release that the last check found, then hands it to Android's
* installer straight away (see [installIfRequested]).
*/
@JvmStatic
fun download(context: Context) {
val release = when (val current = mutableState.value) {
@@ -219,24 +349,41 @@ object FlexeraUpdater {
else -> null
} ?: return
val app = context.applicationContext
requestInstall(app, awaitingPermission = false)
mutableState.value = UpdateState.Downloading(release, 0f)
scope.launch {
val target = apkFile(app, release)
try {
// The APK comes from the same server as the check, so Android may keep this app
// from it in the same way. Say at once what is needed, as the check does, rather
// than wait out the time limit.
if (blockedFromLocalNetwork(app)) throw LocalNetworkBlockedException()
downloadApk(app, release, target) { progress ->
mutableState.value = UpdateState.Downloading(release, progress)
}
} catch (error: Exception) {
Log.w(TAG, "Update download failed", error)
mutableState.value = UpdateState.Failed(UpdateFailure.DOWNLOAD, release)
clearInstallRequest(app)
// As after a failed check: a server that did not answer in time may still be one
// that Android kept this app from, where the look before could not tell (the phone
// joined the home Wi-Fi during the download, say).
val blocked = error is LocalNetworkBlockedException ||
(error is SocketTimeoutException && blockedFromLocalNetwork(app))
mutableState.value = UpdateState.Failed(
UpdateFailure.DOWNLOAD,
release,
problem = if (blocked) CheckProblem.LOCAL_NETWORK else null,
)
return@launch
}
if (isValidUpdate(app, target)) {
mutableState.value = UpdateState.ReadyToInstall(release, target)
installIfRequested()
} else {
Log.w(TAG, "Downloaded file is not a newer ${app.packageName}")
target.delete()
clearInstallRequest(app)
mutableState.value = UpdateState.Failed(UpdateFailure.WRONG_FILE, release)
}
}
@@ -245,18 +392,20 @@ object FlexeraUpdater {
/**
* Hands the downloaded APK to Android's installer, which asks the owner to confirm. The first
* time, Android wants the owner to allow this app to install apps; this opens that setting
* instead, and the owner taps Install again afterwards.
* instead, and the installer follows by itself when the owner comes back having allowed it.
*/
@JvmStatic
fun install(context: Context) {
val ready = mutableState.value as? UpdateState.ReadyToInstall ?: return
if (!ready.file.exists()) {
// Android cleared the cache in the meantime; find the release again.
clearInstallRequest(context)
mutableState.value = UpdateState.Idle
check(context)
return
}
if (!context.packageManager.canRequestPackageInstalls()) {
requestInstall(context, awaitingPermission = true)
val settings = Intent(
Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
Uri.parse("package:${context.packageName}"),
@@ -264,6 +413,7 @@ object FlexeraUpdater {
context.startActivity(settings)
return
}
clearInstallRequest(context)
val uri = FileProvider.getUriForFile(context, "${BuildConfig.APPLICATION_ID}.fileprovider", ready.file)
val install = Intent(Intent.ACTION_VIEW)
.setDataAndType(uri, "application/vnd.android.package-archive")
@@ -271,25 +421,82 @@ object FlexeraUpdater {
context.startActivity(install)
}
/**
* Opens the installer when the owner asked for the update a short while ago, it is downloaded,
* and one of the app's screens is in front to open it from. Runs again each time a screen
* comes to the front, which is how the install carries on after the owner has allowed this
* app to install apps. Coming back without having allowed it drops the request, so the owner
* is not sent to that setting over and over; the Install button stays.
*/
private fun installIfRequested() {
mainHandler.post {
val activity = frontActivity?.get() ?: return@post
if (mutableState.value !is UpdateState.ReadyToInstall) return@post
val prefs = prefs(activity)
val requestedAt = prefs.getLong(KEY_INSTALL_REQUESTED_AT, 0L)
if (requestedAt == 0L) return@post
if (System.currentTimeMillis() - requestedAt !in 0 until AUTO_INSTALL_WINDOW_MS) {
clearInstallRequest(activity)
return@post
}
if (prefs.getBoolean(KEY_AWAITING_INSTALL_PERMISSION, false) &&
!activity.packageManager.canRequestPackageInstalls()
) {
clearInstallRequest(activity)
return@post
}
install(activity)
}
}
private fun requestInstall(context: Context, awaitingPermission: Boolean) {
prefs(context).edit()
.putLong(KEY_INSTALL_REQUESTED_AT, System.currentTimeMillis())
.putBoolean(KEY_AWAITING_INSTALL_PERMISSION, awaitingPermission)
.apply()
}
private fun clearInstallRequest(context: Context) {
prefs(context).edit()
.remove(KEY_INSTALL_REQUESTED_AT)
.remove(KEY_AWAITING_INSTALL_PERMISSION)
.apply()
}
/**
* Picks up an update that was downloaded before the launcher process was restarted, so the
* About screen can offer "Install" straight away. Also clears files left over from updates
* that are already installed.
* that are already installed. It does nothing unless the updater is idle, and it looks only at
* finished downloads: the About screen calls it each time it opens, also while a download runs
* or waits to be installed, and those files must stay.
*/
@JvmStatic
fun restoreDownload(context: Context) {
if (!isSupported) return
if (!isSupported || mutableState.value != UpdateState.Idle) return
val app = context.applicationContext
val candidates = updatesDir(app).listFiles { file -> file.name.startsWith(APK_PREFIX) }.orEmpty()
val candidates = updatesDir(app)
.listFiles { file -> file.name.startsWith(APK_PREFIX) && file.name.endsWith(".apk") }
.orEmpty()
// An update that was not installed before a newer one came out leaves two downloads here,
// listed in no set order. Only the newest is kept, so the card never offers a version that
// a later download has already replaced.
var restored: UpdateState.ReadyToInstall? = null
var restoredVersionCode = 0L
for (file in candidates) {
val info = if (file.name.endsWith(".apk")) app.packageManager.getPackageArchiveInfo(file.absolutePath, 0) else null
val info = app.packageManager.getPackageArchiveInfo(file.absolutePath, 0)
val versionName = info?.versionName
if (versionName != null && restored == null && isValidUpdate(app, file)) {
restored = UpdateState.ReadyToInstall(FlexeraRelease(versionName, "", "", file.length()), file)
} else {
if (info == null || versionName == null || !isValidUpdate(app, file)) {
file.delete()
continue
}
val versionCode = PackageInfoCompat.getLongVersionCode(info)
if (restored != null && versionCode <= restoredVersionCode) {
file.delete()
continue
}
restored?.file?.delete()
restored = UpdateState.ReadyToInstall(FlexeraRelease(versionName, "", "", file.length()), file)
restoredVersionCode = versionCode
}
if (restored != null) mutableState.compareAndSet(UpdateState.Idle, restored)
}
@@ -302,13 +509,123 @@ object FlexeraUpdater {
private fun isBusy(): Boolean =
mutableState.value.let { it is UpdateState.Checking || it is UpdateState.Downloading }
/** Returns the latest published release, or null when nothing has been published yet. */
private fun fetchLatestRelease(context: Context): FlexeraRelease? {
/** The server's name without the scheme, for messages. */
@JvmField
val SERVER_HOST: String = SERVER.substringAfter("://")
private class NoNetworkPermissionException : IOException("This app has no network permission")
private class ServerErrorException(status: Int) : IOException("The server answered HTTP $status")
private class BadAnswerException(message: String) : IOException(message)
private class LocalNetworkBlockedException : IOException("Android does not let this app reach the local network")
/**
* The permission Android 17 asks of an app before it may reach devices on the local
* network. Named by its text, because older Android versions, which the app also runs on,
* do not know it.
*/
const val LOCAL_NETWORK_PERMISSION = "android.permission.ACCESS_LOCAL_NETWORK"
/** The first Android version that keeps apps from the local network: Android 17. */
private const val LOCAL_NETWORK_SDK = 37
/**
* True when Android is keeping this app from the update server because the server is on
* the phone's own network and the owner has not allowed local network access. Looks the
* server's name up, so not for the main thread.
*/
private fun blockedFromLocalNetwork(context: Context): Boolean =
blocksLocalNetwork(context, URL(SERVER).host)
/**
* True when Android keeps this app from [host] because it is on the phone's own network
* and the owner has not allowed local network access; the RSS reader's feeds can be such a
* host too. Looks the name up, so not for the main thread.
*/
@JvmStatic
fun blocksLocalNetwork(context: Context, host: String): Boolean {
if (Build.VERSION.SDK_INT < LOCAL_NETWORK_SDK) return false
if (context.checkSelfPermission(LOCAL_NETWORK_PERMISSION) == PackageManager.PERMISSION_GRANTED) return false
return try {
// Looking a name up is allowed without the permission, also at a resolver at home.
InetAddress.getAllByName(host).any(::isOnOwnNetwork)
} catch (e: IOException) {
false
} catch (e: SecurityException) {
false
}
}
/**
* True for an address that this phone reaches directly, without a router in between: one
* inside the range of one of its own network connections. That is what Android counts as
* the local network.
*/
private fun isOnOwnNetwork(address: InetAddress): Boolean {
if (address.isLoopbackAddress) return false
if (address.isLinkLocalAddress) return true
val target = address.address
val interfaces = NetworkInterface.getNetworkInterfaces() ?: return false
for (network in interfaces) {
if (network.isLoopback || !network.isUp) continue
for (own in network.interfaceAddresses) {
val base = own.address?.address ?: continue
if (base.size != target.size) continue
var bits = own.networkPrefixLength.toInt()
if (bits <= 0) continue
var same = true
for (i in base.indices) {
if (bits <= 0) break
val mask = if (bits >= 8) 0xFF else (0xFF shl (8 - bits)) and 0xFF
if ((base[i].toInt() and mask) != (target[i].toInt() and mask)) {
same = false
break
}
bits -= 8
}
if (same) return true
}
}
return false
}
/** Turns the error of a failed check into a state that says what kind of failure it was. */
private fun failedCheck(context: Context, error: Throwable): UpdateState.Failed {
val kind = when (error) {
is NoNetworkPermissionException, is SecurityException -> CheckProblem.NO_PERMISSION
is LocalNetworkBlockedException -> CheckProblem.LOCAL_NETWORK
is UnknownHostException -> CheckProblem.SERVER_NOT_FOUND
is SSLException -> CheckProblem.NOT_SECURE
is ServerErrorException -> CheckProblem.SERVER_ERROR
is BadAnswerException, is JSONException -> CheckProblem.BAD_ANSWER
else -> CheckProblem.NO_ANSWER
}
// A server that did not answer may still be one that Android kept this app from, where
// the look before the check could not tell (the network changed in between, say).
val problem = if (kind == CheckProblem.NO_ANSWER && blockedFromLocalNetwork(context)) {
CheckProblem.LOCAL_NETWORK
} else {
kind
}
// Android's own error classes keep their names in a release build; this file's are
// renamed by the shrinker, and their messages say everything anyway.
val name = error.javaClass.name.takeIf { it.startsWith("java") || it.startsWith("android") || it.startsWith("org.json") }
?.substringAfterLast('.')
val detail = listOfNotNull(name, error.message).joinToString(": ").take(MAX_DETAIL_LENGTH)
return UpdateState.Failed(UpdateFailure.CHECK, problem = problem, detail = detail.ifEmpty { null })
}
private const val MAX_DETAIL_LENGTH = 200
/** Returns the latest published release. */
private fun fetchLatestRelease(context: Context): FlexeraRelease {
val connection = open(context, LATEST_RELEASE_URL)
try {
val status = connection.responseCode
if (status == HttpURLConnection.HTTP_NOT_FOUND) return null
if (status != HttpURLConnection.HTTP_OK) throw IOException("Update server answered HTTP $status")
// "Not found" is an error too: releases have been published for a long time, so it
// means the repository was moved or made private, or a proxy stopped passing the
// question on. Taken as "nothing newer", it would report the app up to date and delete
// an update that waits to be installed, and nothing would say that updates stopped.
if (status != HttpURLConnection.HTTP_OK) throw ServerErrorException(status)
val json = JSONObject(connection.inputStream.bufferedReader().use { it.readText() })
val tag = json.getString("tag_name")
@@ -326,7 +643,7 @@ object FlexeraUpdater {
apkSize = asset.optLong("size", 0L),
)
}
throw IOException("Release $tag has no APK attached")
throw BadAnswerException("Release $tag has no APK attached")
} finally {
connection.disconnect()
}
@@ -334,7 +651,7 @@ object FlexeraUpdater {
private fun downloadApk(context: Context, release: FlexeraRelease, target: File, onProgress: (Float) -> Unit) {
target.parentFile?.mkdirs()
val partial = File(target.path + ".part")
val partial = File(target.path + PARTIAL_SUFFIX)
val connection = open(context, release.apkUrl)
try {
val status = connection.responseCode
@@ -373,7 +690,7 @@ object FlexeraUpdater {
}
private fun open(context: Context, url: String): HttpURLConnection {
if (!FlexeraNetwork.hasInternetPermission(context)) throw IOException("No INTERNET permission")
if (!FlexeraNetwork.hasInternetPermission(context)) throw NoNetworkPermissionException()
return (URL(url).openConnection() as HttpURLConnection).apply {
connectTimeout = CONNECT_TIMEOUT_MS
readTimeout = READ_TIMEOUT_MS
@@ -416,7 +733,11 @@ object FlexeraUpdater {
val prefs = prefs(context)
if (prefs.getString(KEY_NOTIFIED_VERSION, null) == release.versionName) return
val manager = context.getSystemService(NotificationManager::class.java) ?: return
if (!manager.areNotificationsEnabled()) return
if (!manager.areNotificationsEnabled()) {
askToNotify(context, release)
return
}
waitingToNotify = null
manager.createNotificationChannel(
NotificationChannel(
@@ -442,8 +763,42 @@ object FlexeraUpdater {
prefs.edit().putString(KEY_NOTIFIED_VERSION, release.versionName).apply()
}
/**
* Asks the owner to let the app post notifications, so that it can say that [release] is
* waiting. Android 13 and newer keep an app's notifications off until it asks, and nothing
* else in the app asks. It is asked from the home screen or the settings, whichever is in
* front, right after the check that found the update, and at most [MAX_NOTIFY_ASKS] times.
* The notification follows as soon as the owner allows it ([notifyIfAllowedNow]), there or
* later in Android's settings. Notifications the owner turned off in Android's settings stay
* off: the permission is there then, and nothing is asked.
*/
private fun askToNotify(context: Context, release: FlexeraRelease) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return
val permission = Manifest.permission.POST_NOTIFICATIONS
if (context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) return
waitingToNotify = release
val prefs = prefs(context)
val asks = prefs.getInt(KEY_NOTIFY_ASKS, 0)
if (asks >= MAX_NOTIFY_ASKS) return
mainHandler.post {
// Gone to another app since the check began: asked another time instead.
val activity = frontActivity?.get() ?: return@post
prefs.edit().putInt(KEY_NOTIFY_ASKS, asks + 1).apply()
activity.requestPermissions(arrayOf(permission), REQUEST_NOTIFICATIONS)
}
}
/** Posts the notification that waited for the owner to allow notifications, once they have. */
private fun notifyIfAllowedNow(context: Context) {
val release = waitingToNotify ?: return
if (!canNotify(context)) return
waitingToNotify = null
scope.launch { notifyAvailable(context, release) }
}
private fun clearDownloads(context: Context) {
updatesDir(context).listFiles { file -> file.name.startsWith(APK_PREFIX) }?.forEach { it.delete() }
clearInstallRequest(context)
}
private fun apkFile(context: Context, release: FlexeraRelease): File {
@@ -0,0 +1,118 @@
package app.flexera.widget
import android.content.Context
import android.content.res.Configuration
import android.graphics.Paint
import android.graphics.Typeface
import android.graphics.fonts.FontStyle
import android.os.Build
import android.util.Log
import app.flexera.widget.ClockWidgetStore.Font
import com.android.launcher3.R
import java.io.File
/**
* The typefaces of the clock widget. The figures come in one of a few faces ([Font]): the
* phone's own font, its serif or monospaced one, or one of three widths of Google Sans Flex, the
* variable font that Lawnchair already carries for its own screens. The date and the weather
* line are always in the phone's own font.
*
* Every weight is made heavier by Android's Bold text setting (Android 12 and newer), as Android
* does for the text of a TextView but not for text drawn on a canvas.
*/
internal object ClockFonts {
private const val TAG = "ClockFonts"
/** The optical size the Google Sans Flex faces are drawn at: the one for display type. */
private const val OPTICAL_SIZE = 144
/** Google Sans Flex, once read; null until then, and after a read that failed. */
@Volatile
private var flex: Typeface? = null
private var flexFailed = false
/** The width of each Google Sans Flex face, from 25 (narrowest) to 151; null for the others. */
private fun width(font: Font): Int? = when (font) {
Font.FLEX -> 100
Font.NARROW -> 60
Font.WIDE -> 125
Font.DEFAULT, Font.SERIF, Font.MONO -> null
}
/** Sets [paint] to draw in [font] at [weight], from 100 (thin) to 900. */
fun apply(context: Context, paint: Paint, font: Font, weight: Int) {
// Cleared first: a paint keeps settings it is given again as they are, and would keep
// them on the plain typeface set below.
paint.setFontVariationSettings(null)
val width = width(font)
val variable = width?.let { flex(context) }
if (width == null || variable == null) {
val family = when (font) {
Font.SERIF -> Typeface.SERIF
Font.MONO -> Typeface.MONOSPACE
else -> Typeface.DEFAULT
}
paint.typeface = typeface(context, family, weight)
return
}
paint.typeface = variable
paint.setFontVariationSettings("'wght' ${boldText(context, weight)}, 'wdth' $width, 'opsz' $OPTICAL_SIZE")
}
/** [family] at [weight], from 100 (thin) to 900. Android 8 only knows a few weights. */
fun typeface(context: Context, family: Typeface, weight: Int): Typeface =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
Typeface.create(family, boldText(context, weight), false)
} else if (family == Typeface.DEFAULT) {
val name = when {
weight <= 100 -> "sans-serif-thin"
weight <= 300 -> "sans-serif-light"
weight <= 400 -> "sans-serif"
weight <= 500 -> "sans-serif-medium"
else -> "sans-serif-black"
}
Typeface.create(name, Typeface.NORMAL)
} else {
Typeface.create(family, if (weight >= BOLD) Typeface.BOLD else Typeface.NORMAL)
}
/** [weight] made heavier by Android's Bold text setting, if it is on. */
private fun boldText(context: Context, weight: Int): Int {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return weight
val adjustment = context.resources.configuration.fontWeightAdjustment
if (adjustment == 0 || adjustment == Configuration.FONT_WEIGHT_ADJUSTMENT_UNDEFINED) return weight
return (weight + adjustment).coerceIn(FontStyle.FONT_WEIGHT_MIN, FontStyle.FONT_WEIGHT_MAX)
}
/**
* Google Sans Flex with its axes free to set. The font is stored compressed in the APK, and
* Android drops the variation settings of a font it cannot map from there, so it is read
* from a copy in the cache, as Lawnchair's own FontCache does (and under the same name, so
* that there is one copy). Null if it cannot be read; the phone's own font stands in.
*/
private fun flex(context: Context): Typeface? {
flex?.let { return it }
if (flexFailed) return null
return try {
val app = context.applicationContext
val id = R.font.googlesansflex_variable
val file = File(app.cacheDir, "font_res_$id.ttf")
if (!file.exists() || file.length() == 0L) {
// Written beside it and then renamed, so that a half-written copy is never read.
val partial = File(app.cacheDir, "${file.name}.clock.tmp")
app.resources.openRawResource(id).use { input ->
partial.outputStream().use { output -> input.copyTo(output) }
}
if (!partial.renameTo(file)) partial.delete()
}
Typeface.Builder(file).build().also { flex = it }
} catch (e: Exception) {
Log.w(TAG, "Google Sans Flex could not be read", e)
flexFailed = true
null
}
}
private const val BOLD = 600
}
@@ -0,0 +1,313 @@
package app.flexera.widget
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import android.util.Log
import androidx.annotation.StringRes
import androidx.annotation.WorkerThread
import androidx.core.text.util.LocalePreferences
import com.android.launcher3.R
import com.android.launcher3.util.Executors
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
import java.util.Calendar
import java.util.Locale
import java.util.concurrent.CopyOnWriteArraySet
import kotlin.math.roundToInt
import org.json.JSONObject
/**
* The weather line of the clock widget: the temperature and a word for the sky at a place the
* owner has chosen.
*
* The data comes from Open-Meteo, a weather service that needs no account. It is asked only for
* a place the owner picked by name in the clock's options, never for where the phone is, so the
* launcher needs no location permission; and only while a clock with weather is in view, at most
* every [FRESH_MS], or after a request that failed, at intervals that grow from [RETRY_MS] to
* [RETRY_MAX_MS]. A search sends the name typed and the phone's language, and a forecast the
* place's coordinates, rounded to about a kilometre, and the unit of temperature. Nothing else
* goes out, as the privacy text in About and the clock's options say.
* The last answer is kept, so that the line is there at once and survives a spell offline.
*/
object ClockWeather {
/** A place found by name. [detail] tells places of one name apart: region and country. */
data class Place(val name: String, val detail: String, val latitude: Double, val longitude: Double)
/**
* What the service said: degrees in the unit the phone is set to, and a WMO weather code.
* [isDay] is whether the sun was up at the place when it was asked, and [sunrise] and
* [sunset] the times of that day there, in seconds since 1970; null and 0 for a reading kept
* by a version of the launcher that did not ask for them.
*/
data class Reading(
val degrees: Int,
val code: Int,
val fahrenheit: Boolean,
val readAt: Long,
val isDay: Boolean? = null,
val sunrise: Long = 0,
val sunset: Long = 0,
)
/** What the sky is doing, as the widget draws it ([WeatherIcon]) and names it. */
enum class Sky(@StringRes val word: Int) {
CLEAR(R.string.flexera_weather_clear),
MOSTLY_CLEAR(R.string.flexera_weather_mostly_clear),
PARTLY_CLOUDY(R.string.flexera_weather_partly_cloudy),
OVERCAST(R.string.flexera_weather_overcast),
FOG(R.string.flexera_weather_fog),
DRIZZLE(R.string.flexera_weather_drizzle),
FREEZING_RAIN(R.string.flexera_weather_freezing_rain),
RAIN(R.string.flexera_weather_rain),
SNOW(R.string.flexera_weather_snow),
SHOWERS(R.string.flexera_weather_showers),
SNOW_SHOWERS(R.string.flexera_weather_snow_showers),
THUNDERSTORM(R.string.flexera_weather_thunderstorm),
}
/** Told on the main thread that a new reading has come in. */
fun interface Listener {
fun onWeatherChanged()
}
private const val TAG = "ClockWeather"
private const val FILE = "flexera_clock_weather"
private const val FORECAST = "https://api.open-meteo.com/v1/forecast"
private const val SEARCH = "https://geocoding-api.open-meteo.com/v1/search"
private const val TIMEOUT_MS = 10_000
/** A reading younger than this is not asked for again. */
private const val FRESH_MS = 45 * 60 * 1000L
/**
* How long a place waits for its next try after a request for it failed. The wait doubles
* with each failure in a row, up to [RETRY_MAX_MS].
*/
private const val RETRY_MS = 5 * 60 * 1000L
/**
* The longest wait after failures. Tries made while the phone is offline, on a flight say,
* fail as well; with a short wait the weather is back soon once the phone is online again,
* and a service that cannot be reached is still asked only a few times an hour.
*/
private const val RETRY_MAX_MS = 15 * 60 * 1000L
/** A reading older than this is no longer shown: stale weather is worse than none. */
private const val SHOWN_MS = 3 * 60 * 60 * 1000L
/**
* When the last request for a place failed, on the [SystemClock.elapsedRealtime] clock, and
* how many failed in a row.
*/
private class Failure(val at: Long, val inARow: Int)
private val listeners = CopyOnWriteArraySet<Listener>()
private val asking = HashSet<String>()
/** The places whose last request failed. Guarded by [asking], like it. */
private val failures = HashMap<String, Failure>()
private val main = Handler(Looper.getMainLooper())
/**
* The last answer of [usesFahrenheit], and the locale it is for. Unless a unit is picked in the
* regional preferences, Android works it out from its tables of units, which it reads anew
* each time: too slow to repeat on the main thread at every return to the home screen.
*/
@Volatile
private var temperatureUnit: Pair<Locale, Boolean>? = null
fun addListener(listener: Listener) {
listeners.add(listener)
}
fun removeListener(listener: Listener) {
listeners.remove(listener)
}
/** The places of this name, the likeliest first. Asks the service; throws when it cannot. */
@WorkerThread
@Throws(IOException::class)
fun search(name: String): List<Place> {
// The language decides which names match, not only the names given back: without it,
// "Wien" does not find Vienna, and a name in Cyrillic finds nothing.
val language = Locale.getDefault().language.ifEmpty { "en" }
val answer = get("$SEARCH?name=${URLEncoder.encode(name, "UTF-8")}&count=6&language=$language&format=json")
// The service answered, so the places whose weather failed lately may be asked for again
// at once, such as the one the owner picks from these results.
synchronized(asking) { failures.clear() }
val results = JSONObject(answer).optJSONArray("results") ?: return emptyList()
return (0 until results.length()).map { index ->
val place = results.getJSONObject(index)
val detail = listOf(place.optString("admin1"), place.optString("country"))
.filter { it.isNotEmpty() }
.joinToString(", ")
Place(place.getString("name"), detail, place.getDouble("latitude"), place.getDouble("longitude"))
}
}
/** The last reading for a place, if there is one that is still worth showing. */
fun reading(context: Context, place: Place): Reading? {
val stored = prefs(context).getString(key(place), null)?.split('|') ?: return null
// Four parts were kept before the day and night were (1.0.3 and older).
if (stored.size != 4 && stored.size != 7) return null
val reading = Reading(
degrees = stored[0].toIntOrNull() ?: return null,
code = stored[1].toIntOrNull() ?: return null,
fahrenheit = stored[2] == "F",
readAt = stored[3].toLongOrNull() ?: return null,
isDay = stored.getOrNull(4)?.let { it == "1" },
sunrise = stored.getOrNull(5)?.toLongOrNull() ?: 0,
sunset = stored.getOrNull(6)?.toLongOrNull() ?: 0,
)
val age = System.currentTimeMillis() - reading.readAt
return if (age in 0..SHOWN_MS && reading.fahrenheit == usesFahrenheit()) reading else null
}
/**
* Asks for a new reading in the background, unless the last one is fresh, one is on its way,
* or the last request failed too recently to try again.
*/
fun refreshIfStale(context: Context, place: Place) {
val app = context.applicationContext
val key = key(place)
val last = reading(app, place)
if (last != null && System.currentTimeMillis() - last.readAt < FRESH_MS) return
synchronized(asking) {
// The widget asks at every return to the home screen. While the service cannot be
// reached, that would be a new request each time.
val failure = failures[key]
if (failure != null && SystemClock.elapsedRealtime() - failure.at < retryAfter(failure.inARow)) return
if (!asking.add(key)) return
}
Executors.THREAD_POOL_EXECUTOR.execute {
try {
val fahrenheit = usesFahrenheit()
// Today's sunrise and sunset let the icon turn from sun to moon on time between
// two requests. The service works out the place's time zone from its coordinates.
val answer = get(
"$FORECAST?latitude=${coordinate(place.latitude)}&longitude=${coordinate(place.longitude)}" +
"&current=temperature_2m,weather_code,is_day" +
"&daily=sunrise,sunset&forecast_days=1&timezone=auto&timeformat=unixtime" +
"&temperature_unit=${if (fahrenheit) "fahrenheit" else "celsius"}",
)
val json = JSONObject(answer)
val current = json.getJSONObject("current")
val degrees = current.getDouble("temperature_2m").roundToInt()
val code = current.getInt("weather_code")
val isDay = current.optInt("is_day", 1)
val daily = json.optJSONObject("daily")
val sunrise = daily?.optJSONArray("sunrise")?.optLong(0, 0) ?: 0
val sunset = daily?.optJSONArray("sunset")?.optLong(0, 0) ?: 0
val unit = if (fahrenheit) "F" else "C"
prefs(app).edit()
.putString(key, "$degrees|$code|$unit|${System.currentTimeMillis()}|$isDay|$sunrise|$sunset")
.apply()
synchronized(asking) { failures.remove(key) }
main.post { listeners.forEach { it.onWeatherChanged() } }
} catch (e: Exception) {
// Offline, or the service is down: the last reading stays until it is too old,
// and the next try waits (see RETRY_MS).
Log.w(TAG, "No weather this time", e)
synchronized(asking) {
failures[key] = Failure(SystemClock.elapsedRealtime(), (failures[key]?.inARow ?: 0) + 1)
}
} finally {
synchronized(asking) { asking.remove(key) }
}
}
}
/** The wait after [inARow] failed requests: [RETRY_MS], doubled for each after the first, up to [RETRY_MAX_MS]. */
private fun retryAfter(inARow: Int): Long =
(RETRY_MS shl (inARow - 1).coerceIn(0, 8)).coerceAtMost(RETRY_MAX_MS)
/** The line as the widget shows it, such as "6° · Overcast". */
fun line(context: Context, reading: Reading): String =
context.getString(R.string.flexera_weather_line, reading.degrees, context.getString(sky(reading.code).word))
/** The sky of a WMO weather code (the codes Open-Meteo uses). */
fun sky(code: Int): Sky = when (code) {
0 -> Sky.CLEAR
1 -> Sky.MOSTLY_CLEAR
2 -> Sky.PARTLY_CLOUDY
3 -> Sky.OVERCAST
45, 48 -> Sky.FOG
51, 53, 55 -> Sky.DRIZZLE
56, 57, 66, 67 -> Sky.FREEZING_RAIN
61, 63, 65 -> Sky.RAIN
71, 73, 75, 77 -> Sky.SNOW
80, 81, 82 -> Sky.SHOWERS
85, 86 -> Sky.SNOW_SHOWERS
95, 96, 99 -> Sky.THUNDERSTORM
else -> Sky.OVERCAST
}
/**
* Whether the sun is down at the reading's place at [now] (milliseconds since 1970). The
* sunrise and sunset of the day it was read are moved on by whole days, so that a reading
* from yesterday evening still knows this morning's sunrise, to within a few minutes.
* Where the sun does not rise or set that day, as near the poles, it is what the service
* said when asked; for an old reading without either, a guess from the phone's clock.
*/
fun isNight(reading: Reading, now: Long): Boolean {
val rise = reading.sunrise
val set = reading.sunset
if (rise > 0 && set > rise && set - rise < DAY_S) {
val seconds = now / 1000
val days = Math.floorDiv(seconds - rise, DAY_S)
return seconds - days * DAY_S >= set
}
reading.isDay?.let { return !it }
val hour = Calendar.getInstance().apply { timeInMillis = now }.get(Calendar.HOUR_OF_DAY)
return hour < 6 || hour >= 20
}
private const val DAY_S = 24 * 60 * 60L
/**
* True when the phone counts degrees in Fahrenheit: the unit the owner picked under Android's
* regional preferences (Android 14 and newer), or else the one usual where the phone's
* language is from, such as the United States for American English.
*/
private fun usesFahrenheit(): Boolean {
// The locale LocalePreferences would read by itself. A unit picked in the regional
// preferences is part of it, so a new choice is a new locale.
val locale = Locale.getDefault(Locale.Category.FORMAT)
val known = temperatureUnit
if (known != null && known.first == locale) return known.second
val fahrenheit = LocalePreferences.getTemperatureUnit(locale) == LocalePreferences.TemperatureUnit.FAHRENHEIT
temperatureUnit = locale to fahrenheit
return fahrenheit
}
/** Two decimals, about a kilometre: all a forecast needs, and no more exact than that. */
private fun coordinate(value: Double): String = String.format(Locale.ROOT, "%.2f", value)
private fun key(place: Place): String = "${coordinate(place.latitude)},${coordinate(place.longitude)}"
private fun prefs(context: Context) =
context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)
private fun get(address: String): String {
val connection = URL(address).openConnection() as HttpURLConnection
try {
connection.connectTimeout = TIMEOUT_MS
connection.readTimeout = TIMEOUT_MS
connection.setRequestProperty("Accept", "application/json")
// Android's own User-Agent would tell the service the phone's model and its exact
// Android build. This one names only the app.
connection.setRequestProperty("User-Agent", "FlexeraLauncher")
if (connection.responseCode != HttpURLConnection.HTTP_OK) {
throw IOException("The weather service answered HTTP ${connection.responseCode}")
}
return connection.inputStream.bufferedReader().use { it.readText() }
} finally {
connection.disconnect()
}
}
}
@@ -0,0 +1,847 @@
package app.flexera.widget
import android.app.Activity
import android.app.WallpaperManager
import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.pm.LauncherActivityInfo
import android.content.pm.LauncherApps
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.os.Process
import android.provider.AlarmClock
import android.text.TextPaint
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.annotation.StringRes
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import app.flexera.widget.ClockWidgetStore.Align
import app.flexera.widget.ClockWidgetStore.Font
import app.flexera.widget.ClockWidgetStore.Icon
import app.flexera.widget.ClockWidgetStore.TapApp
import app.flexera.widget.ClockWidgetStore.Weight
import app.lawnchair.gestures.config.GestureHandlerConfig
import app.lawnchair.gestures.config.GestureHandlerOption
import app.lawnchair.gestures.handlers.OpenAppTarget
import app.lawnchair.ui.theme.EdgeToEdge
import app.lawnchair.ui.theme.LawnchairTheme
import app.lawnchair.util.App
import com.android.launcher3.R
import com.android.launcher3.model.data.AppInfo
import com.android.launcher3.util.ComponentKey
import com.android.launcher3.util.Executors.MODEL_EXECUTOR
import java.util.TimeZone
import kotlin.math.min
import kotlin.math.roundToInt
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* The clock widget's options: how large its figures are, in which font and how heavy, where its
* text stands, the place its weather line is for and how its weather icon is drawn, and the apps
* a tap on the time or on the weather opens. Reached from the widget's edit button. It is a sheet
* over the home screen with a preview of the clock at its top, which stays in view while the
* options scroll under it. Every choice shows in the preview and on the widget at once; closing
* the sheet is all there is to finishing.
*/
class ClockWidgetConfigActivity : ComponentActivity() {
@OptIn(ExperimentalMaterial3Api::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
val widget = intent?.getIntExtra(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID,
) ?: AppWidgetManager.INVALID_APPWIDGET_ID
if (widget == AppWidgetManager.INVALID_APPWIDGET_ID) {
setResult(RESULT_CANCELED)
finish()
return
}
// The widget is fine with or without a visit here.
setResult(RESULT_OK, Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widget))
setContent {
LawnchairTheme {
EdgeToEdge()
var options by remember { mutableStateOf(ClockWidgetStore.options(this, widget)) }
val change = { changed: ClockWidgetStore.Options ->
options = changed
ClockWidgetStore.set(this, widget, changed)
}
// The largest figures this widget has room for, as the preview finds it.
var largest by remember { mutableFloatStateOf(ClockWidgetStore.MAX_SCALE) }
ModalBottomSheet(
onDismissRequest = { finish() },
sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true),
containerColor = MaterialTheme.colorScheme.surface,
// No dimming: what shows of the home screen above the sheet stays as it is.
scrimColor = Color.Transparent,
) {
Column(modifier = Modifier.fillMaxWidth()) {
Column(modifier = Modifier.padding(horizontal = 24.dp)) {
Text(
text = stringResource(id = R.string.flexera_clock_widget),
style = MaterialTheme.typography.titleLarge,
)
Spacer(modifier = Modifier.height(16.dp))
ClockPreview(widget = widget, options = options, onLargest = { largest = it })
}
// The options scroll under the preview; a line marks the edge while they do.
val scroll = rememberScrollState()
Spacer(modifier = Modifier.height(12.dp))
HorizontalDivider(
color = if (scroll.value > 0) MaterialTheme.colorScheme.outlineVariant else Color.Transparent,
)
Column(
modifier = Modifier
.weight(1f, fill = false)
.verticalScroll(scroll)
.imePadding()
.padding(start = 24.dp, end = 24.dp, top = 12.dp, bottom = 32.dp),
) {
SizeChoice(
scale = options.scale,
largest = largest,
onChange = { change(options.copy(scale = it)) },
)
Spacer(modifier = Modifier.height(20.dp))
FontChoice(
chosen = options.font,
weight = options.weight,
onChoose = { change(options.copy(font = it)) },
)
Spacer(modifier = Modifier.height(20.dp))
Choice(
heading = R.string.flexera_clock_widget_weight,
choices = listOf(
Weight.THIN to R.string.flexera_clock_widget_thin,
Weight.LIGHT to R.string.flexera_clock_widget_light,
Weight.REGULAR to R.string.flexera_clock_widget_regular,
Weight.BOLD to R.string.flexera_clock_widget_bold,
),
chosen = options.weight,
onChoose = { change(options.copy(weight = it)) },
)
Spacer(modifier = Modifier.height(20.dp))
Choice(
heading = R.string.flexera_clock_widget_alignment,
choices = listOf(
Align.LEFT to R.string.flexera_clock_widget_left,
Align.CENTER to R.string.flexera_clock_widget_center,
Align.RIGHT to R.string.flexera_clock_widget_right,
),
chosen = options.align,
onChoose = { change(options.copy(align = it)) },
sides = true,
)
Spacer(modifier = Modifier.height(20.dp))
WeatherChoice(
place = options.weather,
onChoose = { change(options.copy(weather = it)) },
icon = options.icon,
onChooseIcon = { change(options.copy(icon = it)) },
)
Spacer(modifier = Modifier.height(24.dp))
TapChoices(
options = options,
onClockTap = { change(options.copy(clockTap = it)) },
onWeatherTap = { change(options.copy(weatherTap = it)) },
)
}
}
}
}
}
}
}
/**
* The clock as it is on the home screen, with the options being chosen: the widget's own view,
* laid out at the widget's size and scaled to fit, on the colours of the wallpaper. Tells
* [onLargest] the largest figures the widget has room for.
*/
@Composable
private fun ClockPreview(widget: Int, options: ClockWidgetStore.Options, onLargest: (Float) -> Unit) {
val look = remember(widget) { ClockLooks[widget] }
val density = LocalDensity.current
val textColor = look?.textColor ?: android.graphics.Color.WHITE
val backdrop = previewBackdrop(textColor)
BoxWithConstraints(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
// Around the clock's own area, a margin of the backdrop: at its largest the clock fills its
// cells to their edges, which the card's edge would otherwise cut.
val margin = with(density) { PreviewMargin.toPx() }
val width = look?.width?.toFloat() ?: (constraints.maxWidth - 2 * margin)
val height = look?.height?.toFloat() ?: with(density) { PreviewFallbackHeight.toPx() }
val tallest = with(density) { PreviewMaxHeight.toPx() }
val fit = min(1f, min((constraints.maxWidth - 2 * margin) / width, (tallest - 2 * margin) / height))
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.size(
with(density) { (width * fit + 2 * margin).toDp() },
with(density) { (height * fit + 2 * margin).toDp() },
)
.clip(RoundedCornerShape(24.dp))
.background(backdrop),
) {
AndroidView(
factory = { ClockWidgetView(it) },
update = {
it.onLargestScale = onLargest
it.preview(widget, options)
},
modifier = Modifier
.requiredSize(with(density) { width.toDp() }, with(density) { height.toDp() })
.graphicsLayer {
scaleX = fit
scaleY = fit
},
)
}
}
}
/**
* What the preview stands on: the main colours of the wallpaper, toned down towards black under
* light text and towards white under dark text, so that the text reads as it does at home.
*/
@Composable
private fun previewBackdrop(textColor: Int): Brush {
val context = LocalContext.current
val colors = remember {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
runCatching { WallpaperManager.getInstance(context).getWallpaperColors(WallpaperManager.FLAG_SYSTEM) }.getOrNull()
} else {
null
}
}
val lightText = Color(textColor).luminance() > 0.5f
val toward = if (lightText) Color.Black else Color.White
val primary = colors?.primaryColor?.toArgb()
val shades = if (primary == null) {
if (lightText) listOf(Color(0xFF2B3040), Color(0xFF1B1E28)) else listOf(Color(0xFFF1F3F8), Color(0xFFDDE2EC))
} else {
listOf(Color(primary), Color(colors.secondaryColor?.toArgb() ?: primary))
}
return Brush.verticalGradient(shades.map { lerp(it, toward, BACKDROP_TONE) })
}
/**
* The size of the figures: a slider from small to large, in proportion to the icons. Its top is
* as large as the widget has room for ([largest]); when that is less than the largest size, a
* note says how to get more.
*/
@Composable
private fun SizeChoice(scale: Float, largest: Float, onChange: (Float) -> Unit) {
Heading(R.string.flexera_clock_widget_size)
val top = largest.coerceIn(ClockWidgetStore.MIN_SCALE + MIN_SLIDER_SPAN, ClockWidgetStore.MAX_SCALE)
val shown = scale.coerceIn(ClockWidgetStore.MIN_SCALE, top)
val state = stringResource(id = R.string.flexera_clock_widget_size_value, (shown * 100).roundToInt())
Slider(
value = shown,
onValueChange = { onChange((it * 100).roundToInt() / 100f) },
valueRange = ClockWidgetStore.MIN_SCALE..top,
modifier = Modifier.semantics { stateDescription = state },
)
Row(modifier = Modifier.fillMaxWidth()) {
Text(
text = stringResource(id = R.string.flexera_clock_widget_small),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(modifier = Modifier.weight(1f))
Text(
text = stringResource(id = R.string.flexera_clock_widget_large),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (largest < ClockWidgetStore.MAX_SCALE) {
Spacer(modifier = Modifier.height(8.dp))
Text(
text = stringResource(id = R.string.flexera_clock_widget_size_limit),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
/**
* The font of the figures: a row of cards, each with a sample in that font at the chosen
* [weight], drawn by the same code as the clock (ClockFonts), so that it shows what the clock
* will look like. The row scrolls sideways where it does not fit.
*/
@Composable
private fun FontChoice(chosen: Font, weight: Weight, onChoose: (Font) -> Unit) {
Heading(R.string.flexera_clock_widget_font)
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier
.fillMaxWidth()
.horizontalScroll(rememberScrollState())
.selectableGroup(),
) {
Fonts.forEach { (font, label) ->
val selected = font == chosen
val shape = RoundedCornerShape(16.dp)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.width(76.dp)
.clip(shape)
.background(
if (selected) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.surfaceContainerHigh,
)
.border(
width = if (selected) 2.dp else 1.dp,
color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outlineVariant,
shape = shape,
)
.selectable(selected = selected, onClick = { onChoose(font) }, role = Role.RadioButton)
.padding(vertical = 10.dp),
) {
FontSample(
font = font,
weight = weight,
color = if (selected) MaterialTheme.colorScheme.onSecondaryContainer else MaterialTheme.colorScheme.onSurface,
modifier = Modifier
.fillMaxWidth()
.height(44.dp),
)
Text(
text = stringResource(id = label),
style = MaterialTheme.typography.labelMedium,
color = if (selected) MaterialTheme.colorScheme.onSecondaryContainer else MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
)
}
}
}
}
/** [FontSampleText] in [font] at [weight], in the middle of its box. */
@Composable
private fun FontSample(font: Font, weight: Weight, color: Color, modifier: Modifier) {
val context = LocalContext.current
val paint = remember(font, weight) {
TextPaint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply {
ClockFonts.apply(context, this, font, weight.value)
textAlign = android.graphics.Paint.Align.CENTER
}
}
val ink = remember { android.graphics.Rect() }
Canvas(modifier = modifier) {
paint.color = color.toArgb()
paint.textSize = FontSampleSize.toPx()
paint.getTextBounds(FontSampleText, 0, FontSampleText.length, ink)
drawIntoCanvas {
it.nativeCanvas.drawText(FontSampleText, size.width / 2f, size.height / 2f - ink.exactCenterY(), paint)
}
}
}
@Composable
private fun Heading(@StringRes text: Int) {
Text(
text = stringResource(id = text),
style = MaterialTheme.typography.labelLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Spacer(modifier = Modifier.height(8.dp))
}
/**
* A heading with one row of choices under it, of which one is taken. When a label does not fit
* its segment, as at large font sizes, the choices are a list instead, one to a line.
*
* Choices that are [sides] of the widget are not a reading order: their row stays left to right
* in right-to-left languages too, so that Left is on the left.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun <T> Choice(
@StringRes heading: Int,
choices: List<Pair<T, Int>>,
chosen: T,
onChoose: (T) -> Unit,
sides: Boolean = false,
) {
Heading(heading)
val labels = choices.map { (_, label) -> stringResource(id = label) }
BoxWithConstraints(modifier = Modifier.fillMaxWidth()) {
if (fitInSegments(labels, maxWidth)) {
val direction = if (sides) LayoutDirection.Ltr else LocalLayoutDirection.current
CompositionLocalProvider(LocalLayoutDirection provides direction) {
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
choices.forEachIndexed { index, (value, _) ->
SegmentedButton(
selected = value == chosen,
onClick = { onChoose(value) },
shape = SegmentedButtonDefaults.itemShape(index = index, count = choices.size),
) {
Text(text = labels[index], maxLines = 1)
}
}
}
}
} else {
Column(modifier = Modifier.selectableGroup()) {
choices.forEachIndexed { index, (value, _) ->
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 48.dp)
.selectable(
selected = value == chosen,
onClick = { onChoose(value) },
role = Role.RadioButton,
),
) {
RadioButton(selected = value == chosen, onClick = null)
Spacer(modifier = Modifier.width(12.dp))
Text(text = labels[index], style = MaterialTheme.typography.bodyLarge)
}
}
}
}
}
}
/**
* True when every label fits its segment of a row [width] wide, beside the check mark the chosen
* one carries. Material measures a label against all the room in its segment and then adds the
* check mark beside it, so a word that is too long is broken mid-word ("Regul") or runs into the
* border.
*/
@Composable
private fun fitInSegments(labels: List<String>, width: Dp): Boolean {
val measurer = rememberTextMeasurer()
val style = MaterialTheme.typography.labelLarge
val room = with(LocalDensity.current) { (width / labels.size - CheckMarkRoom).toPx() }
return labels.all { measurer.measure(it, style, softWrap = false, maxLines = 1).size.width <= room }
}
/**
* The tallest the preview is drawn, its height while the clock's own is not known, and the
* margin around the clock in it.
*/
private val PreviewMaxHeight = 220.dp
private val PreviewFallbackHeight = 160.dp
private val PreviewMargin = 12.dp
/** The fonts to pick from, each with its name. */
private val Fonts = listOf(
Font.DEFAULT to R.string.flexera_clock_widget_font_default,
Font.FLEX to R.string.flexera_clock_widget_font_flex,
Font.NARROW to R.string.flexera_clock_widget_font_narrow,
Font.WIDE to R.string.flexera_clock_widget_font_wide,
Font.SERIF to R.string.flexera_clock_widget_font_serif,
Font.MONO to R.string.flexera_clock_widget_font_mono,
)
/** The text of each font's sample, and its size. */
private const val FontSampleText = "12"
private val FontSampleSize = 30.sp
/** How far the wallpaper's colours are toned down behind the preview. */
private const val BACKDROP_TONE = 0.35f
/** The least the size slider spans, for a widget with room for little more than the smallest figures. */
private const val MIN_SLIDER_SPAN = 0.05f
/** What a chosen segment keeps beside its label: the check mark, the space after it, and its two borders. */
private val CheckMarkRoom = SegmentedButtonDefaults.IconSize + 10.dp
private enum class Search { IDLE, RUNNING, NOTHING, FAILED }
/**
* The weather line: off until the owner looks a place up by name and picks it from what the
* weather service finds. The field starts with the city of the phone's time zone as a guess.
*/
@Composable
private fun WeatherChoice(
place: ClockWeather.Place?,
onChoose: (ClockWeather.Place?) -> Unit,
icon: Icon,
onChooseIcon: (Icon) -> Unit,
) {
val scope = rememberCoroutineScope()
var name by rememberSaveable { mutableStateOf(place?.name ?: timeZoneCity()) }
var found by remember { mutableStateOf(emptyList<ClockWeather.Place>()) }
var search by remember { mutableStateOf(Search.IDLE) }
var searches by remember { mutableIntStateOf(0) }
val keyboard = LocalSoftwareKeyboardController.current
val focus = LocalFocusManager.current
val look = {
val wanted = name.trim()
if (wanted.isNotEmpty() && search != Search.RUNNING) {
// The places found are listed under the field, where the keyboard would cover them.
keyboard?.hide()
focus.clearFocus()
search = Search.RUNNING
searches++
scope.launch {
val result = withContext(Dispatchers.IO) { runCatching { ClockWeather.search(wanted) } }
found = result.getOrDefault(emptyList())
search = when {
result.isFailure -> Search.FAILED
found.isEmpty() -> Search.NOTHING
else -> Search.IDLE
}
}
}
}
Heading(R.string.flexera_clock_widget_weather)
Text(
text = if (place == null) {
stringResource(id = R.string.flexera_clock_widget_weather_off)
} else {
stringResource(id = R.string.flexera_clock_widget_weather_on, placeLabel(place))
},
style = MaterialTheme.typography.bodyMedium,
)
Spacer(modifier = Modifier.height(12.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
OutlinedTextField(
value = name,
onValueChange = { name = it },
label = { Text(text = stringResource(id = R.string.flexera_clock_widget_weather_place)) },
singleLine = true,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
keyboardActions = KeyboardActions(onSearch = { look() }),
modifier = Modifier.weight(1f),
)
Spacer(modifier = Modifier.width(12.dp))
Button(onClick = { look() }) {
Text(text = stringResource(id = R.string.flexera_clock_widget_weather_search))
}
}
// Each search gets a new note, which TalkBack reads out, also when it says what the last one
// did: offline, a search can fail before the progress bar is ever drawn, and the note that
// stayed would not be read again.
key(searches) {
when (search) {
Search.RUNNING -> LinearProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.padding(top = 12.dp),
)
Search.NOTHING -> Note(stringResource(id = R.string.flexera_clock_widget_weather_nothing))
Search.FAILED -> Note(stringResource(id = R.string.flexera_clock_widget_weather_failed))
Search.IDLE -> if (found.isNotEmpty()) {
Note(pluralStringResource(id = R.plurals.flexera_clock_widget_weather_found, count = found.size, found.size))
}
}
}
found.forEach { candidate ->
Text(
text = placeLabel(candidate),
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier
.fillMaxWidth()
.clickable {
onChoose(candidate)
name = candidate.name
found = emptyList()
}
.padding(vertical = 14.dp),
)
}
if (place != null) {
TextButton(onClick = { onChoose(null) }) {
Text(text = stringResource(id = R.string.flexera_clock_widget_weather_remove))
}
Spacer(modifier = Modifier.height(12.dp))
Choice(
heading = R.string.flexera_clock_widget_weather_icon,
choices = listOf(
Icon.COLOR to R.string.flexera_clock_widget_icon_color,
Icon.PLAIN to R.string.flexera_clock_widget_icon_plain,
Icon.NONE to R.string.flexera_clock_widget_icon_none,
),
chosen = icon,
onChoose = onChooseIcon,
)
Spacer(modifier = Modifier.height(12.dp))
}
Spacer(modifier = Modifier.height(8.dp))
Text(
text = stringResource(id = R.string.flexera_clock_widget_weather_source),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
/**
* How a search went, under the search field. TalkBack reads it out as it appears: the answer
* comes a moment after the owner asked, and nothing else would say that it is there.
*/
@Composable
private fun Note(text: String) {
Text(
text = text,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier
.padding(top = 12.dp)
.semantics { liveRegion = LiveRegionMode.Polite },
)
}
/**
* Which app a tap on the time and date opens, and which one a tap on the weather opens; the
* second only while there is a weather line. Each opens the launcher's own list of apps, as the
* Quick launch choices do, and can be put back to what it was.
*/
@Composable
private fun TapChoices(
options: ClockWidgetStore.Options,
onClockTap: (TapApp?) -> Unit,
onWeatherTap: (TapApp?) -> Unit,
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val pick = { onPicked: (TapApp) -> Unit ->
scope.launch {
val activity = context.findActivity() ?: return@launch
val config = GestureHandlerOption.OpenApp.buildConfig(activity) as? GestureHandlerConfig.OpenApp
val target = config?.target as? OpenAppTarget.App ?: return@launch
onPicked(TapApp(target.key, config.appName))
}
Unit
}
// What a tap on the time opens when nothing is picked: the phone's clock app.
val clockApp by produceState<ComponentKey?>(initialValue = null) {
value = withContext(Dispatchers.IO) { defaultClockApp(context) }
}
Heading(R.string.flexera_clock_widget_tap)
TapChoice(
title = stringResource(id = R.string.flexera_clock_widget_tap_clock),
chosen = options.clockTap,
fallback = clockApp,
fallbackText = stringResource(id = R.string.flexera_clock_widget_tap_clock_default),
onPick = { pick(onClockTap) },
onReset = { onClockTap(null) },
)
if (options.weather != null) {
TapChoice(
title = stringResource(id = R.string.flexera_clock_widget_tap_weather),
chosen = options.weatherTap,
fallback = options.clockTap?.key ?: clockApp,
fallbackText = stringResource(id = R.string.flexera_clock_widget_tap_weather_default),
onPick = { pick(onWeatherTap) },
onReset = { onWeatherTap(null) },
)
}
}
/**
* One tap choice: what it is for, the app it opens with that app's icon, and Reset once an app
* is picked. Without one it opens [fallback], described as [fallbackText].
*/
@Composable
private fun TapChoice(
title: String,
chosen: TapApp?,
fallback: ComponentKey?,
fallbackText: String,
onPick: () -> Unit,
onReset: () -> Unit,
) {
val context = LocalContext.current
val shown = chosen?.key ?: fallback
// The app's name and its icon as the launcher draws it, with the icon pack and shape; null
// while they are looked up.
val found by produceState<Found?>(initialValue = null, shown) {
value = shown?.let { key ->
withContext(MODEL_EXECUTOR.asCoroutineDispatcher()) {
resolve(context, key)?.let { info -> Found(info.label.toString(), App(context, info).icon) } ?: Found.MISSING
}
}
}
val value = when {
chosen == null -> fallbackText
found === Found.MISSING -> stringResource(id = R.string.flexera_clock_widget_tap_missing, chosen.name)
else -> chosen.name.ifEmpty { found?.label.orEmpty() }
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 64.dp)
.clickable(onClick = onPick, role = Role.Button)
.padding(vertical = 8.dp),
) {
val icon = found?.icon
if (icon != null) {
Image(
bitmap = icon.asImageBitmap(),
contentDescription = null,
modifier = Modifier.size(36.dp),
)
} else {
Spacer(modifier = Modifier.size(36.dp))
}
Spacer(modifier = Modifier.width(16.dp))
Column(modifier = Modifier.weight(1f)) {
Text(text = title, style = MaterialTheme.typography.bodyLarge)
Text(
text = value,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
if (chosen != null) {
val description = stringResource(id = R.string.flexera_clock_widget_tap_reset_description, title)
TextButton(
onClick = onReset,
modifier = Modifier.semantics { contentDescription = description },
) {
Text(text = stringResource(id = R.string.flexera_clock_widget_tap_reset))
}
}
}
}
/** The launcher's view of [key]'s app, or null when it is not installed or not enabled. */
private fun resolve(context: Context, key: ComponentKey): LauncherActivityInfo? = try {
context.getSystemService(LauncherApps::class.java)
?.resolveActivity(AppInfo.makeLaunchIntent(key.componentName), key.user)
} catch (e: RuntimeException) {
// A work profile that is paused, or the app is gone.
null
}
/** A tap choice's app as found on the phone: its name and icon, or [MISSING]. */
private class Found(val label: String, val icon: Bitmap?) {
companion object {
/** No longer installed, or disabled. */
val MISSING = Found("", null)
}
}
/** The app the widget opens by itself: the one that shows the alarms, found as ClockWidgetView finds it. */
private fun defaultClockApp(context: Context): ComponentKey? {
val pm = context.packageManager
val clockApp = pm.resolveActivity(Intent(AlarmClock.ACTION_SHOW_ALARMS), 0)?.activityInfo?.packageName ?: return null
val component = pm.getLaunchIntentForPackage(clockApp)?.component ?: return null
return ComponentKey(component, Process.myUserHandle())
}
private fun Context.findActivity(): Activity? {
var current: Context? = this
while (current != null) {
if (current is Activity) return current
current = (current as? ContextWrapper)?.baseContext
}
return null
}
private fun placeLabel(place: ClockWeather.Place): String =
if (place.detail.isEmpty()) place.name else "${place.name}, ${place.detail}"
/** The city a time zone is named after ("Europe/Zagreb" gives "Zagreb"); empty for zones without one. */
private fun timeZoneCity(): String {
val id = TimeZone.getDefault().id
return if ('/' in id) id.substringAfterLast('/').replace('_', ' ') else ""
}
@@ -0,0 +1,68 @@
package app.flexera.widget
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.util.Log
import com.android.launcher3.BuildConfig
import com.android.launcher3.model.data.LauncherAppWidgetInfo
/**
* The launcher's own clock widget: the time, large, with the date under it. Android knows it as
* an ordinary app widget; the launcher draws it itself with a [ClockWidgetView]. It needs no
* setting up; what the owner may choose for it is kept in [ClockWidgetStore], under the
* widget's id, and goes with the widget when a restore gives it a new one. See [FlexeraWidgets].
*/
class ClockWidgetProvider : AppWidgetProvider() {
override fun onDeleted(context: Context, appWidgetIds: IntArray) {
appWidgetIds.forEach { ClockWidgetStore.delete(context, it) }
}
/** After Android's own restore. */
override fun onRestored(context: Context, oldWidgetIds: IntArray, newWidgetIds: IntArray) {
ClockWidgetStore.move(context, oldWidgetIds, newWidgetIds)
}
companion object {
private const val TAG = "ClockWidgetProvider"
@JvmField
val componentName = ComponentName(BuildConfig.APPLICATION_ID, ClockWidgetProvider::class.java.name)
/**
* Told by Launcher3 (WidgetInflater) that a widget of the home screen got a new id
* because the one it had is no longer valid, as after a restore of the launcher's
* backup; [oldAppWidgetId] is the id it had. Android's onRestored does not come in that
* case, and Launcher3 deletes the old id after the home screens are loaded, so the
* clock's options go to the new id first, before onDeleted would forget them.
*/
@JvmStatic
fun onNewAppWidgetId(context: Context, item: LauncherAppWidgetInfo, oldAppWidgetId: Int) {
val newId = item.appWidgetId
if (item.providerName != componentName || oldAppWidgetId <= 0 || newId <= 0) return
try {
ClockWidgetStore.move(context, intArrayOf(oldAppWidgetId), intArrayOf(newId))
} catch (e: RuntimeException) {
// Never in the way of loading the home screens.
Log.w(TAG, "Options not handed to widget $newId", e)
}
}
/**
* Told by Launcher3 (LauncherWidgetHolder) that it deleted a widget id, of any widget.
* Android calls onDeleted only for an id that was bound, and a clock removed while it
* waited for "tap to set up" may have options under an id that was not
* ([onNewAppWidgetId]); they go with it. For another widget's id there is nothing to remove.
*/
@JvmStatic
fun onAppWidgetIdDeleted(context: Context, appWidgetId: Int) {
if (appWidgetId <= 0) return
try {
ClockWidgetStore.delete(context, appWidgetId)
} catch (e: RuntimeException) {
Log.w(TAG, "Options of widget $appWidgetId not removed", e)
}
}
}
}
@@ -0,0 +1,228 @@
package app.flexera.widget
import android.content.Context
import android.content.SharedPreferences
import android.os.Handler
import android.os.Looper
import com.android.launcher3.util.ComponentKey
import java.util.concurrent.CopyOnWriteArraySet
/**
* What the owner has chosen for each clock widget on the home screen: where its text stands, how
* large and how heavy its figures are and in which font, the place its weather line is for, if it has one, how its
* weather icon is drawn, and the apps a tap on the time or on the weather opens. Kept per widget,
* so that two clocks can differ.
*/
object ClockWidgetStore {
/** Which side of the widget the time and the date stand on. */
enum class Align(val key: String) { LEFT("left"), CENTER("center"), RIGHT("right") }
/** The face of the figures (see ClockFonts): the phone's own font, or one of five others. */
enum class Font(val key: String) {
DEFAULT("default"),
FLEX("flex"),
NARROW("narrow"),
WIDE("wide"),
SERIF("serif"),
MONO("mono"),
}
/** How heavy the figures are drawn; [value] is the font weight, from 100 to 900. */
enum class Weight(val key: String, val value: Int) {
THIN("thin", 100),
LIGHT("light", 300),
REGULAR("regular", 400),
BOLD("bold", 700),
}
/** How the picture beside the weather line is drawn ([WeatherIcon]), or that there is none. */
enum class Icon(val key: String) { COLOR("color"), PLAIN("plain"), NONE("none") }
/** An app the owner picked for a tap, with its name as it was when picked. */
data class TapApp(val key: ComponentKey, val name: String)
data class Options(
val align: Align = Align.LEFT,
/**
* How tall the figures are, in heights of what is seen of an icon, from [MIN_SCALE] to
* [MAX_SCALE]. The widget's own size is the limit (see ClockWidgetView).
*/
val scale: Float = DEFAULT_SCALE,
val weight: Weight = Weight.LIGHT,
val font: Font = Font.DEFAULT,
/** The place of the weather line; null for a clock without weather, which is how it starts. */
val weather: ClockWeather.Place? = null,
val icon: Icon = Icon.COLOR,
/** What a tap on the time and the date opens; null for the phone's clock app. */
val clockTap: TapApp? = null,
/** What a tap on the weather opens; null for the same as a tap on the time. */
val weatherTap: TapApp? = null,
)
/** Told, on the thread that made the change, that a widget's options are different now. */
fun interface Listener {
fun onClockOptionsChanged(appWidgetId: Int)
}
private val listeners = CopyOnWriteArraySet<Listener>()
fun addListener(listener: Listener) {
listeners.add(listener)
}
fun removeListener(listener: Listener) {
listeners.remove(listener)
}
fun options(context: Context, appWidgetId: Int): Options {
val prefs = prefs(context)
val align = prefs.getString(ALIGN + appWidgetId, null)
val weight = prefs.getString(WEIGHT + appWidgetId, null)
val font = prefs.getString(FONT + appWidgetId, null)
val place = prefs.getString(PLACE + appWidgetId, null)
val icon = prefs.getString(ICON + appWidgetId, null)
return Options(
align = Align.entries.firstOrNull { it.key == align } ?: Align.LEFT,
scale = scale(prefs, appWidgetId),
weight = Weight.entries.firstOrNull { it.key == weight } ?: Weight.LIGHT,
font = Font.entries.firstOrNull { it.key == font } ?: Font.DEFAULT,
weather = place?.let {
ClockWeather.Place(
name = it,
detail = prefs.getString(PLACE_DETAIL + appWidgetId, "").orEmpty(),
latitude = prefs.getFloat(LATITUDE + appWidgetId, 0f).toDouble(),
longitude = prefs.getFloat(LONGITUDE + appWidgetId, 0f).toDouble(),
)
},
icon = Icon.entries.firstOrNull { it.key == icon } ?: Icon.COLOR,
clockTap = tapApp(prefs, CLOCK_APP, CLOCK_APP_NAME, appWidgetId),
weatherTap = tapApp(prefs, WEATHER_APP, WEATHER_APP_NAME, appWidgetId),
)
}
/**
* The figures' height of a widget. Until 1.0.3 there were three sizes to pick from; a clock
* set to one of them keeps it.
*/
private fun scale(prefs: SharedPreferences, appWidgetId: Int): Float {
if (prefs.contains(SCALE + appWidgetId)) {
return prefs.getFloat(SCALE + appWidgetId, DEFAULT_SCALE).coerceIn(MIN_SCALE, MAX_SCALE)
}
return when (prefs.getString(SIZE + appWidgetId, null)) {
"small" -> 0.5f
"large" -> 1.25f
else -> DEFAULT_SCALE
}
}
private fun tapApp(prefs: SharedPreferences, appKey: String, nameKey: String, appWidgetId: Int): TapApp? {
val key = prefs.getString(appKey + appWidgetId, null)?.let(ComponentKey::fromString) ?: return null
return TapApp(key, prefs.getString(nameKey + appWidgetId, null).orEmpty())
}
private fun putTapApp(edit: SharedPreferences.Editor, app: TapApp?, appKey: String, nameKey: String, appWidgetId: Int) {
if (app == null) {
edit.remove(appKey + appWidgetId).remove(nameKey + appWidgetId)
} else {
edit.putString(appKey + appWidgetId, app.key.toString()).putString(nameKey + appWidgetId, app.name)
}
}
fun set(context: Context, appWidgetId: Int, options: Options) {
val edit = prefs(context).edit()
.putString(ALIGN + appWidgetId, options.align.key)
.putFloat(SCALE + appWidgetId, options.scale.coerceIn(MIN_SCALE, MAX_SCALE))
.remove(SIZE + appWidgetId)
.putString(WEIGHT + appWidgetId, options.weight.key)
.putString(FONT + appWidgetId, options.font.key)
.putString(ICON + appWidgetId, options.icon.key)
putTapApp(edit, options.clockTap, CLOCK_APP, CLOCK_APP_NAME, appWidgetId)
putTapApp(edit, options.weatherTap, WEATHER_APP, WEATHER_APP_NAME, appWidgetId)
val place = options.weather
if (place == null) {
edit.remove(PLACE + appWidgetId).remove(PLACE_DETAIL + appWidgetId)
.remove(LATITUDE + appWidgetId).remove(LONGITUDE + appWidgetId)
} else {
edit.putString(PLACE + appWidgetId, place.name)
.putString(PLACE_DETAIL + appWidgetId, place.detail)
.putFloat(LATITUDE + appWidgetId, place.latitude.toFloat())
.putFloat(LONGITUDE + appWidgetId, place.longitude.toFloat())
}
edit.apply()
listeners.forEach { it.onClockOptionsChanged(appWidgetId) }
}
/** Forgets the options of a widget that left the home screen. */
fun delete(context: Context, appWidgetId: Int) {
val edit = prefs(context).edit()
for (key in KEYS) {
edit.remove(key + appWidgetId)
}
edit.apply()
}
/**
* Hands the options of each widget in [from] to the widget at the same place in [to]: the
* ids that a restore gave the widgets in place of the ones they had. May be called on any
* thread; listeners are told on the main thread.
*/
fun move(context: Context, from: IntArray, to: IntArray) {
val prefs = prefs(context)
val before = prefs.all
val edit = prefs.edit()
// The old ids are all cleared before the new ones are written, in one change, so that an
// id that is one widget's old id and another's new one ends up with the right options.
for (oldId in from) {
for (key in KEYS) edit.remove(key + oldId)
}
val moved = ArrayList<Int>()
for (i in from.indices) {
val newId = to.getOrNull(i) ?: continue
for (key in KEYS) {
when (val value = before[key + from[i]]) {
is String -> edit.putString(key + newId, value)
is Float -> edit.putFloat(key + newId, value)
else -> edit.remove(key + newId)
}
}
moved.add(newId)
}
edit.apply()
mainHandler.post { moved.forEach { id -> listeners.forEach { it.onClockOptionsChanged(id) } } }
}
private fun prefs(context: Context): SharedPreferences =
context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)
private val mainHandler = Handler(Looper.getMainLooper())
/** The smallest and largest figures, and those of a new clock, in icon heights. */
const val MIN_SCALE = 0.4f
const val MAX_SCALE = 1.6f
const val DEFAULT_SCALE = 0.8f
private const val FILE = "flexera_clock_widget"
private const val ALIGN = "align_"
/** The three sizes of 1.0.3 and older; read once, then replaced by [SCALE]. */
private const val SIZE = "size_"
private const val SCALE = "scale_"
private const val WEIGHT = "weight_"
private const val FONT = "font_"
private const val PLACE = "place_"
private const val PLACE_DETAIL = "place_detail_"
private const val LATITUDE = "latitude_"
private const val LONGITUDE = "longitude_"
private const val ICON = "weather_icon_"
private const val CLOCK_APP = "clock_app_"
private const val CLOCK_APP_NAME = "clock_app_name_"
private const val WEATHER_APP = "weather_app_"
private const val WEATHER_APP_NAME = "weather_app_name_"
/** Every option kept for a widget, each under its key followed by the widget's id. */
private val KEYS = listOf(
ALIGN, SIZE, SCALE, WEIGHT, FONT, PLACE, PLACE_DETAIL, LATITUDE, LONGITUDE,
ICON, CLOCK_APP, CLOCK_APP_NAME, WEATHER_APP, WEATHER_APP_NAME,
)
}
@@ -0,0 +1,767 @@
package app.flexera.widget
import android.animation.ValueAnimator
import android.app.ActivityOptions
import android.appwidget.AppWidgetManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.LauncherApps
import android.content.res.Configuration
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.Typeface
import android.provider.AlarmClock
import android.text.TextPaint
import android.text.format.DateFormat
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.ViewConfiguration
import android.widget.FrameLayout
import android.widget.Toast
import android.window.SplashScreen
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat
import app.flexera.widget.ClockWidgetStore.Align
import app.flexera.widget.ClockWidgetStore.Icon
import com.android.launcher3.R
import com.android.launcher3.Utilities
import com.android.launcher3.util.Themes
import java.util.Calendar
import java.util.Locale
import java.util.TimeZone
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
/**
* What the clock widget ([ClockWidgetProvider]) looks like: the time in light figures and the
* date under it, written straight onto the wallpaper in the colour of the icon labels.
*
* Like the picture widget it keeps to the box of the icons in its cells ([IconFrame]). The
* owner chooses which side of that box the text stands on, or its middle, and how large the
* figures are ([ClockWidgetStore], set from the widget's edit button). The size is measured
* against the icons, so that the clock keeps its proportion to them on any grid: from under half
* an icon tall to over one and a half icons (ClockWidgetStore.MIN_SCALE to MAX_SCALE). The
* widget's own height and width are the limit in every case. Up and down the text stands in the
* middle of the widget's own cells, which is what the outline shows while the widget is edited.
*
* A clock for which the owner has picked a place has a third line, the weather there
* ([ClockWeather]), with a picture of the sky before it ([WeatherIcon]), a moon after sunset.
*
* A tap on the time or the date opens the phone's clock app, or the app the owner picked for it;
* a tap on the weather line, or below it, opens the app picked for the weather, else the same.
* The part that was touched dims while the finger is on it, and the app opens out of it.
*
* The same view is the preview in the clock's options ([preview]): drawn as the clock is on the
* home screen, at its size and in its colours, with the options being chosen.
*/
class ClockWidgetView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
) : FrameLayout(context, attrs),
ClockWidgetStore.Listener,
ClockWeather.Listener {
/** The two parts of the widget that a tap can open an app from. */
private enum class Part { CLOCK, WEATHER }
/** Where the view is: in the list of widgets, on the home screen, or in the clock's options. */
private enum class Mode { SAMPLE, HOME, PREVIEW }
/**
* How a clock on the home screen was last laid out, in pixels: its size, the box of the
* icons in its cells ([frame]), the height of what is seen of an icon, and its text colour.
*/
class Look(val width: Int, val height: Int, val frame: RectF, val iconHeight: Float, val textColor: Int)
private var appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID
private var mode = Mode.SAMPLE
private var options = ClockWidgetStore.Options()
/** In the preview: the options shown, and how the clock looks on the home screen, if known. */
private var previewOptions = ClockWidgetStore.Options()
private var look: Look? = null
/**
* Told, in the preview, the largest figures this clock can have, in icon heights: above
* that the widget's height or width is the limit, and the figures grow no more.
*/
var onLargestScale: ((Float) -> Unit)? = null
private var largestTold = -1f
private val frame = RectF()
/** What the figures are measured against: the height of what is seen of an icon. */
private var iconHeight = 0f
private val ink = Rect()
private val now = Calendar.getInstance()
private var time = ""
/** The time as a screen reader says it: as drawn, but with "AM" or "PM" in 12-hour mode. */
private var spokenTime = ""
private var date = ""
/** The weather line; empty for a clock without weather or while none is known. */
private var weather = ""
private var reading: ClockWeather.Reading? = null
/** Whether the sun is down at the weather's place, which turns the sun in the picture into a moon. */
private var night = false
private val weatherIcon = WeatherIcon()
/** Whether the picture is drawn; worked out in arrange(). */
private var showIcon = false
private val timePaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
// Figures of one width, so that the time does not shift sideways from minute to minute.
fontFeatureSettings = "tnum"
}
private val datePaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
typeface = ClockFonts.typeface(context, Typeface.DEFAULT, DATE_WEIGHT)
}
private val weatherPaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
typeface = ClockFonts.typeface(context, Typeface.DEFAULT, WEATHER_WEIGHT)
}
private var textColor = Color.WHITE
private var shadow: WeatherIcon.Shadow? = null
// Where the lines go; worked out in arrange().
private var timeX = 0f
private var timeBaseline = 0f
private var dateX = 0f
private var dateBaseline = 0f
private var weatherX = 0f
private var weatherBaseline = 0f
private var iconX = 0f
private var iconY = 0f
/** What is drawn of each part, and where the weather part begins for a tap: worked out in arrange(). */
private val clockArea = RectF()
private val weatherArea = RectF()
private var weatherFrom = Float.MAX_VALUE
/** The part the finger came down on. A tap that comes without a touch, as from TalkBack, is on the clock. */
private var touched = Part.CLOCK
private var pressedPart = Part.CLOCK
/** How far the pressed part has dimmed, from 0 to 1. */
private var pressed = 0f
private var pressAnimator: ValueAnimator? = null
/**
* A press held this long is the launcher's, to pick the widget up: the part stops looking
* pressed. The launcher does not always let the widget see the end of that touch.
*/
private val longPressed = Runnable { dimTo(0f) }
/** The id of the screen reader's action for the weather, while there is one. */
private var weatherAction = NO_ID
private var listening = false
private val clock = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == Intent.ACTION_TIMEZONE_CHANGED) now.timeZone = TimeZone.getDefault()
tell()
}
}
init {
setWillNotDraw(false)
// Says to Launcher3 that this widget shapes itself (see RoundedCornerEnforcement).
id = android.R.id.background
clipToOutline = true
colour()
}
/**
* On the home screen the text has the colour of the icon labels, which follows the
* wallpaper. The list of widgets is a sheet of its own, so a sample there takes the sheet's
* text colour. The preview takes the colour the clock has on the home screen.
*/
private fun colour() {
textColor = when (mode) {
Mode.SAMPLE -> Themes.getAttrColor(context, android.R.attr.textColorPrimary)
Mode.HOME -> Themes.getAttrColor(context, R.attr.workspaceTextColor)
Mode.PREVIEW -> look?.textColor ?: Color.WHITE
}
val paints = listOf(timePaint, datePaint, weatherPaint)
paints.forEach { it.color = textColor }
// Light text on a wallpaper gets the soft shadow the icon labels have.
if (mode != Mode.SAMPLE && Color.luminance(textColor) > 0.5f) {
val density = resources.displayMetrics.density
val cast = WeatherIcon.Shadow(SHADOW_RADIUS_DP * density, SHADOW_DROP_DP * density, SHADOW_COLOR)
shadow = cast
paints.forEach { it.setShadowLayer(cast.radius, 0f, cast.dy, cast.color) }
} else {
shadow = null
paints.forEach { it.clearShadowLayer() }
}
}
/** Takes the owner's choices for this widget: how the figures are drawn, the weather, the taps. */
private fun takeOptions() {
options = when (mode) {
Mode.SAMPLE -> ClockWidgetStore.Options()
Mode.HOME -> ClockWidgetStore.options(context, appWidgetId)
Mode.PREVIEW -> previewOptions
}
ClockFonts.apply(context, timePaint, options.font, options.weight.value)
readWeather()
}
/** Shows the last known weather for the chosen place and asks for newer if it is due. */
private fun readWeather() {
val place = options.weather
reading = if (place == null) {
null
} else {
if (isAttachedToWindow && mode == Mode.HOME) ClockWeather.refreshIfStale(context, place)
ClockWeather.reading(context, place)
}
weather = reading?.let { ClockWeather.line(context, it) }.orEmpty()
night = reading?.let { ClockWeather.isNight(it, System.currentTimeMillis()) } ?: false
describe()
describeActions()
}
override fun onWeatherChanged() {
val before = Triple(weather, reading?.code, night)
readWeather()
if (Triple(weather, reading?.code, night) != before) {
arrange()
invalidate()
}
}
/** Tells the view which widget it shows. Ids that Android never hands out mean a sample. */
fun bind(appWidgetId: Int) {
this.appWidgetId = appWidgetId
mode = if (appWidgetId <= 0) Mode.SAMPLE else Mode.HOME
takeOptions()
colour()
if (mode == Mode.SAMPLE) {
// In the list of widgets a tap belongs to the list.
setOnClickListener(null)
isClickable = false
} else {
setOnClickListener {
open(touched)
touched = Part.CLOCK
}
}
arrange()
invalidate()
}
/**
* Shows the clock of [appWidgetId] as it is on the home screen, but with [options]: the
* preview in its options. It takes no taps.
*/
fun preview(appWidgetId: Int, options: ClockWidgetStore.Options) {
val first = mode != Mode.PREVIEW || appWidgetId != this.appWidgetId
this.appWidgetId = appWidgetId
mode = Mode.PREVIEW
previewOptions = options
if (first) {
look = ClockLooks[appWidgetId]
setOnClickListener(null)
isClickable = false
colour()
requestLayout()
}
takeOptions()
arrange()
invalidate()
}
override fun onClockOptionsChanged(appWidgetId: Int) {
if (mode != Mode.HOME || appWidgetId != this.appWidgetId) return
takeOptions()
arrange()
invalidate()
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
ClockWidgetStore.addListener(this)
ClockWeather.addListener(this)
if (!listening) {
val changes = IntentFilter().apply {
addAction(Intent.ACTION_TIME_TICK)
addAction(Intent.ACTION_TIME_CHANGED)
addAction(Intent.ACTION_TIMEZONE_CHANGED)
addAction(Intent.ACTION_LOCALE_CHANGED)
}
ContextCompat.registerReceiver(context, clock, changes, ContextCompat.RECEIVER_NOT_EXPORTED)
listening = true
}
now.timeZone = TimeZone.getDefault()
takeOptions()
tell()
arrange()
}
override fun onDetachedFromWindow() {
ClockWidgetStore.removeListener(this)
ClockWeather.removeListener(this)
if (listening) {
context.unregisterReceiver(clock)
listening = false
}
undim()
super.onDetachedFromWindow()
}
override fun onVisibilityAggregated(isVisible: Boolean) {
super.onVisibilityAggregated(isVisible)
// Android does not announce the minutes to an app in the background; catch up, with the
// time and with the weather.
if (isVisible) {
tell()
onWeatherChanged()
} else {
undim()
}
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
// Android's Bold text setting is part of the configuration; the lines follow a new one
// as a TextView does. Heavier lines are wider, so they are placed anew.
ClockFonts.apply(context, timePaint, options.font, options.weight.value)
datePaint.typeface = ClockFonts.typeface(context, Typeface.DEFAULT, DATE_WEIGHT)
weatherPaint.typeface = ClockFonts.typeface(context, Typeface.DEFAULT, WEATHER_WEIGHT)
arrange()
invalidate()
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
val aligned = IconFrame.of(this)
val shown = look.takeIf { mode == Mode.PREVIEW }
if (aligned != null) {
frame.set(aligned.left, aligned.top, aligned.right, aligned.bottom)
iconHeight = aligned.visibleIconSize
if (mode == Mode.HOME) ClockLooks[appWidgetId] = Look(width, height, RectF(frame), iconHeight, textColor)
} else if (shown != null) {
// The preview is laid out at the clock's own size, and scaled to fit by its parent.
frame.set(shown.frame)
iconHeight = shown.iconHeight
} else {
// In the list of widgets: the whole view with a little air, and a made-up icon.
val margin = min(width, height) * LOOSE_MARGIN_SHARE
frame.set(margin, margin, width - margin, height - margin)
iconHeight = frame.height() * LOOSE_ICON_SHARE
}
arrange()
}
/** Reads the clock and shows what it says. */
private fun tell() {
now.timeInMillis = System.currentTimeMillis()
val locale = Locale.getDefault()
// The phone's own choice of 12 or 24 hours, drawn without "AM" and "PM": the date line and
// the daylight say which half of the day it is. Spoken, the time keeps them.
val hours = if (DateFormat.is24HourFormat(context)) "Hm" else "hm"
val spokenPattern = DateFormat.getBestDateTimePattern(locale, hours)
val timePattern = spokenPattern.replace("a", "").trim()
val datePattern = DateFormat.getBestDateTimePattern(locale, "EEEEdMMMM")
val newTime = DateFormat.format(timePattern, now).toString()
val newSpokenTime = DateFormat.format(spokenPattern, now).toString()
val newDate = DateFormat.format(datePattern, now).toString()
// The sun sets between two readings of the weather; the picture follows it.
val newNight = reading?.let { ClockWeather.isNight(it, now.timeInMillis) } ?: false
if (newTime == time && newSpokenTime == spokenTime && newDate == date && newNight == night) return
time = newTime
spokenTime = newSpokenTime
date = newDate
night = newNight
describe()
arrange()
invalidate()
}
/** What a screen reader says for the widget: everything it shows. */
private fun describe() {
contentDescription = listOf(spokenTime, date, weather).filter { it.isNotEmpty() }.joinToString(", ")
}
/**
* What a screen reader offers to do: a double tap opens what a tap on the time opens; when
* the weather opens another app, that is one more action.
*/
private fun describeActions() {
if (mode != Mode.HOME) return
val clockLabel = options.clockTap?.name?.takeIf { it.isNotEmpty() }
?.let { resources.getString(R.string.flexera_clock_widget_open, it) }
?: resources.getString(R.string.flexera_clock_widget_open_clock)
ViewCompat.replaceAccessibilityAction(this, AccessibilityActionCompat.ACTION_CLICK, clockLabel, null)
if (weatherAction != NO_ID) {
ViewCompat.removeAccessibilityAction(this, weatherAction)
weatherAction = NO_ID
}
val weatherApp = options.weatherTap
if (weather.isNotEmpty() && weatherApp != null) {
val name = weatherApp.name.ifEmpty { weatherApp.key.componentName.packageName }
weatherAction = ViewCompat.addAccessibilityAction(
this,
resources.getString(R.string.flexera_clock_widget_open, name),
) { _, _ ->
open(Part.WEATHER)
true
}
}
}
/** Sizes the lines for the frame and the owner's choices, and works out where they go. */
private fun arrange() {
val width = frame.width()
if (width <= 0f || frame.height() <= 0f || time.isEmpty()) return
val scaled = resources.displayMetrics.scaledDensity
// Up and down, the room is the widget's own cells; in the list of widgets, the frame.
val loose = mode == Mode.SAMPLE || (mode == Mode.PREVIEW && look == null)
val roomTop = if (loose) frame.top else 0f
val roomHeight = if (loose) frame.height() else height.toFloat()
// How tall the figures would like to be.
val wanted = iconHeight * options.scale
// The lines under the figures go with them in size, within the sizes that read well, and
// are never wider than the frame. The picture goes with the weather line's text.
val sky = reading?.let { ClockWeather.sky(it.code) }
showIcon = weather.isNotEmpty() && sky != null && options.icon != Icon.NONE
var smallSize = smallSizeFor(wanted, scaled)
sizeSmallLines(smallSize, sky)
val widest = max(datePaint.measureText(date), weatherWidth())
if (widest > width) {
smallSize *= width / widest
sizeSmallLines(smallSize, sky)
}
// What is seen of a line of words is its capitals' height; the room a font keeps above
// and below them would push the text off the middle.
val smallHeight = smallSize * CAPITALS_IN_TEXT_SIZE
val gap = smallSize * GAP_IN_DATE_SIZES
// The picture stands taller than the words beside it; the line before it keeps a
// little less room, so that the space looks the same.
val lineGap = smallSize * if (showIcon) ICON_LINE_GAP_IN_DATE_SIZES else LINE_GAP_IN_DATE_SIZES
val weatherHeight = if (showIcon) max(smallHeight, weatherIcon.ink.height()) else smallHeight
val under = gap + smallHeight + if (weather.isEmpty()) 0f else lineGap + weatherHeight
// The picture's height for a line of text one pixel high, for the limit below.
val iconShare = if (showIcon) weatherIcon.ink.height() / smallSize else 0f
// The figures: as tall as wanted, unless the room above the other lines or the frame's
// width is less. Measured on the figures themselves, not on the line they stand in.
timePaint.textSize = MEASURE_SIZE
timePaint.getTextBounds(time, 0, time.length, ink)
val inkHeightAtMeasure = max(1, ink.height()).toFloat()
val inkWidthAtMeasure = max(1, ink.width()).toFloat()
// The tallest figures that the frame's width allows.
val widestFigures = width * inkHeightAtMeasure / inkWidthAtMeasure
val figures = min(wanted, min(roomHeight - under, widestFigures))
if (mode == Mode.PREVIEW) {
// Told after the layout pass, not during it, and only when it changes.
val largest = largestScale(roomHeight, widestFigures, iconShare, scaled)
if (largest != largestTold) {
largestTold = largest
post { onLargestScale?.invoke(largest) }
}
}
timePaint.textSize = max(1f, MEASURE_SIZE * figures / inkHeightAtMeasure)
timePaint.getTextBounds(time, 0, time.length, ink)
// All lines together, in the middle of the room.
val block = ink.height() + under
val top = roomTop + (roomHeight - block) / 2f
timeBaseline = top - ink.top
dateBaseline = top + ink.height() + gap + smallHeight
val weatherTop = dateBaseline + lineGap
weatherBaseline = weatherTop + (weatherHeight + smallHeight) / 2f
iconY = weatherTop + weatherHeight / 2f - weatherIcon.ink.centerY()
// Sideways it is the figures' own edges that meet the frame's, not the space the font
// leaves beside them; the same goes for the picture.
val dateLength = datePaint.measureText(date)
val weatherSpan = weatherWidth()
val weatherStart = when (options.align) {
Align.LEFT -> {
timeX = frame.left - ink.left
dateX = frame.left
frame.left
}
Align.CENTER -> {
timeX = frame.centerX() - ink.exactCenterX()
dateX = frame.centerX() - dateLength / 2f
frame.centerX() - weatherSpan / 2f
}
Align.RIGHT -> {
timeX = frame.right - ink.right
dateX = frame.right - dateLength
frame.right - weatherSpan
}
}
// The picture comes first in reading order: on the left, or in a right-to-left
// language on the right.
val textLength = weatherPaint.measureText(weather)
if (!showIcon) {
weatherX = weatherStart
} else if (layoutDirection == LAYOUT_DIRECTION_RTL) {
weatherX = weatherStart
iconX = weatherStart + textLength + iconGap() - weatherIcon.ink.left
} else {
iconX = weatherStart - weatherIcon.ink.left
weatherX = weatherStart + weatherIcon.ink.width() + iconGap()
}
// What a tap opens: the weather from halfway between the date and the weather line down.
clockArea.set(timeX + ink.left, timeBaseline + ink.top, timeX + ink.right, timeBaseline + ink.bottom)
clockArea.union(dateX, dateBaseline - smallHeight, dateX + dateLength, dateBaseline)
if (weather.isEmpty()) {
weatherArea.setEmpty()
weatherFrom = Float.MAX_VALUE
} else {
weatherArea.set(weatherStart, weatherTop, weatherStart + weatherSpan, weatherTop + weatherHeight)
weatherFrom = dateBaseline + lineGap / 2f
}
}
/** The text size of the date and weather lines that goes with figures [wanted] tall. */
private fun smallSizeFor(wanted: Float, scaled: Float): Float =
(wanted * DATE_IN_FIGURES).coerceIn(DATE_MIN_SP * scaled, DATE_MAX_SP * scaled)
/**
* The height under the figures that the date and weather lines take at text [size], where
* the picture is [iconShare] times the text size tall.
*/
private fun under(size: Float, iconShare: Float): Float {
val capitals = size * CAPITALS_IN_TEXT_SIZE
val gap = size * GAP_IN_DATE_SIZES
if (weather.isEmpty()) return gap + capitals
val lineGap = size * if (showIcon) ICON_LINE_GAP_IN_DATE_SIZES else LINE_GAP_IN_DATE_SIZES
return gap + capitals + lineGap + max(capitals, size * iconShare)
}
/**
* The largest figures, in icon heights, that still fit the room above the other lines and
* the [widest] figures the frame allows: past it, a larger choice changes nothing. Larger
* figures take larger lines under them, so it is found by halving.
*/
private fun largestScale(roomHeight: Float, widest: Float, iconShare: Float, scaled: Float): Float {
val fits = { scale: Float ->
val wanted = iconHeight * scale
wanted <= min(roomHeight - under(smallSizeFor(wanted, scaled), iconShare), widest)
}
if (iconHeight <= 0f || fits(ClockWidgetStore.MAX_SCALE)) return ClockWidgetStore.MAX_SCALE
var low = 0f
var high = ClockWidgetStore.MAX_SCALE
repeat(LIMIT_STEPS) {
val middle = (low + high) / 2f
if (fits(middle)) low = middle else high = middle
}
return low
}
/** Sets the date and weather lines, and the picture, to [size]. */
private fun sizeSmallLines(size: Float, sky: ClockWeather.Sky?) {
datePaint.textSize = size
weatherPaint.textSize = size
if (showIcon && sky != null) {
weatherIcon.set(sky, night, size * ICON_IN_TEXT_SIZE, options.icon == Icon.COLOR, textColor, shadow)
}
}
private fun iconGap(): Float = weatherPaint.textSize * ICON_GAP_IN_TEXT_SIZE
/** The width of the weather line, with its picture. */
private fun weatherWidth(): Float {
val text = weatherPaint.measureText(weather)
return if (showIcon) weatherIcon.ink.width() + iconGap() + text else text
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (frame.isEmpty || time.isEmpty()) return
part(canvas, Part.CLOCK) {
canvas.drawText(time, timeX, timeBaseline, timePaint)
canvas.drawText(date, dateX, dateBaseline, datePaint)
}
if (weather.isNotEmpty()) {
part(canvas, Part.WEATHER) {
if (showIcon) weatherIcon.draw(canvas, iconX, iconY)
canvas.drawText(weather, weatherX, weatherBaseline, weatherPaint)
}
}
}
/** Draws a part of the widget, dimmed while it is pressed. */
private inline fun part(canvas: Canvas, part: Part, draw: () -> Unit) {
val dim = if (part == pressedPart) pressed * PRESSED_DIM else 0f
if (dim <= 0f) {
draw()
return
}
val layer = canvas.saveLayerAlpha(null, ((1f - dim) * 255).roundToInt())
draw()
canvas.restoreToCount(layer)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
touched = if (event.y >= weatherFrom) Part.WEATHER else Part.CLOCK
}
return super.onTouchEvent(event)
}
override fun setPressed(pressed: Boolean) {
val was = isPressed
super.setPressed(pressed)
if (pressed == was || mode != Mode.HOME) return
removeCallbacks(longPressed)
if (pressed) {
pressedPart = touched
postDelayed(longPressed, ViewConfiguration.getLongPressTimeout().toLong())
}
dimTo(if (pressed) 1f else 0f)
}
/** Fades the pressed part to [target], 1 for pressed and 0 for not. */
private fun dimTo(target: Float) {
pressAnimator?.cancel()
if (pressed == target) return
pressAnimator = ValueAnimator.ofFloat(pressed, target).apply {
duration = if (target > pressed) PRESS_MS else RELEASE_MS
addUpdateListener {
pressed = it.animatedValue as Float
invalidate()
}
start()
}
}
/** Drops the pressed look at once, as when the widget leaves the screen. */
private fun undim() {
removeCallbacks(longPressed)
pressAnimator?.cancel()
if (pressed != 0f) {
pressed = 0f
invalidate()
}
}
/** Opens what a tap on [part] opens, growing out of what is drawn of that part. */
private fun open(part: Part) {
val area = if (part == Part.WEATHER && !weatherArea.isEmpty) weatherArea else clockArea
val reveal = Rect()
area.roundOut(reveal)
if (!reveal.intersect(0, 0, width, height)) reveal.set(0, 0, width, height)
val launch = ActivityOptions.makeClipRevealAnimation(this, reveal.left, reveal.top, reveal.width(), reveal.height())
if (Utilities.ATLEAST_T) launch.splashScreenStyle = SplashScreen.SPLASH_SCREEN_STYLE_ICON
val onScreen = IntArray(2)
getLocationOnScreen(onScreen)
val bounds = Rect(reveal).apply { offset(onScreen[0], onScreen[1]) }
val app = if (part == Part.WEATHER) options.weatherTap ?: options.clockTap else options.clockTap
if (app == null) openClock(launch, bounds) else openApp(app, launch, bounds)
}
/** Opens an app the owner picked; says so when it is no longer there to open. */
private fun openApp(app: ClockWidgetStore.TapApp, launch: ActivityOptions, bounds: Rect) {
val apps = context.getSystemService(LauncherApps::class.java) ?: return
val component = app.key.componentName
val opened = try {
if (apps.isActivityEnabled(component, app.key.user)) {
apps.startMainActivity(component, app.key.user, bounds, launch.toBundle())
true
} else {
false
}
} catch (e: RuntimeException) {
// Uninstalled, or of a work profile that is paused.
Log.w(TAG, "$component could not be opened", e)
false
}
if (!opened) {
val name = app.name.ifEmpty { component.packageName }
Toast.makeText(context, resources.getString(R.string.flexera_quick_launch_app_missing, name), Toast.LENGTH_SHORT).show()
}
}
private fun openClock(launch: ActivityOptions, bounds: Rect) {
val alarms = Intent(AlarmClock.ACTION_SHOW_ALARMS)
try {
// The clock app's own front door; its alarm list needs a permission of its own.
val clockApp = context.packageManager.resolveActivity(alarms, 0)?.activityInfo?.packageName
val intent = clockApp?.let(context.packageManager::getLaunchIntentForPackage) ?: return
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).sourceBounds = bounds
context.startActivity(intent, launch.toBundle())
} catch (e: RuntimeException) {
Log.w(TAG, "The clock app could not be opened", e)
}
}
private companion object {
const val TAG = "ClockWidgetView"
const val DATE_WEIGHT = 500
const val WEATHER_WEIGHT = 400
/** How many halvings find the largest figures: to within a ten-thousandth of an icon. */
const val LIMIT_STEPS = 14
/** The date's text size as a share of the figures' height, and its limits. */
const val DATE_IN_FIGURES = 0.26f
const val DATE_MIN_SP = 12f
const val DATE_MAX_SP = 18f
/** How tall a font's capitals are, as a share of its text size. */
const val CAPITALS_IN_TEXT_SIZE = 0.72f
/** The space between the figures and the date, and between the lines under them, in date text sizes. */
const val GAP_IN_DATE_SIZES = 0.8f
const val LINE_GAP_IN_DATE_SIZES = 0.65f
const val ICON_LINE_GAP_IN_DATE_SIZES = 0.5f
/**
* The weather picture's square, and the space between what is seen of it and the words
* beside it, in text sizes of the weather line.
*/
const val ICON_IN_TEXT_SIZE = 1.65f
const val ICON_GAP_IN_TEXT_SIZE = 0.35f
const val MEASURE_SIZE = 200f
const val LOOSE_MARGIN_SHARE = 0.12f
const val LOOSE_ICON_SHARE = 0.45f
const val SHADOW_RADIUS_DP = 3f
const val SHADOW_DROP_DP = 1f
const val SHADOW_COLOR = 0x59000000
/** How much a pressed part fades, and how quickly it fades and comes back. */
const val PRESSED_DIM = 0.45f
const val PRESS_MS = 90L
const val RELEASE_MS = 220L
}
}
/**
* How each clock on the home screen looks, by widget id ([ClockWidgetView.Look]), for the
* preview in its options. Kept while the launcher runs. Used on the main thread only.
*/
internal object ClockLooks {
private val looks = HashMap<Int, ClockWidgetView.Look>()
operator fun get(appWidgetId: Int): ClockWidgetView.Look? = looks[appWidgetId]
operator fun set(appWidgetId: Int, look: ClockWidgetView.Look) {
looks[appWidgetId] = look
}
}
@@ -0,0 +1,132 @@
package app.flexera.widget
import android.appwidget.AppWidgetProviderInfo
import android.content.ComponentName
import android.graphics.Rect
import android.view.View
import android.widget.FrameLayout
import com.android.launcher3.DeviceProfile
import com.android.launcher3.icons.IconNormalizer.ICON_VISIBLE_AREA_FACTOR
import com.android.launcher3.model.data.LauncherAppWidgetInfo
import com.android.launcher3.widget.LauncherAppWidgetHostView
import com.android.launcher3.widget.PendingAppWidgetHostView
import kotlin.math.max
import kotlin.math.roundToInt
/**
* The widgets that come with the launcher: Pictures ([PictureWidgetProvider]) and Clock
* ([ClockWidgetProvider]).
*
* Android knows each as an ordinary app widget, so they are added, moved, resized and removed
* like any other. What they show is not sent through Android, though: the launcher draws them
* itself with a view of its own, which is what lets them line up with the icons ([IconFrame]).
* This is where Launcher3's widget code asks about them, and about the room every other widget
* keeps in its cells, which by default lines those up with the icons as well.
*/
object FlexeraWidgets {
private val noInset = Rect()
private fun isOwn(provider: ComponentName?): Boolean =
provider == PictureWidgetProvider.componentName || provider == ClockWidgetProvider.componentName
/**
* The room a widget's cells keep free around it, on each side; one cell is [cellWidth] by
* [cellHeight]. The launcher's own widgets take none, because they place what they draw
* against the icons of their cells by themselves ([IconFrame]); every other widget gets
* [appWidgetPadding].
*/
@JvmStatic
fun cellInset(child: View, profile: DeviceProfile, cellWidth: Int, cellHeight: Int): Rect =
cellInset((child.tag as? LauncherAppWidgetInfo)?.providerName, profile, cellWidth, cellHeight)
/**
* [cellInset] for a widget of [provider]. The drop animation asks this way, because a widget
* dropped from the list of widgets is not tagged with its item until it is on the home screen;
* asked about its view, the launcher's own Clock would get another app's room.
*/
@JvmStatic
fun cellInset(provider: ComponentName?, profile: DeviceProfile, cellWidth: Int, cellHeight: Int): Rect =
if (isOwn(provider)) noInset else appWidgetPadding(profile, cellWidth, cellHeight)
/** [appWidgetPadding] for the cells of [profile]'s home screen. */
@JvmStatic
fun appWidgetPadding(profile: DeviceProfile): Rect {
val cell = profile.cellSize
return appWidgetPadding(profile, cell.x, cell.y)
}
/**
* The room a widget of another app keeps free inside its cells, on each side, where one
* cell is [cellWidth] by [cellHeight]. Lined up with the icons (the default), it is the
* distance from the cells' edges to the edges of the icons that would sit in them: the
* same box the launcher's own widgets draw in ([IconFrame]), so that every widget's edges
* meet the edges of the icons above, below and beside it. Otherwise it is Launcher3's own,
* which the Widget padding setting scales.
*
* How many cells a widget takes is still worked out with Launcher3's own padding
* (LauncherAppWidgetProviderInfo.initSpans), on purpose: lining widgets up with the icons
* changes no widget's cell count, on the home screen or in the list of widgets. The cost is
* that a widget can be laid out smaller than the minimum size it declares, by up to about a
* cell less an icon each way; one that asks for 72dp of height on cells about 90dp tall,
* say, gets one row and so the height of an icon.
*/
@JvmStatic
fun appWidgetPadding(profile: DeviceProfile, cellWidth: Int, cellHeight: Int): Rect {
if (!profile.alignWidgetsWithIcons || cellWidth <= 0 || cellHeight <= 0) {
return profile.widgetPadding
}
// As in IconFrame: the icon is centred sideways in its cell and sits a set distance
// below the cell's top; what is seen of it leaves a little air inside its square.
val icon = profile.iconSizePx.toFloat()
val air = icon * (1f - ICON_VISIBLE_AREA_FACTOR) / 2f
val iconTop = if (profile.cellYPaddingPx >= 0) {
profile.cellYPaddingPx.toFloat()
} else {
max(0f, (cellHeight - profile.cellHeightPx) / 2f)
}
val side = max(0, ((cellWidth - icon) / 2f + air).roundToInt())
return Rect(
side,
max(0, (iconTop + air).roundToInt()),
side,
max(0, (cellHeight - iconTop - icon + air).roundToInt()),
)
}
/**
* Puts the launcher's own view into a widget host view when the widget is one of the
* launcher's, and returns it; returns null for every other widget. Launcher3's host view
* calls this in place of asking Android for the widget's views.
*/
@JvmStatic
fun attachIfOwn(host: LauncherAppWidgetHostView, appWidgetId: Int, info: AppWidgetProviderInfo?): View? {
val provider = info?.provider
if (!isOwn(provider)) return null
// A widget that still waits to be set up draws its own "tap to set up".
if (host is PendingAppWidgetHostView) return null
val pictures = provider == PictureWidgetProvider.componentName
var view: View? = null
for (i in host.childCount - 1 downTo 0) {
val child = host.getChildAt(i)
val wanted = if (pictures) child is PictureWidgetView else child is ClockWidgetView
if (wanted && view == null) view = child else host.removeViewAt(i)
}
if (view == null) {
view = if (pictures) PictureWidgetView(host.context) else ClockWidgetView(host.context)
host.addView(
view,
FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT,
),
)
}
when (view) {
is PictureWidgetView -> view.bind(appWidgetId)
is ClockWidgetView -> view.bind(appWidgetId)
}
return view
}
}
@@ -0,0 +1,83 @@
package app.flexera.widget
import android.content.Context
import android.content.ContextWrapper
import android.view.View
import com.android.launcher3.ShortcutAndWidgetContainer
import com.android.launcher3.celllayout.CellLayoutLayoutParams
import com.android.launcher3.icons.IconNormalizer.ICON_VISIBLE_AREA_FACTOR
import com.android.launcher3.views.ActivityContext
import kotlin.math.max
import kotlin.math.min
/**
* The box around the icons that would sit in the cells a widget covers: from the left edge of
* the first column's icon to the right edge of the last column's, and from the top of the first
* row's icon to the bottom of the last row's. A widget of the launcher's own that keeps what it
* draws inside this box lines up with the icons beside, above and below it.
*/
internal class IconFrame private constructor(
val left: Float,
val top: Float,
val right: Float,
val bottom: Float,
/** The size of the square an icon is drawn in. */
val iconSize: Float,
/** The size of what is seen of an icon; the rest of the square is room for its shadow. */
val visibleIconSize: Float,
) {
companion object {
/**
* The box for the widget that [view] fills, in [view]'s own coordinates. Null when
* [view] is not inside a widget on the home screen (in the list of widgets, say).
*/
fun of(view: View): IconFrame? {
val host = view.parent as? View ?: return null
val lp = host.layoutParams as? CellLayoutLayoutParams ?: return null
val container = host.parent as? ShortcutAndWidgetContainer ?: return null
val profile = activityContext(view.context)?.deviceProfile ?: return null
if (lp.cellHSpan <= 0 || lp.cellVSpan <= 0) return null
// The cells the widget covers, measured from the corner of the host view. Undoes
// what CellLayoutLayoutParams.setup took off them.
val cell = profile.cellSize
val inset = FlexeraWidgets.cellInset(host, profile, cell.x, cell.y)
val spanLeft = -(lp.leftMargin + inset.left).toFloat()
val spanTop = -(lp.topMargin + inset.top).toFloat()
val spanWidth = (lp.width + lp.leftMargin + lp.rightMargin + inset.left + inset.right).toFloat()
val spanHeight = (lp.height + lp.topMargin + lp.bottomMargin + inset.top + inset.bottom).toFloat()
val gap = profile.cellLayoutBorderSpacePx
val cellWidth = (spanWidth - (lp.cellHSpan - 1) * gap.x) / lp.cellHSpan
val cellHeight = (spanHeight - (lp.cellVSpan - 1) * gap.y) / lp.cellVSpan
// Where an icon sits in its cell: centred sideways and a set distance below the
// cell's top (ShortcutAndWidgetContainer.measureChild, BubbleTextView.getIconBounds).
val icon = profile.iconSizePx.toFloat()
val iconLeft = (cellWidth - icon) / 2f
val iconTop = if (profile.cellYPaddingPx >= 0) {
profile.cellYPaddingPx.toFloat()
} else {
max(0f, (cellHeight - min(container.measuredHeight, profile.cellHeightPx)) / 2f)
}
val visible = icon * ICON_VISIBLE_AREA_FACTOR
val air = (icon - visible) / 2f
val l = spanLeft + iconLeft + air - view.left
val r = spanLeft + spanWidth - iconLeft - air - view.left
val t = spanTop + iconTop + air - view.top
val b = spanTop + spanHeight - cellHeight + iconTop + icon - air - view.top
if (r - l < 1f || b - t < 1f) return null
return IconFrame(l, t, r, b, icon, visible)
}
private fun activityContext(context: Context): ActivityContext? {
var current: Context? = context
while (current != null) {
if (current is ActivityContext) return current
current = (current as? ContextWrapper)?.baseContext
}
return null
}
}
}
@@ -0,0 +1,227 @@
package app.flexera.widget
import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.Gravity
import android.widget.FrameLayout
import android.widget.ProgressBar
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.WorkerThread
import androidx.lifecycle.lifecycleScope
import com.android.launcher3.LauncherAppState
import com.android.launcher3.LauncherSettings.Favorites
import com.android.launcher3.R
import com.android.launcher3.model.data.LauncherAppWidgetInfo
import kotlin.math.min
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* Lets the owner choose the pictures of a picture widget. It has no screen of its own: it opens
* Android's photo picker, copies what was chosen into the widget's storage and closes.
*
* Android starts it when the widget is put on the home screen and from the widget's edit
* button; the widget starts it itself when it has no pictures. The photo picker hands over
* only the pictures the owner picks, so the launcher needs no access to the gallery.
*
* Android may make this screen anew at any moment, as it does when the dark theme comes on: the
* picker then answers the new screen, and a copy under way goes on and is waited for by it. A
* copy goes on, too, when the owner leaves for the home screen while it is made; only Back stops
* it.
*/
class PictureWidgetConfigActivity : ComponentActivity() {
private var appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID
/** True from asking the photo picker until it answers; kept when the screen is made anew. */
private var picking = false
private val picker = registerForActivityResult(
ActivityResultContracts.PickMultipleVisualMedia(mostPictures()),
) { chosen -> onChosen(chosen) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
appWidgetId = intent?.getIntExtra(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID,
) ?: AppWidgetManager.INVALID_APPWIDGET_ID
// Leaving without pictures means "no": a widget that was just being added is dropped.
setResult(RESULT_CANCELED, result())
if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
finish()
return
}
val underWay = copies[appWidgetId]
when {
// The pictures are still being copied, as when Android made this screen anew.
underWay != null -> waitFor(underWay)
// The picker is open and answers here.
savedInstanceState?.getBoolean(STATE_PICKING) == true -> picking = true
else -> start()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean(STATE_PICKING, picking)
}
private fun start() {
val widget = appWidgetId
lifecycleScope.launch {
val ready = withContext(Dispatchers.IO) { hasPicturesWaiting(widget) }
if (ready) {
setResult(RESULT_OK, result())
finish()
} else {
picking = true
picker.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
}
}
}
/**
* True if this widget is waiting to be set up and already has its pictures, so that there
* is nothing to choose: a widget that came back from a restore with them, or that an import
* brought along with its photos (see [PictureWidgetProvider.onNewAppWidgetId]). The launcher's
* database knows which widgets wait to be set up. The edit button, and a widget that has no
* pictures, open the photo picker as ever.
*/
private fun hasPicturesWaiting(widget: Int): Boolean {
val context = applicationContext
if (PictureWidgetStore.pictures(context, widget).isEmpty()) return false
return try {
LauncherAppState.getInstance(context).model.modelDbController.query(
arrayOf(Favorites.RESTORED),
"${Favorites.APPWIDGET_ID} = ? AND ${Favorites.ITEM_TYPE} = ${Favorites.ITEM_TYPE_APPWIDGET}",
arrayOf(widget.toString()),
null,
).use { row ->
row.moveToFirst() && row.getInt(0) != LauncherAppWidgetInfo.RESTORE_COMPLETED
}
} catch (e: RuntimeException) {
Log.w(TAG, "Could not look the widget up", e)
false
}
}
private fun onChosen(chosen: List<Uri>) {
picking = false
if (chosen.isEmpty()) {
finish()
return
}
val widget = appWidgetId
val context = applicationContext
// Not tied to this screen, which Android may make anew while the copies are made, and
// which the owner may leave for the home screen without waiting for them.
val started = copying.async(Dispatchers.IO) {
val saved = PictureWidgetStore.replace(context, widget, chosen) { isActive }
// A widget that was being added is dropped when its screen is left before the copies
// are done, and they go with it.
if (isRemoved(context, widget)) PictureWidgetStore.delete(context, widget)
saved
}
copies[widget] = started
copying.launch {
started.join()
if (copies[widget] === started) copies.remove(widget)
}
waitFor(started)
}
private fun waitFor(underWay: Deferred<Int>) {
// Back while the pictures are copied means no: the copy stops, and the widget keeps what
// it had. Any other way out, as to the home screen, lets the copy finish.
onBackPressedDispatcher.addCallback(
this,
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
underWay.cancel()
finish()
}
},
)
// Copying a few large photos takes a moment.
setContentView(
FrameLayout(this).apply {
addView(
ProgressBar(context),
FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT,
Gravity.CENTER,
),
)
},
)
lifecycleScope.launch {
val saved = try {
underWay.await()
} catch (e: CancellationException) {
// Back stopped the copy, or this screen is gone; if it was made anew, the new one
// waits for the copy.
throw e
} catch (e: Exception) {
Log.w(TAG, "The chosen pictures were not copied", e)
0
}
if (saved > 0) {
setResult(RESULT_OK, result())
} else {
Toast.makeText(
this@PictureWidgetConfigActivity,
R.string.flexera_picture_widget_unreadable,
Toast.LENGTH_LONG,
).show()
}
finish()
}
}
private fun result() = Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
private companion object {
const val TAG = "PictureWidgetConfig"
const val STATE_PICKING = "picking"
/** Copies of chosen pictures under way, by widget, each until it is done; used on the main thread only. */
val copies = HashMap<Int, Deferred<Int>>()
/** Where those copies run: outside any one screen, so that they outlast it. */
val copying = MainScope()
/** True if the widget has left the home screen, which takes its id away. */
@WorkerThread
fun isRemoved(context: Context, widget: Int): Boolean = try {
AppWidgetManager.getInstance(context).getAppWidgetInfo(widget) == null
} catch (e: RuntimeException) {
Log.w(TAG, "Could not look the widget up", e)
false
}
/** How many pictures the photo picker lets the owner tick. */
fun mostPictures(): Int = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
min(PictureWidgetStore.MAX_PICTURES, MediaStore.getPickImagesMaxLimit())
} else {
PictureWidgetStore.MAX_PICTURES
}
}
}
@@ -0,0 +1,95 @@
package app.flexera.widget
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.util.Log
import com.android.launcher3.BuildConfig
import com.android.launcher3.LauncherSettings.Favorites
import com.android.launcher3.model.data.LauncherAppWidgetInfo
/**
* The launcher's own picture widget: one picture, or several that take turns.
*
* Android knows it as an ordinary app widget, so it is added, moved, resized and removed like
* any other. What it shows is not sent through Android, though: the launcher draws it itself
* with a [PictureWidgetView], which is what lets it line up with the icons around it. Its
* pictures live in [PictureWidgetStore], under the widget's id; they leave only with the widget,
* and a widget that comes back from a restore under a new id takes them along.
* See [FlexeraWidgets].
*/
class PictureWidgetProvider : AppWidgetProvider() {
override fun onDeleted(context: Context, appWidgetIds: IntArray) {
appWidgetIds.forEach { PictureWidgetStore.delete(context, it) }
}
/** After Android's own restore. */
override fun onRestored(context: Context, oldWidgetIds: IntArray, newWidgetIds: IntArray) {
PictureWidgetStore.move(context, oldWidgetIds, newWidgetIds)
}
companion object {
private const val TAG = "PictureWidgetProvider"
@JvmField
val componentName = ComponentName(BuildConfig.APPLICATION_ID, PictureWidgetProvider::class.java.name)
/**
* Told by Launcher3 (WidgetInflater) that a widget of the home screen got a new id
* because the one it had is no longer valid: after a restore of the launcher's backup or
* an import. [oldAppWidgetId] is the id it had; an import's widgets had none.
*
* Android's onRestored does not come in that case. Launcher3 deletes the old id after
* the home screens are loaded, and onDeleted would take the pictures with it, so they go
* to the new id first. A picture widget of an import takes the pictures the import kept
* for the place it was put in.
*/
@JvmStatic
fun onNewAppWidgetId(context: Context, item: LauncherAppWidgetInfo, oldAppWidgetId: Int) {
val newId = item.appWidgetId
if (item.providerName != componentName || newId <= 0 || newId == oldAppWidgetId) return
try {
if (oldAppWidgetId > 0) {
PictureWidgetStore.move(context, intArrayOf(oldAppWidgetId), intArrayOf(newId))
} else if (item.container == Favorites.CONTAINER_DESKTOP) {
PictureWidgetStore.adoptImport(context, newId, item.screenId, item.cellX, item.cellY)
}
} catch (e: RuntimeException) {
// Never in the way of loading the home screens.
Log.w(TAG, "Pictures not handed to widget $newId", e)
}
}
/**
* Told by Launcher3 (LoaderTask) that the home screens are loaded. Each picture widget an
* import brought along has had its id by then, and with it the pictures the import kept
* for it ([onNewAppWidgetId]). Pictures still kept are for a widget that did not come,
* and no widget can take them later, so they go.
*/
@JvmStatic
fun onHomeScreensLoaded(context: Context) {
try {
PictureWidgetStore.clearImports(context)
} catch (e: RuntimeException) {
Log.w(TAG, "Pictures of an import not removed", e)
}
}
/**
* Told by Launcher3 (LauncherWidgetHolder) that it deleted a widget id, of any widget.
* Android calls onDeleted only for an id that was bound, and a widget removed while it
* waited for "tap to set up" may have pictures under an id that was not
* ([onNewAppWidgetId]); they go with it. For another widget's id there is nothing to remove.
*/
@JvmStatic
fun onAppWidgetIdDeleted(context: Context, appWidgetId: Int) {
if (appWidgetId <= 0) return
try {
PictureWidgetStore.delete(context, appWidgetId)
} catch (e: RuntimeException) {
Log.w(TAG, "Pictures of widget $appWidgetId not removed", e)
}
}
}
}
@@ -0,0 +1,320 @@
package app.flexera.widget
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.BitmapRegionDecoder
import android.graphics.ImageDecoder
import android.graphics.Rect
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.annotation.WorkerThread
import java.io.File
import java.io.IOException
import java.util.Locale
import java.util.concurrent.CopyOnWriteArraySet
import kotlin.math.max
import kotlin.math.roundToInt
/**
* Where the picture widget keeps its pictures: copies in the app's own storage, one folder per
* widget on the home screen.
*
* Copies, because Android's photo picker lends a picture only for a while, and because a copy
* needs no permission to read the gallery later. Each copy is scaled down to what a widget can
* show, so a slideshow of large photos stays small.
*/
object PictureWidgetStore {
/** Told, on the main thread, that the pictures of a widget were replaced or removed. */
fun interface Listener {
fun onPicturesChanged(appWidgetId: Int)
}
private val listeners = CopyOnWriteArraySet<Listener>()
private val mainHandler = Handler(Looper.getMainLooper())
fun addListener(listener: Listener) {
listeners.add(listener)
}
fun removeListener(listener: Listener) {
listeners.remove(listener)
}
/** The pictures of one widget, in the order they were chosen. Empty when it has none. */
fun pictures(context: Context, appWidgetId: Int): List<File> =
folder(context, appWidgetId).listFiles { file -> file.isFile }?.sortedBy { it.name }.orEmpty()
/**
* Gives a widget copies of [sources] in place of the pictures it had, and returns how many
* were saved. A source that cannot be read is left out; when none can be read the widget
* keeps what it had and the result is 0. So it does when [keepGoing] turns false before the
* copies are done, as when the owner presses Back while they are being made.
*/
@WorkerThread
fun replace(context: Context, appWidgetId: Int, sources: List<Uri>, keepGoing: () -> Boolean = { true }): Int {
val incoming = File(root(context), "$appWidgetId$INCOMING_SUFFIX")
var saved = saveCopies(context, incoming, sources, keepGoing)
if (saved == 0) return 0
val folder = folder(context, appWidgetId)
folder.deleteRecursively()
if (!incoming.renameTo(folder)) {
incoming.deleteRecursively()
saved = 0
}
notifyChanged(appWidgetId)
return saved
}
/**
* Keeps copies of [sources] for a picture widget that an import has put at a place on a
* home screen. Such a widget has no id yet: the launcher gives it one when it first loads
* the imported home screens, and [adoptImport] then hands it these pictures, which from then
* on go with the widget wherever it is moved and leave with it. Returns how many were saved.
*/
@WorkerThread
fun stageImport(context: Context, screen: Int, cellX: Int, cellY: Int, sources: List<Uri>): Int =
saveCopies(context, importFolder(context, screen, cellX, cellY), sources) { true }
/**
* Forgets the pictures an import kept that no widget took: when another import keeps its own,
* and once the home screens are loaded ([PictureWidgetProvider.onHomeScreensLoaded]).
*/
fun clearImports(context: Context) {
root(context).listFiles { file -> file.isDirectory && file.name.startsWith(IMPORT_PREFIX) }
?.forEach { it.deleteRecursively() }
}
/**
* Gives a widget the pictures an import kept for the place it was imported to, when the
* widget gets its id (see [PictureWidgetProvider.onNewAppWidgetId]). True if there were any.
* Asked only then, so that a widget put in that place later never gets them.
*/
@WorkerThread
fun adoptImport(context: Context, appWidgetId: Int, screen: Int, cellX: Int, cellY: Int): Boolean {
val staged = importFolder(context, screen, cellX, cellY)
if (staged.listFiles { file -> file.isFile }.isNullOrEmpty()) return false
val folder = folder(context, appWidgetId)
folder.deleteRecursively()
if (!staged.renameTo(folder)) return false
notifyChanged(appWidgetId)
return true
}
/**
* Fills [into] with copies of [sources], replacing what it held. Returns how many were saved;
* none, with nothing kept, if [keepGoing] turns false on the way.
*/
private fun saveCopies(context: Context, into: File, sources: List<Uri>, keepGoing: () -> Boolean): Int {
into.deleteRecursively()
if (!into.mkdirs()) return 0
var saved = 0
for (source in sources.take(MAX_PICTURES)) {
if (!keepGoing()) break
val bitmap = try {
decode(context, source)
} catch (e: Exception) {
Log.w(TAG, "A chosen picture could not be read", e)
null
} ?: continue
// A picture with see-through parts keeps them; everything else is a photo.
val keepsAlpha = isSeeThrough(bitmap)
val name = String.format(Locale.ROOT, "%03d.%s", saved, if (keepsAlpha) "png" else "jpg")
val file = File(into, name)
val written = try {
file.outputStream().use { out ->
bitmap.compress(
if (keepsAlpha) Bitmap.CompressFormat.PNG else Bitmap.CompressFormat.JPEG,
JPEG_QUALITY,
out,
)
}
} catch (e: Exception) {
Log.w(TAG, "A chosen picture could not be saved", e)
false
}
bitmap.recycle()
if (written) saved++ else file.delete()
}
if (saved == 0 || !keepGoing()) {
into.deleteRecursively()
return 0
}
return saved
}
/** Removes the pictures of a widget that left the home screen. */
fun delete(context: Context, appWidgetId: Int) {
folder(context, appWidgetId).deleteRecursively()
File(root(context), "$appWidgetId$INCOMING_SUFFIX").deleteRecursively()
notifyChanged(appWidgetId)
}
/**
* Hands the pictures of each widget in [from] to the widget at the same place in [to]: the
* ids that a restore gave the widgets in place of the ones they had.
*/
fun move(context: Context, from: IntArray, to: IntArray) {
// In two steps, so that an id that is one widget's old id and another's new one ends up
// with the right pictures.
val moving = ArrayList<Pair<File, Int>>()
for (i in from.indices) {
val newId = to.getOrNull(i) ?: continue
val folder = folder(context, from[i])
if (newId == from[i] || !folder.isDirectory) continue
val aside = File(root(context), "${from[i]}$MOVING_SUFFIX")
aside.deleteRecursively()
if (folder.renameTo(aside)) moving.add(aside to newId)
}
for ((aside, newId) in moving) {
val target = folder(context, newId)
target.deleteRecursively()
if (!aside.renameTo(target)) aside.deleteRecursively()
notifyChanged(newId)
}
}
/**
* Reads a stored picture for a frame of [width] by [height] pixels: only the part the frame
* shows, which is the middle of the picture in the frame's shape, at the frame's size. A
* picture smaller than the frame comes at its own size and is stretched when drawn.
*/
@WorkerThread
fun load(file: File, width: Int, height: Int): Bitmap? {
if (width <= 0 || height <= 0) return null
val decoder = openInParts(file) ?: return loadWhole(file, width, height)
try {
val pictureWidth = decoder.width
val pictureHeight = decoder.height
if (pictureWidth <= 0 || pictureHeight <= 0) return null
val part = if (pictureWidth.toLong() * height > pictureHeight.toLong() * width) {
// Wider than the frame: its sides are cut off.
val partWidth = (pictureHeight.toLong() * width / height).toInt().coerceIn(1, pictureWidth)
val left = (pictureWidth - partWidth) / 2
Rect(left, 0, left + partWidth, pictureHeight)
} else {
// Taller than the frame: its top and bottom are cut off.
val partHeight = (pictureWidth.toLong() * height / width).toInt().coerceIn(1, pictureHeight)
val top = (pictureHeight - partHeight) / 2
Rect(0, top, pictureWidth, top + partHeight)
}
var sample = 1
while (part.width() / (sample * 2) >= width && part.height() / (sample * 2) >= height) {
sample *= 2
}
val read = decoder.decodeRegion(part, BitmapFactory.Options().apply { inSampleSize = sample })
?: return loadWhole(file, width, height)
// Read at a power of two, the part can still be up to twice the frame's size each way.
if (read.width <= width && read.height <= height) return read
val scaled = Bitmap.createScaledBitmap(read, width, height, true)
if (scaled !== read) read.recycle()
return scaled
} finally {
decoder.recycle()
}
}
/** Opens a stored picture for reading in parts; null if Android cannot read it that way. */
@Suppress("DEPRECATION") // The only way before Android 12.
private fun openInParts(file: File): BitmapRegionDecoder? = try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
BitmapRegionDecoder.newInstance(file.path)
} else {
BitmapRegionDecoder.newInstance(file.path, false)
}
} catch (e: IOException) {
null
}
/**
* Reads a whole stored picture, at the smallest size that still covers the frame; for a
* picture that cannot be read in parts, or whose part could not be read. The frame then crops
* it when it is drawn.
*/
private fun loadWhole(file: File, width: Int, height: Int): Bitmap? {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(file.path, bounds)
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return null
var sample = 1
while (bounds.outWidth / (sample * 2) >= width && bounds.outHeight / (sample * 2) >= height) {
sample *= 2
}
return BitmapFactory.decodeFile(file.path, BitmapFactory.Options().apply { inSampleSize = sample })
}
/** Reads a chosen picture, upright and no larger than [MAX_EDGE] on its long side. */
private fun decode(context: Context, source: Uri): Bitmap? {
val resolver = context.contentResolver
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// ImageDecoder turns the picture the way the camera held it and knows the newer
// formats (HEIC, AVIF).
return ImageDecoder.decodeBitmap(ImageDecoder.createSource(resolver, source)) { decoder, info, _ ->
// The copy is compressed right after, which needs the pixels in ordinary memory.
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
val longEdge = max(info.size.width, info.size.height)
if (longEdge > MAX_EDGE) {
val scale = MAX_EDGE.toFloat() / longEdge
decoder.setTargetSize(
max(1, (info.size.width * scale).roundToInt()),
max(1, (info.size.height * scale).roundToInt()),
)
}
}
}
// Android 8: no ImageDecoder. Photos taken sideways stay sideways there.
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
resolver.openInputStream(source)?.use { BitmapFactory.decodeStream(it, null, bounds) }
var sample = 1
while (max(bounds.outWidth, bounds.outHeight) / sample > MAX_EDGE) sample *= 2
val options = BitmapFactory.Options().apply { inSampleSize = sample }
return resolver.openInputStream(source)?.use { BitmapFactory.decodeStream(it, null, options) }
}
/**
* True if some of the picture lets the background through. Many pictures can hold such
* parts without having any (every screenshot, for one), so the pixels are looked at.
*/
private fun isSeeThrough(bitmap: Bitmap): Boolean {
if (!bitmap.hasAlpha()) return false
val row = IntArray(bitmap.width)
for (y in 0 until bitmap.height) {
bitmap.getPixels(row, 0, bitmap.width, 0, y, bitmap.width, 1)
if (row.any { it ushr 24 != 0xFF }) return true
}
return false
}
private fun notifyChanged(appWidgetId: Int) {
mainHandler.post { listeners.forEach { it.onPicturesChanged(appWidgetId) } }
}
private fun root(context: Context) = File(context.filesDir, FOLDER)
private fun folder(context: Context, appWidgetId: Int) = File(root(context), appWidgetId.toString())
private fun importFolder(context: Context, screen: Int, cellX: Int, cellY: Int) =
File(root(context), "$IMPORT_PREFIX$screen-$cellX-$cellY")
private const val TAG = "PictureWidgetStore"
private const val FOLDER = "flexera_picture_widget"
private const val INCOMING_SUFFIX = ".incoming"
private const val MOVING_SUFFIX = ".moving"
private const val IMPORT_PREFIX = "import-"
/** The most pictures one widget holds. */
const val MAX_PICTURES = 50
/**
* The long side of a stored picture, in pixels. A widget is never wider than the screen,
* and a picture is cropped to fill it, so this leaves room to crop on any phone.
*/
private const val MAX_EDGE = 2048
private const val JPEG_QUALITY = 90
}
@@ -0,0 +1,736 @@
package app.flexera.widget
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.app.Activity
import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.BitmapShader
import android.graphics.Canvas
import android.graphics.LinearGradient
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.graphics.Shader
import android.graphics.Typeface
import android.graphics.fonts.FontStyle
import android.os.Build
import android.text.Layout
import android.text.StaticLayout
import android.text.TextPaint
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.animation.LinearInterpolator
import android.widget.FrameLayout
import app.lawnchair.icons.shape.CornerShapeCompat
import app.lawnchair.icons.shape.IconShape
import app.lawnchair.preferences2.PreferenceManager2
import app.lawnchair.preferences2.firstCached
import com.android.launcher3.CellLayout
import com.android.launcher3.Launcher
import com.android.launcher3.LauncherState
import com.android.launcher3.R
import com.android.launcher3.ShortcutAndWidgetContainer
import com.android.launcher3.Workspace
import com.android.launcher3.folder.Folder
import com.android.launcher3.util.Executors
import java.io.File
import java.text.BreakIterator
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
/**
* What the picture widget ([PictureWidgetProvider]) looks like on the home screen: one picture
* cropped to fill a frame, or several that take turns every [INTERVAL_MS].
*
* The frame is made to look like a large icon. Its edges are the outer edges of the icons that
* would sit in the cells the widget covers, and its corners are the corners of the icon shape
* in use, so the picture lines up with the icons beside, above and below it. The view itself is
* larger than the frame: it fills the widget's cells and draws nothing outside the frame.
*
* The pictures take turns only while the widget can be seen ([isSeen]). Each is read at the
* size of the frame, which keeps the one shown small enough to stay in memory while the launcher
* is out of sight, so that it is there at once on the way back.
*
* In the list of widgets and while it is dragged from there, the same view shows a sample.
*/
class PictureWidgetView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
) : FrameLayout(context, attrs),
PictureWidgetStore.Listener {
/** A picture ready to draw. */
private class Slide(val bitmap: Bitmap) {
val shader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
}
private var appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID
/** True while this is only a sample of the widget, with no pictures of its own. */
private var sample = true
private var pictures: List<File> = emptyList()
private var index = 0
private var shown: Slide? = null
// The picture that is fading in over the shown one, and its place among the pictures.
private var incoming: Slide? = null
private var incomingIndex = 0
private var fade = 0f
private var fadeAnimator: ValueAnimator? = null
// Pictures are read off the main thread. A result is used only if no newer read was started.
private var loadGeneration = 0
private var loading = false
/** The frame size the shown picture was read for; 0 before the first read. */
private var loadedWidth = 0
private var loadedHeight = 0
private var onScreen = false
/**
* True when none of the pictures could be read: the widget then shows and acts as if it had
* none, until they are read anew ([reload]).
*/
private var unreadable = false
/** True while the slideshow waits for the widget to be seen again ([isSeen]). */
private var waitingToBeSeen = false
private val frame = RectF()
private val shape = Path()
private val farHill = Path()
private val nearHill = Path()
private val sun = Path()
private val scratch = Path()
private val cropMatrix = Matrix()
private var hint: StaticLayout? = null
private var hintTop = 0f
/** False when the hint needs the whole frame and the sun is left out of the drawing. */
private var drawsSun = true
private var sampleShader: Shader? = null
private val picturePaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
private val platePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = PLATE_COLOR }
private val sceneryPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = SCENERY_COLOR }
private val hintPaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
color = HINT_COLOR
textSize = resources.getDimension(R.dimen.flexera_picture_widget_hint_text_size)
// Heavier with Android's Bold text setting, like the icon labels.
typeface = withBoldText(Typeface.DEFAULT)
// The soft shadow of the icon labels, for the words over the light parts of the drawing.
val density = resources.displayMetrics.density
setShadowLayer(HINT_SHADOW_RADIUS_DP * density, 0f, HINT_SHADOW_DROP_DP * density, HINT_SHADOW_COLOR)
}
private val advance = Runnable { showNext() }
private val reloadForSize = Runnable { reload() }
// The icon shape, as corners that can be put on a rectangle of any size. Null for the few
// shapes that are one fixed outline; those get plain round corners.
private val cornerShape: IconShape.CornerBased? by lazy(LazyThreadSafetyMode.NONE) {
when (val iconShape = currentIconShape()) {
is IconShape.SystemBased -> iconShape.findNearestShape()
is IconShape.CornerBased -> iconShape
else -> null
}
}
init {
setWillNotDraw(false)
// Launcher3 rounds the corners of every widget that does not round its own. This id
// together with clipToOutline is how a widget says that it does (see
// RoundedCornerEnforcement); without it the picture's corners would be cut twice.
id = android.R.id.background
clipToOutline = true
}
/** Tells the view which widget it shows. Ids that Android never hands out mean a sample. */
fun bind(appWidgetId: Int) {
this.appWidgetId = appWidgetId
sample = appWidgetId <= 0
if (sample) {
// In the list of widgets a tap belongs to the list.
setOnClickListener(null)
isClickable = false
} else {
setOnClickListener { onTap() }
}
index = 0
// What the frame holds depends on whether this is a sample.
frame.setEmpty()
if (isLaidOut) updateFrame()
if (isAttachedToWindow) reload()
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
PictureWidgetStore.addListener(this)
reload()
}
override fun onDetachedFromWindow() {
PictureWidgetStore.removeListener(this)
fadeAnimator?.cancel()
removeCallbacks(advance)
removeCallbacks(reloadForSize)
// Whatever is still being read is no longer wanted.
loadGeneration++
loading = false
super.onDetachedFromWindow()
}
override fun onVisibilityAggregated(isVisible: Boolean) {
super.onVisibilityAggregated(isVisible)
// The pictures only take turns while the home screen can be seen.
onScreen = isVisible
if (isVisible) scheduleNext() else removeCallbacks(advance)
}
override fun onPicturesChanged(appWidgetId: Int) {
if (appWidgetId != this.appWidgetId || sample) return
index = 0
reload()
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
updateFrame()
if (!isAttachedToWindow || frame.isEmpty || pictures.isEmpty()) return
val width = frame.width().roundToInt()
val height = frame.height().roundToInt()
if (width == loadedWidth && height == loadedHeight) return
removeCallbacks(reloadForSize)
if (loadedWidth == 0) {
// The first time the size is known.
post(reloadForSize)
} else {
// The widget is being resized: read the picture anew once the size has settled.
postDelayed(reloadForSize, RESIZE_SETTLE_MS)
}
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
// Android's Bold text setting is part of the configuration; the hint follows a new one
// as a TextView does. Heavier words take more room, so it is laid out anew.
hintPaint.typeface = withBoldText(Typeface.DEFAULT)
if (!frame.isEmpty) buildSample()
invalidate()
}
/** Reads the widget's pictures anew and shows the one whose turn it is. */
private fun reload() {
fadeAnimator?.cancel()
removeCallbacks(advance)
removeCallbacks(reloadForSize)
incoming = null
pictures = if (sample) emptyList() else PictureWidgetStore.pictures(context, appWidgetId)
unreadable = false
updateDescription()
if (pictures.isEmpty()) {
loadGeneration++
loading = false
shown = null
loadedWidth = 0
loadedHeight = 0
invalidate()
return
}
if (frame.isEmpty) {
// Not laid out yet; onLayout comes back here.
loadedWidth = 0
loadedHeight = 0
return
}
index = index.coerceIn(0, pictures.lastIndex)
loadedWidth = frame.width().roundToInt()
loadedHeight = frame.height().roundToInt()
showFirstReadable(index, pictures.size)
}
/**
* Shows the picture at [position], or the first after it that can be read, trying [tries]
* pictures at most. When none can be read the widget looks and acts as if it had none, so
* that a tap asks for new ones.
*/
private fun showFirstReadable(position: Int, tries: Int) {
load(position) { slide ->
when {
slide != null -> {
index = position
shown = slide
updateDescription()
invalidate()
scheduleNext()
}
tries > 1 -> showFirstReadable((position + 1) % pictures.size, tries - 1)
else -> {
shown = null
unreadable = true
updateDescription()
invalidate()
}
}
}
}
private fun load(position: Int, then: (Slide?) -> Unit) {
val file = pictures.getOrNull(position)
if (file == null) {
then(null)
return
}
val width = max(1, frame.width().roundToInt())
val height = max(1, frame.height().roundToInt())
val generation = ++loadGeneration
loading = true
Executors.THREAD_POOL_EXECUTOR.execute {
val bitmap = try {
PictureWidgetStore.load(file, width, height)
} catch (e: Exception) {
Log.w(TAG, "A picture could not be read", e)
null
} catch (e: OutOfMemoryError) {
Log.w(TAG, "A picture was too large to read", e)
null
}
Executors.MAIN_EXECUTOR.execute {
if (generation == loadGeneration) {
loading = false
then(bitmap?.let(::Slide))
}
}
}
}
/**
* Gives the shown picture a whole turn from now. With none that can be read there are no
* turns: the widget asks for new pictures instead.
*/
private fun scheduleNext() {
removeCallbacks(advance)
waitingToBeSeen = false
if (onScreen && !sample && !unreadable && pictures.size > 1) postDelayed(advance, INTERVAL_MS)
}
/** Brings in the next picture; at once for [now], as for a tap, else only if it can be seen. */
private fun showNext(now: Boolean = false) {
if (pictures.size < 2 || loading || incoming != null) return
if (!now && !isSeen()) {
// Nobody can see it, so nothing is read or faded in. It is looked at again shortly;
// seen again, the picture it shows gets a whole turn first.
waitingToBeSeen = true
removeCallbacks(advance)
if (onScreen) postDelayed(advance, SEEN_CHECK_MS)
return
}
if (!now && waitingToBeSeen) {
scheduleNext()
return
}
waitingToBeSeen = false
val next = (index + 1) % pictures.size
load(next) { slide ->
if (slide == null) {
// A picture that cannot be read is passed over.
index = next
scheduleNext()
} else {
incoming = slide
incomingIndex = next
startFade()
}
}
}
private fun startFade() {
if (!ValueAnimator.areAnimatorsEnabled() || !isShown || shown == null) {
finishFade()
return
}
fade = 0f
fadeAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
duration = FADE_MS
interpolator = LinearInterpolator()
addUpdateListener {
fade = it.animatedValue as Float
invalidate()
}
addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) = finishFade()
})
start()
}
}
private fun finishFade() {
fadeAnimator = null
val slide = incoming ?: return
shown = slide
index = incomingIndex
incoming = null
fade = 0f
updateDescription()
invalidate()
scheduleNext()
}
/**
* True while the widget can really be seen. Its window being on the screen is not enough:
* Launcher3 leaves every home screen page shown, and covers them with the app drawer, Recents
* or a folder without hiding them.
*/
private fun isSeen(): Boolean {
if (!onScreen || !isShown) return false
val launcher = launcher() ?: return true
if (!launcher.isInState(LauncherState.NORMAL) &&
!launcher.isInState(LauncherState.SPRING_LOADED) &&
!launcher.isInState(LauncherState.EDIT_MODE)
) {
return false
}
if (Folder.getOpen(launcher) != null) return false
// On the home screen: the page the widget is on has to be one of those on the screen,
// and not faded out.
val cells = (parent as? View)?.parent as? ShortcutAndWidgetContainer ?: return true
if (cells.alpha <= 0f) return false
val page = cells.parent as? CellLayout ?: return true
val pages = page.parent as? Workspace<*> ?: return true
return pages.isVisible(page)
}
private fun launcher(): Launcher? {
var current: Context? = context
while (current != null) {
if (current is Launcher) return current
current = (current as? ContextWrapper)?.baseContext
}
return null
}
private fun onTap() {
when {
// Nothing to show yet, as after a restore on a new phone, or nothing that can be
// read: ask for pictures.
pictures.isEmpty() || unreadable -> choosePictures()
// A tap does not wait for the picture's turn to end.
pictures.size > 1 -> {
removeCallbacks(advance)
showNext(now = true)
}
}
}
private fun choosePictures() {
val intent = Intent(context, PictureWidgetConfigActivity::class.java)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
var activity: Context? = context
while (activity != null && activity !is Activity) {
activity = (activity as? ContextWrapper)?.baseContext
}
try {
if (activity != null) {
activity.startActivity(intent)
} else {
context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
} catch (e: RuntimeException) {
Log.w(TAG, "The picture chooser could not be opened", e)
}
}
private fun updateDescription() {
contentDescription = when {
sample -> resources.getString(R.string.flexera_picture_widget)
pictures.isEmpty() || unreadable -> resources.getString(R.string.flexera_picture_widget_empty)
pictures.size == 1 -> resources.getString(R.string.flexera_picture_widget)
else -> resources.getString(
R.string.flexera_picture_widget_position,
index + 1,
pictures.size,
)
}
}
/**
* Works out where the picture goes inside this view. On the home screen that is the box
* around the icons of the cells the widget covers; anywhere else it is the whole view.
*/
private fun updateFrame() {
var left = 0f
var top = 0f
var right = width.toFloat()
var bottom = height.toFloat()
var corner = min(width, height) * LOOSE_CORNER_SHARE
var iconSize = min(width, height).toFloat()
val aligned = IconFrame.of(this)
if (aligned != null) {
left = aligned.left
top = aligned.top
right = aligned.right
bottom = aligned.bottom
corner = aligned.visibleIconSize / 2f
iconSize = aligned.iconSize
}
corner = min(corner, min(right - left, bottom - top) / 2f)
if (left == frame.left && top == frame.top && right == frame.right && bottom == frame.bottom) return
frame.set(left, top, right, bottom)
shape.reset()
val corners = cornerShape
if (corners != null) {
CornerShapeCompat.addToPath(corners, shape, left, top, right, bottom, size = corner)
} else {
val radius = corner * currentIconShape().windowTransitionRadius
shape.addRoundRect(frame, radius, radius, Path.Direction.CW)
}
shape.close()
// The same soft shadow an icon has (ShadowGenerator), so the picture sits on the
// wallpaper the way the icons do.
platePaint.setShadowLayer(
iconSize * SHADOW_BLUR_SHARE,
0f,
iconSize * SHADOW_DROP_SHARE,
SHADOW_COLOR,
)
buildSample()
invalidate()
}
/** The drawing shown in place of a picture: a sun over two hills, and a hint when empty. */
private fun buildSample() {
val width = frame.width()
val height = frame.height()
val unit = min(width, height)
scratch.reset()
scratch.moveTo(frame.left + width * 0.28f, frame.bottom)
scratch.quadTo(frame.left + width * 0.66f, frame.bottom - unit * 0.80f, frame.right + width * 0.10f, frame.bottom)
scratch.close()
farHill.op(scratch, shape, Path.Op.INTERSECT)
scratch.reset()
scratch.moveTo(frame.left - width * 0.10f, frame.bottom)
scratch.quadTo(frame.left + width * 0.30f, frame.bottom - unit * 0.62f, frame.left + width * 0.74f, frame.bottom)
scratch.close()
nearHill.op(scratch, shape, Path.Op.INTERSECT)
scratch.reset()
scratch.addCircle(
frame.right - unit * SUN_CENTRE_SHARE,
frame.top + unit * SUN_CENTRE_SHARE,
unit * SUN_RADIUS_SHARE,
Path.Direction.CW,
)
sun.op(scratch, shape, Path.Op.INTERSECT)
sampleShader = LinearGradient(
frame.left,
frame.top,
frame.right,
frame.bottom,
SAMPLE_COLOR_START,
SAMPLE_COLOR_END,
Shader.TileMode.CLAMP,
)
hint = null
drawsSun = true
if (!sample) layOutHint(unit)
}
/**
* Lays out the hint of a widget without pictures. It goes below the sun, so that the white
* of the sun is never behind the words, at the size the owner has text at. Where they need
* more room, at a large font size, they take the whole frame and the sun is left out; where
* that is still too little they get smaller, though never smaller than at Android's standard
* font size. Too small a widget for the words gets the drawing alone.
*/
private fun layOutHint(unit: Float) {
val margin = resources.getDimension(R.dimen.flexera_picture_widget_hint_margin)
val width = (frame.width() - 2 * margin).toInt()
if (width <= 0) return
val text = resources.getString(R.string.flexera_picture_widget_empty)
val bottom = frame.bottom - margin
val belowSun = frame.top + unit * (SUN_CENTRE_SHARE + SUN_RADIUS_SHARE) + margin
val wanted = hintPaint.textSize
layHint(text, width, wanted, bottom - belowSun)?.let { layout ->
hint = layout
hintTop = belowSun + (bottom - belowSun - layout.height) / 2f
return
}
val top = frame.top + margin
val smallest = wanted / max(1f, resources.configuration.fontScale)
var size = wanted
while (true) {
val layout = layHint(text, width, size, bottom - top)
if (layout != null) {
hint = layout
hintTop = top + (bottom - top - layout.height) / 2f
drawsSun = false
return
}
if (size <= smallest) return
size = max(smallest, size * HINT_SHRINK)
}
}
/**
* The hint at a text [size], or null if it is taller than [room], or if a word of it is wider
* than [width] and would be split.
*/
private fun layHint(text: String, width: Int, size: Float, room: Float): StaticLayout? {
if (room <= 0f) return null
val paint = TextPaint(hintPaint).apply { textSize = size }
val words = BreakIterator.getLineInstance().apply { setText(text) }
var start = words.first()
var end = words.next()
while (end != BreakIterator.DONE) {
if (paint.measureText(text.substring(start, end).trimEnd()) > width) return null
start = end
end = words.next()
}
val layout = StaticLayout.Builder.obtain(text, 0, text.length, paint, width)
.setAlignment(Layout.Alignment.ALIGN_CENTER)
.build()
return layout.takeIf { it.height <= room }
}
/**
* [typeface] made heavier by Android's Bold text setting (Android 12 and newer), as Android
* does for the text of a TextView but not for text drawn on a canvas.
*/
private fun withBoldText(typeface: Typeface): Typeface {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return typeface
val adjustment = resources.configuration.fontWeightAdjustment
if (adjustment == 0 || adjustment == Configuration.FONT_WEIGHT_ADJUSTMENT_UNDEFINED) return typeface
val weight = (typeface.weight + adjustment).coerceIn(FontStyle.FONT_WEIGHT_MIN, FontStyle.FONT_WEIGHT_MAX)
return Typeface.create(typeface, weight, typeface.isItalic)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (frame.isEmpty) return
val current = shown
if (current == null) {
if (pictures.isEmpty() || unreadable) {
drawSample(canvas)
} else {
// A picture is on its way from storage. Until it comes there is the plate alone:
// the drawing and its hint are for a widget that has no pictures.
canvas.drawPath(shape, platePaint)
}
return
}
// The plate carries the shadow. A picture with see-through parts goes without, so
// that the wallpaper shows through it.
if (!current.bitmap.hasAlpha()) canvas.drawPath(shape, platePaint)
drawSlide(canvas, current, 255)
incoming?.let { drawSlide(canvas, it, (fade * 255).roundToInt()) }
}
private fun drawSlide(canvas: Canvas, slide: Slide, alpha: Int) {
val bitmap = slide.bitmap
// Fill the frame and crop what does not fit, keeping the middle of the picture.
val scale = max(frame.width() / bitmap.width, frame.height() / bitmap.height)
cropMatrix.setScale(scale, scale)
cropMatrix.postTranslate(
frame.left + (frame.width() - bitmap.width * scale) / 2f,
frame.top + (frame.height() - bitmap.height * scale) / 2f,
)
slide.shader.setLocalMatrix(cropMatrix)
picturePaint.shader = slide.shader
picturePaint.alpha = alpha
canvas.drawPath(shape, picturePaint)
picturePaint.shader = null
}
private fun drawSample(canvas: Canvas) {
platePaint.shader = sampleShader
canvas.drawPath(shape, platePaint)
platePaint.shader = null
if (drawsSun) {
sceneryPaint.alpha = SUN_ALPHA
canvas.drawPath(sun, sceneryPaint)
}
sceneryPaint.alpha = FAR_HILL_ALPHA
canvas.drawPath(farHill, sceneryPaint)
sceneryPaint.alpha = NEAR_HILL_ALPHA
canvas.drawPath(nearHill, sceneryPaint)
val layout = hint ?: return
canvas.save()
canvas.translate(frame.left + (frame.width() - layout.width) / 2f, hintTop)
layout.draw(canvas)
canvas.restore()
}
private fun currentIconShape(): IconShape = PreferenceManager2.getInstance(context).iconShape.firstCached()
companion object {
private const val TAG = "PictureWidgetView"
/** How long each picture of several is shown. */
const val INTERVAL_MS = 10_000L
/** How long one picture takes to fade into the next. */
const val FADE_MS = 600L
/** How long the size has to stay put during a resize before the picture is read anew. */
const val RESIZE_SETTLE_MS = 200L
/** How often a slideshow that nobody can see looks whether it can be seen again. */
const val SEEN_CHECK_MS = 2_000L
/** Corner radius, as a share of the shorter side, where there are no icons to match. */
const val LOOSE_CORNER_SHARE = 0.18f
// An icon's shadow as Launcher3 draws it (ShadowGenerator.BLUR_FACTOR and
// KEY_SHADOW_DISTANCE), as shares of the icon size.
const val SHADOW_BLUR_SHARE = 1.68f / 48f
const val SHADOW_DROP_SHARE = 1f / 48f
const val SHADOW_COLOR = 0x26000000
/** Under a picture, where it shows only while the next one fades in. */
const val PLATE_COLOR = 0xFF17181C.toInt()
const val SAMPLE_COLOR_START = 0xFF5B6B95.toInt()
const val SAMPLE_COLOR_END = 0xFF2B3350.toInt()
const val SCENERY_COLOR = 0xFFFFFFFF.toInt()
const val SUN_ALPHA = 150
/** Where the sun's middle is from the top right corner, and its radius, as shares of the shorter side. */
const val SUN_CENTRE_SHARE = 0.30f
const val SUN_RADIUS_SHARE = 0.10f
const val FAR_HILL_ALPHA = 40
const val NEAR_HILL_ALPHA = 64
const val HINT_COLOR = 0xF2FFFFFF.toInt()
/** The step by which a hint that does not fit gets smaller. */
const val HINT_SHRINK = 0.9f
// The soft shadow of light text on the wallpaper, as the clock widget has it.
const val HINT_SHADOW_RADIUS_DP = 3f
const val HINT_SHADOW_DROP_DP = 1f
const val HINT_SHADOW_COLOR = 0x59000000
}
}
@@ -0,0 +1,347 @@
package app.flexera.widget
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.graphics.Region
import android.graphics.Shader
import app.flexera.widget.ClockWeather.Sky
import kotlin.math.cos
import kotlin.math.sin
/**
* The picture beside the clock widget's weather line: a sun, a moon, clouds, rain, snow or
* lightning, drawn by the launcher itself so that it is sharp at any size and takes the colour
* of the text.
*
* Each picture is a few filled shapes on a grid of 24 by 24, in layers from back to front. A
* shape in front cuts a thin gap into the ones behind it, as in Material's own weather symbols,
* so that a cloud stays clear of the sun behind it on any wallpaper. In colour the sun, the moon
* and lightning are warm, rain and snow blue, and the clouds the colour of the text; plain, all
* of it is the colour of the text. The colours come in two strengths: bright beside light text,
* for dark wallpapers, and deeper beside dark text, for light ones.
*/
class WeatherIcon {
/** What a shape is, which decides its colour. */
private enum class Role { SUN, MOON, CLOUD, BACK_CLOUD, WATER, ICE, BOLT, MIST }
private class Layer(val role: Role, val path: Path)
private var sky: Sky? = null
private var night = false
private var size = 0f
private var colour = true
private var textColor = Color.WHITE
private var shadow: Shadow? = null
/** The layers at the current size, in pixels from the top left of the picture's square. */
private var drawn: List<Pair<Layer, Paint>> = emptyList()
/** Where the picture's ink is inside its square of [size]. */
val ink = RectF()
/** The soft shadow the text casts, which the picture casts as well. */
data class Shadow(val radius: Float, val dy: Float, val color: Int)
/**
* Sets what is drawn: [sky] at day or [night], in a square [size] pixels wide, in [colour] or
* plain, beside text of [textColor] that casts [shadow].
*/
fun set(sky: Sky, night: Boolean, size: Float, colour: Boolean, textColor: Int, shadow: Shadow?) {
if (sky == this.sky && night == this.night && size == this.size && colour == this.colour &&
textColor == this.textColor && shadow == this.shadow
) {
return
}
this.sky = sky
this.night = night
this.size = size
this.colour = colour
this.textColor = textColor
this.shadow = shadow
val scale = Matrix().apply { setScale(size / GRID, size / GRID) }
val palette = if (Color.luminance(textColor) > 0.5f) BRIGHT else DEEP
ink.setEmpty()
val bounds = RectF()
drawn = layers(sky, night).map { layer ->
val path = Path(layer.path).apply { transform(scale) }
path.computeBounds(bounds, true)
ink.union(bounds)
Layer(layer.role, path) to paint(layer.role, palette, bounds)
}
}
private fun paint(role: Role, palette: Palette, bounds: RectF): Paint {
val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
if (!colour) {
paint.color = withAlpha(textColor, if (role == Role.BACK_CLOUD) BACK_ALPHA else if (role == Role.MIST) MIST_ALPHA else 1f)
} else {
when (role) {
Role.SUN -> gradient(paint, bounds, palette.sunTop, palette.sunBottom)
Role.MOON -> gradient(paint, bounds, palette.moonTop, palette.moonBottom)
Role.BOLT -> gradient(paint, bounds, palette.sunTop, palette.sunBottom)
Role.WATER -> paint.color = palette.water
Role.ICE -> paint.color = palette.ice
Role.CLOUD -> paint.color = textColor
Role.BACK_CLOUD -> paint.color = withAlpha(textColor, BACK_ALPHA)
Role.MIST -> paint.color = withAlpha(textColor, MIST_ALPHA)
}
}
shadow?.let { paint.setShadowLayer(it.radius, 0f, it.dy, it.color) }
return paint
}
private fun gradient(paint: Paint, bounds: RectF, top: Int, bottom: Int) {
paint.color = Color.BLACK
paint.shader = LinearGradient(0f, bounds.top, 0f, bounds.bottom, top, bottom, Shader.TileMode.CLAMP)
}
/** Draws the picture with its square's top left at [x], [y]. */
fun draw(canvas: Canvas, x: Float, y: Float) {
if (drawn.isEmpty()) return
canvas.save()
canvas.translate(x, y)
for ((layer, paint) in drawn) canvas.drawPath(layer.path, paint)
canvas.restore()
}
private class Palette(
val sunTop: Int,
val sunBottom: Int,
val moonTop: Int,
val moonBottom: Int,
val water: Int,
val ice: Int,
)
private companion object {
const val GRID = 24f
/** The gap a shape in front cuts into the shapes behind it, in grid units. */
const val GAP = 1.2f
const val BACK_ALPHA = 0.55f
const val MIST_ALPHA = 0.8f
/** Beside light text, on a dark wallpaper. */
val BRIGHT = Palette(
sunTop = 0xFFFFD95A.toInt(),
sunBottom = 0xFFFFAE2B.toInt(),
moonTop = 0xFFFFF1C4.toInt(),
moonBottom = 0xFFF2D27A.toInt(),
water = 0xFF7CC8FF.toInt(),
ice = 0xFFD3EEFF.toInt(),
)
/** Beside dark text, on a light wallpaper. */
val DEEP = Palette(
sunTop = 0xFFFFB300.toInt(),
sunBottom = 0xFFF57C00.toInt(),
moonTop = 0xFFE0B84E.toInt(),
moonBottom = 0xFFB8862B.toInt(),
water = 0xFF1E7FD6.toInt(),
ice = 0xFF3D8FD9.toInt(),
)
fun withAlpha(color: Int, alpha: Float): Int =
Color.argb((Color.alpha(color) * alpha).toInt(), Color.red(color), Color.green(color), Color.blue(color))
/** Every picture, on the grid, made once each. Used on the main thread only. */
val cache = HashMap<Pair<Sky, Boolean>, List<Layer>>()
fun layers(sky: Sky, night: Boolean): List<Layer> = cache.getOrPut(sky to night) { build(sky, night) }
fun build(sky: Sky, night: Boolean): List<Layer> {
val layers = ArrayList<Layer>()
// A cloud with rain, snow or lightning under it.
val raised = { cloud(1.8f, -2.6f, 0.85f) }
when (sky) {
Sky.CLEAR -> layers += if (night) Layer(Role.MOON, moon(12.5f, 11.5f, 8f)) else Layer(Role.SUN, sun(12f, 12f, 4.6f, 7f, 9.6f, 2f))
Sky.MOSTLY_CLEAR -> {
val cloud = cloud(11.4f, 10.6f, 0.5f)
layers += behind(if (night) Layer(Role.MOON, moon(10.5f, 10f, 7f)) else Layer(Role.SUN, sun(10f, 10f, 4.2f, 6.4f, 8.8f, 1.9f, clearOf = cloud)), cloud)
layers += Layer(Role.CLOUD, cloud)
}
Sky.PARTLY_CLOUDY -> {
val cloud = cloud(5.6f, 5f, 0.8f)
layers += behind(if (night) Layer(Role.MOON, moon(9f, 8.6f, 6.2f)) else Layer(Role.SUN, sun(8.6f, 8.6f, 3.6f, 5.5f, 7.5f, 1.8f, clearOf = cloud)), cloud)
layers += Layer(Role.CLOUD, cloud)
}
Sky.OVERCAST -> {
val front = cloud(-0.8f, 4.4f, 0.86f)
layers += behind(Layer(Role.BACK_CLOUD, cloud(8.2f, 1.2f, 0.66f)), front)
layers += Layer(Role.CLOUD, front)
}
Sky.FOG -> {
layers += Layer(Role.CLOUD, cloud(2.4f, -1.6f, 0.8f))
layers += Layer(Role.MIST, union(line(4.5f, 18.2f, 19.5f, 18.2f, 1.9f), line(7.5f, 21.6f, 16.5f, 21.6f, 1.9f)))
}
Sky.DRIZZLE -> {
layers += Layer(Role.CLOUD, raised())
layers += Layer(Role.WATER, union(circle(8.4f, 18f, 1.2f), circle(12.4f, 20.6f, 1.2f), circle(16.4f, 18f, 1.2f)))
}
Sky.RAIN -> {
layers += Layer(Role.CLOUD, raised())
layers += Layer(Role.WATER, union(streak(8.9f, 16.4f), streak(13.1f, 17.4f, 4.6f), streak(17.3f, 16.4f)))
}
Sky.FREEZING_RAIN -> {
layers += Layer(Role.CLOUD, raised())
layers += Layer(Role.WATER, union(streak(8.6f, 16.4f), streak(17.4f, 16.4f)))
layers += Layer(Role.ICE, flake(12.6f, 19.4f))
}
Sky.SNOW -> {
layers += Layer(Role.CLOUD, raised())
layers += Layer(Role.ICE, union(flake(8.2f, 18.2f), flake(12.6f, 20.8f), flake(17f, 18.2f)))
}
Sky.SHOWERS, Sky.SNOW_SHOWERS -> {
// The sun, or the moon, looks out from behind the cloud.
val cloud = cloud(4.9f, -0.9f, 0.78f)
layers += behind(if (night) Layer(Role.MOON, moon(7.2f, 6.8f, 4.6f)) else Layer(Role.SUN, sun(6.8f, 6.6f, 2.9f, 4.4f, 6f, 1.6f, clearOf = cloud)), cloud)
layers += Layer(Role.CLOUD, cloud)
layers += if (sky == Sky.SHOWERS) {
Layer(Role.WATER, union(streak(10.4f, 16.8f), streak(14.6f, 17.6f, 4.4f), streak(18.6f, 16.8f)))
} else {
Layer(Role.ICE, union(flake(10f, 18.6f), flake(14.4f, 21f), flake(18.6f, 18.6f)))
}
}
Sky.THUNDERSTORM -> {
val bolt = polygon(13.6f, 13.4f, 9.4f, 19.2f, 12.2f, 19.2f, 10.6f, 23.6f, 15.8f, 17f, 12.9f, 17f, 14.9f, 13.4f)
layers += behind(Layer(Role.CLOUD, raised()), bolt)
layers += Layer(Role.BOLT, bolt)
}
}
return layers
}
/** [layer] with a gap cut around [front], which is drawn over it. */
fun behind(layer: Layer, front: Path): Layer =
Layer(layer.role, Path(layer.path).apply { op(around(front), Path.Op.DIFFERENCE) })
/** [shape] and the gap around it. */
fun around(shape: Path): Path {
val around = Path()
Paint().apply {
style = Paint.Style.STROKE
strokeWidth = GAP * 2
strokeJoin = Paint.Join.ROUND
}.getFillPath(shape, around)
around.op(shape, Path.Op.UNION)
return around
}
/** Whether [a] and [b] overlap, to within a twentieth of a grid unit. */
fun overlap(a: Path, b: Path): Boolean {
val fine = Matrix().apply { setScale(20f, 20f) }
val clip = Region(-1000, -1000, 1000, 1000)
val first = Region().apply { setPath(Path(a).apply { transform(fine) }, clip) }
val second = Region().apply { setPath(Path(b).apply { transform(fine) }, clip) }
return first.op(second, Region.Op.INTERSECT)
}
/** A cloud: a flat base with round ends and three puffs on it, moved by [dx], [dy] and scaled by [scale]. */
fun cloud(dx: Float, dy: Float, scale: Float): Path {
val path = Path().apply { addRoundRect(RectF(3f, 11f, 21f, 19f), 4f, 4f, Path.Direction.CW) }
path.op(circle(13f, 10.5f, 5.5f), Path.Op.UNION)
path.op(circle(8.5f, 12.5f, 3.5f), Path.Op.UNION)
path.op(circle(17f, 13f, 3.2f), Path.Op.UNION)
path.transform(Matrix().apply { setScale(scale, scale); postTranslate(dx, dy) })
return path
}
/**
* A sun: a disc of [radius] and eight rays from [rayIn] to [rayOut] from its centre. A
* ray that would reach into the gap around [clearOf], a cloud in front, is left out
* whole: cut, it would leave a stub beside the cloud.
*/
fun sun(cx: Float, cy: Float, radius: Float, rayIn: Float, rayOut: Float, rayWidth: Float, clearOf: Path? = null): Path {
val path = circle(cx, cy, radius)
val keepOut = clearOf?.let(::around)
for (i in 0 until 8) {
val angle = i * Math.PI / 4
val c = cos(angle).toFloat()
val s = sin(angle).toFloat()
val ray = line(cx + c * rayIn, cy + s * rayIn, cx + c * rayOut, cy + s * rayOut, rayWidth)
if (keepOut != null && overlap(ray, keepOut)) continue
path.op(ray, Path.Op.UNION)
}
return path
}
/** A crescent moon: a disc less a disc a little up and to the right. */
fun moon(cx: Float, cy: Float, radius: Float): Path =
circle(cx, cy, radius).apply { op(circle(cx + radius * 0.58f, cy - radius * 0.42f, radius * 0.82f), Path.Op.DIFFERENCE) }
/** A slanting streak of rain, [length] long, from its top at [x], [y]. */
fun streak(x: Float, y: Float, length: Float = 3.8f): Path = line(x, y, x - length * 0.31f, y + length, 1.9f)
/** A snowflake: three crossed strokes. */
fun flake(cx: Float, cy: Float): Path {
val path = Path()
for (i in 0 until 3) {
val angle = Math.PI / 2 + i * Math.PI / 3
val c = cos(angle).toFloat() * FLAKE_ARM
val s = sin(angle).toFloat() * FLAKE_ARM
path.op(line(cx - c, cy - s, cx + c, cy + s, 1.2f), Path.Op.UNION)
}
return path
}
const val FLAKE_ARM = 1.8f
fun circle(cx: Float, cy: Float, radius: Float): Path = Path().apply { addCircle(cx, cy, radius, Path.Direction.CW) }
/** A stroke with round ends, as a filled shape. */
fun line(x1: Float, y1: Float, x2: Float, y2: Float, width: Float): Path {
val stroke = Path().apply {
moveTo(x1, y1)
lineTo(x2, y2)
}
val filled = Path()
Paint().apply {
style = Paint.Style.STROKE
strokeWidth = width
strokeCap = Paint.Cap.ROUND
}.getFillPath(stroke, filled)
return filled
}
/** A closed shape through the points given as x, y pairs, with slightly rounded corners. */
fun polygon(vararg xy: Float): Path {
val outline = Path().apply {
moveTo(xy[0], xy[1])
for (i in 2 until xy.size step 2) lineTo(xy[i], xy[i + 1])
close()
}
// A thin stroke with round joins around it softens the corners.
val rounded = Path()
Paint().apply {
style = Paint.Style.FILL_AND_STROKE
strokeWidth = 0.5f
strokeJoin = Paint.Join.ROUND
}.getFillPath(outline, rounded)
return rounded
}
fun union(vararg paths: Path): Path {
val result = Path(paths[0])
for (i in 1 until paths.size) result.op(paths[i], Path.Op.UNION)
return result
}
}
}
@@ -0,0 +1,16 @@
package app.lawnchair.gestures.handlers
import android.content.Context
import app.flexera.reader.ReaderPage
import app.lawnchair.LawnchairLauncher
/**
* Flexera Launcher: brings the RSS reader's page in ([ReaderPage]), for a gesture other than the
* swipe past a home screen page, which brings it in with the finger instead. In Lawnchair's
* package because Lawnchair's gesture handlers are a sealed class.
*/
class OpenRssReaderGestureHandler(context: Context) : GestureHandler(context) {
override suspend fun onTrigger(launcher: LawnchairLauncher) {
ReaderPage.open(launcher)
}
}
+1 -1
View File
@@ -2,4 +2,4 @@
# build.gradle reads this and derives the Android version code from it
# (major * 10000 + minor * 100 + patch), so the name and the code can never disagree.
# flexera/release.ps1 raises it for every release.
versionName=0.2.0
versionName=1.0.7
+98
View File
@@ -0,0 +1,98 @@
// Remakes WEBSITE/assets/og.jpg, the 1200 x 630 card that chats and social sites show for a link
// to the website. The card is drawn from the site itself, so it follows it: the headline is read
// from WEBSITE/index.html, and the phones are drawn by the site's own script.js and styles.css.
//
// node flexera/website/make-og.mjs
//
// Needs Chrome and Node 22 or newer, nothing to install. Set CHROME to the browser's path if it
// is not in the usual place. Run it again whenever the headline or the look of the top changes.
import { spawn } from 'node:child_process';
import { readFileSync, writeFileSync, rmSync, mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { setTimeout as sleep } from 'node:timers/promises';
const here = dirname(fileURLToPath(import.meta.url));
const site = resolve(here, '..', '..', 'WEBSITE');
const out = join(site, 'assets', 'og.jpg');
const card = join(site, '.og-card.html'); // lives beside index.html for a moment, so its links to styles, script and fonts are the site's own
const CHROME = process.env.CHROME || 'C:/Program Files/Google/Chrome/Application/chrome.exe';
const PORT = 9377;
const index = readFileSync(join(site, 'index.html'), 'utf8');
const sprites = [...index.matchAll(/<svg class="sprite"[\s\S]*?<\/svg>/g)].map((m) => m[0]).join('\n');
const headline = (index.match(/<h1 id="hero-title">([\s\S]*?)<\/h1>/) || [])[1];
if (!headline || !sprites) throw new Error('index.html: the headline (h1#hero-title) or the icon sprite was not found');
writeFileSync(card, `<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="robots" content="noindex">
<link rel="stylesheet" href="styles.css">
<style>
html, body { width: 1200px; height: 630px; overflow: hidden; }
body { position: relative; }
.card__text { position: absolute; left: 80px; top: 0; bottom: 0; width: 500px; display: flex; flex-direction: column; justify-content: center; }
.card__brand { display: flex; align-items: center; gap: 14px; margin: 0 0 44px; color: var(--white); font: 500 25px/1 var(--ui); letter-spacing: -.01em; }
.card__brand img { width: 46px; height: 46px; border-radius: 12px; }
.card__text h1 { font-size: 60px; line-height: 1.05; letter-spacing: -.035em; text-wrap: balance; }
.card__sub { margin: 30px 0 0; font-size: 25px; line-height: 1.4; color: var(--muted); }
.card__phones { isolation: isolate; } /* keeps the rim's light, which sits behind its phone, in front of the page */
.card__phone { position: absolute; bottom: 24px; }
.card__phone--side { left: 622px; width: 200px; }
.card__phone--main { left: 848px; width: 280px; }
</style>
${sprites}
<div class="card__text">
<div class="card__brand"><img src="assets/flexera-icon-256.webp" alt=""><span>Flexera Launcher</span></div>
<h1>${headline}</h1>
<p class="card__sub">A free launcher for Android</p>
</div>
<div class="card__phones" data-fig>
<div class="fig__item--side"><div class="phone-host card__phone card__phone--side" data-phone="edge"></div></div>
<div class="phone-host fig__phone card__phone card__phone--main" data-phone="hero"></div>
</div>
<script src="script.js"></script>
</html>`);
const profile = mkdtempSync(join(tmpdir(), 'flexera-og-'));
const chrome = spawn(CHROME, ['--headless=new', '--disable-gpu', '--hide-scrollbars', `--remote-debugging-port=${PORT}`, `--user-data-dir=${profile}`, '--window-size=1200,630', 'about:blank'], { stdio: 'ignore' });
try {
let page;
for (let i = 0; i < 60 && !page; i++) {
try {
page = (await (await fetch(`http://127.0.0.1:${PORT}/json`)).json()).find((t) => t.type === 'page');
} catch (_) { /* Chrome is not up yet */ }
if (!page) await sleep(200);
}
if (!page) throw new Error(`Chrome did not start (${CHROME}); set CHROME to its path`);
const ws = new WebSocket(page.webSocketDebuggerUrl);
await new Promise((res, rej) => { ws.onopen = res; ws.onerror = rej; });
let id = 0;
const waiting = new Map();
ws.onmessage = (m) => {
const msg = JSON.parse(m.data);
if (!waiting.has(msg.id)) return;
const { res, rej } = waiting.get(msg.id);
waiting.delete(msg.id);
if (msg.error) rej(new Error(JSON.stringify(msg.error))); else res(msg.result);
};
const send = (method, params = {}) => new Promise((res, rej) => { waiting.set(++id, { res, rej }); ws.send(JSON.stringify({ id, method, params })); });
await send('Page.enable');
await send('Emulation.setDeviceMetricsOverride', { width: 1200, height: 630, deviceScaleFactor: 1, mobile: false });
await send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-reduced-motion', value: 'reduce' }] }); // the stills, with no entrance
await send('Page.navigate', { url: pathToFileURL(card).href });
await sleep(600);
await send('Runtime.evaluate', { expression: 'document.fonts.ready.then(() => new Promise((r) => setTimeout(r, 700)))', awaitPromise: true });
const shot = await send('Page.captureScreenshot', { format: 'jpeg', quality: 90 });
writeFileSync(out, Buffer.from(shot.data, 'base64'));
console.log(`wrote ${out} (${Math.round(Buffer.from(shot.data, 'base64').length / 1024)} KB), headline: ${headline.replace(/<[^>]+>/g, '')}`);
try { await send('Browser.close'); } catch (_) { /* gone already */ }
} finally {
chrome.kill();
rmSync(card, { force: true });
await sleep(300);
try { rmSync(profile, { recursive: true, force: true }); } catch (_) { /* Chrome may still hold it; it is in the temp folder */ }
}
+41
View File
@@ -0,0 +1,41 @@
// Makes WEBSITE/PRODUCTION, the folder to upload: the page, its stylesheet and script, and only
// the pictures and fonts those three actually load, each font with its licence beside it.
//
// node flexera/website/make-production.mjs
//
// The folder is a copy. It is emptied and filled again on every run, so run this after any change
// to the website and never edit the copy. Needs Node 22 or newer, nothing to install.
import { readFileSync, rmSync, mkdirSync, copyFileSync, existsSync, statSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const here = dirname(fileURLToPath(import.meta.url));
const site = resolve(here, '..', '..', 'WEBSITE');
const out = join(site, 'PRODUCTION');
const pages = ['index.html', 'styles.css', 'script.js'];
// every assets/... and fonts/... file the three name
const text = pages.map((f) => readFileSync(join(site, f), 'utf8')).join('\n');
const used = new Set([...text.matchAll(/\b(?:assets|fonts)\/[A-Za-z0-9._-]+\.[a-z0-9]+/g)].map((m) => m[0]));
for (const f of [...used]) { // a font goes out with its licence: fonts/outfit.woff2 -> fonts/outfit-OFL.txt
const licence = f.replace(/\.woff2?$/, '-OFL.txt');
if (f.startsWith('fonts/') && licence !== f && existsSync(join(site, licence))) used.add(licence);
}
const missing = [...used].filter((f) => !existsSync(join(site, f)));
if (missing.length) throw new Error(`the site names files that are not there: ${missing.join(', ')}`);
rmSync(out, { recursive: true, force: true });
const files = [...pages, ...[...used].sort()];
let bytes = 0;
for (const f of files) {
mkdirSync(dirname(join(out, f)), { recursive: true });
copyFileSync(join(site, f), join(out, f));
const size = statSync(join(out, f)).size;
bytes += size;
console.log(`${String(Math.ceil(size / 1024)).padStart(5)} KB ${f}`);
}
console.log(`${files.length} files, ${Math.ceil(bytes / 1024)} KB, in ${out}`);
// Link previews only show the picture when the page gives its full address.
const og = (text.match(/property="og:image" content="([^"]*)"/) || [])[1] || '';
if (!/^https?:\/\//.test(og)) console.log(`\nNOTE: og:image is "${og}", not a full address, so link previews will show no picture. See "Putting it online" in WEBSITE/README.md.`);
+4
View File
@@ -128,6 +128,10 @@ coil-compose = "io.coil-kt:coil-compose:2.7.0"
google-material = "com.google.android.material:material:1.14.0"
hoko-blur = "io.github.hokofly:hoko-blur:1.5.5"
javax-inject = "javax.inject:javax.inject:1"
# Flexera Launcher: QR code on the About screen (app.flexera.ui.FlexeraAbout).
zxing-core = "com.google.zxing:core:3.5.3"
# Flexera Launcher: reads web pages for the RSS reader's article view (app.flexera.reader.ArticleStore).
jsoup = "org.jsoup:jsoup:1.23.2"
kdrag0n-colorkt = "dev.kdrag0n:colorkt:1.0.5"
leakcanary-android = "com.squareup.leakcanary:leakcanary-android:2.14"
leakcanary-androidstudio = "com.android.tools.studio.leakcanary:leakcanary:1.0.0"
@@ -89,6 +89,11 @@ class DeviceProfileOverrides @Inject constructor(
/** Override for any other value that's not a DBGridInfo, extends this value when needed */
data class PreviewOverrides(
val foldableDatabaseHotseatIcons: Int? = null,
// Flexera Launcher: margins shown in a preview before they are kept
// (app.flexera.home.HomeMargins); read by DeviceProfile.
val homeSideMarginDp: Int? = null,
val homeTopMarginDp: Int? = null,
val homeBottomMarginDp: Int? = null,
)
data class Options(
@@ -171,9 +176,9 @@ class DeviceProfileOverrides @Inject constructor(
if (foldableDatabaseHotseatIcons > 0) {
idp.numDatabaseHotseatIcons = foldableDatabaseHotseatIcons
}
if (foldableDatabaseAllAppsColumns > 0) {
idp.numDatabaseAllAppsColumns = foldableDatabaseAllAppsColumns
}
// Flexera Launcher: no foldable override for the drawer's columns. Two-panel mode (an
// unfolded foldable) takes them from numDatabaseAllAppsColumns, and the drawer is one
// column there too (set above).
// Ensure database can hold enough icons for multi-row / multi-page dock
val requiredSlots = idp.numShownHotseatIcons * numHotseatRows * numDockPages
@@ -214,6 +214,10 @@ class LawnchairApp : LauncherApplication() {
val launcher: LawnchairLauncher?
get() = activities.filterIsInstance<LawnchairLauncher>().firstOrNull()
// Flexera Launcher: see LawnchairApp.launchers.
val launchers: List<LawnchairLauncher>
get() = activities.filterIsInstance<LawnchairLauncher>()
fun finishAll() {
HashSet(activities).forEach { it.finish() }
}
@@ -292,6 +296,14 @@ class LawnchairApp : LauncherApplication() {
@JvmStatic
val launcher: LawnchairLauncher? get() = instance.activityHandler.launcher
/**
* Flexera Launcher: every copy of the launcher that is open. There are two when it was
* opened like an app (from the installer's "Open", say) and then made the home app: one
* in the app's own task and one as the home screen. [launcher] picks either of them.
*/
@JvmStatic
val launchers: List<LawnchairLauncher> get() = instance.activityHandler.launchers
@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class)
fun Launcher.showQuickstepWarningIfNecessary() {
val launcher = this
@@ -120,7 +120,11 @@ class LawnchairLauncher : QuickstepLauncher() {
private val rememberPositionStateListener = object : StateManager.StateListener<LauncherState> {
override fun onStateTransitionStart(toState: LauncherState) {
if (toState is AllAppsState) {
mAppsView.activeRecyclerView.restoreScrollPosition()
// Flexera Launcher: note where the list stands rather than send it back to where a
// finger last left it. Nothing moves a closed drawer's list while it remembers its
// place, so the list is still where it was left, a letter chosen on the alphabet
// included. A scrub from a swipe that was a mistake goes back to this note.
mAppsView.activeRecyclerView.saveScrollPosition()
}
}
override fun onStateTransitionComplete(finalState: LauncherState) {}
@@ -283,7 +287,8 @@ class LawnchairLauncher : QuickstepLauncher() {
super.getSupportedShortcuts(container),
Stream.concat(
Stream.of(LawnchairShortcut.UNINSTALL, LawnchairShortcut.CUSTOMIZE, LawnchairShortcut.OPEN_IN_STORE),
Stream.of(LawnchairShortcut.PAUSE_APPS),
// Flexera Launcher: "Hide app", which its factory offers in the app list only.
Stream.of(LawnchairShortcut.PAUSE_APPS, app.flexera.drawer.HideApp.SHORTCUT),
),
)
@@ -517,7 +522,10 @@ class LawnchairLauncher : QuickstepLauncher() {
fun recreateIfNotScheduled() {
if (sRestartFlags == 0) {
recreate()
// Flexera Launcher: every open copy, not only this one. A changed setting used to
// rebuild whichever copy LawnchairApp.launcher happened to return, which could be
// the one in the background, and the home screen kept its old look until restart.
(LawnchairApp.launchers + this).distinct().forEach { it.recreate() }
}
}
@@ -191,7 +191,7 @@ class AllAppsSearchInput(context: Context, attrs: AttributeSet?) :
}
// Flexera Launcher: the drawer has no background panel, so the search field keeps
// its own pill while typing; without it the dark text sits on the wallpaper.
// its own pill while typing; without it the text sits on the wallpaper.
val backgroundAlpha by animateIntAsState(
if ((isFocused || !queryEmpty) && !app.flexera.drawer.FlexeraDrawer.KEEP_SEARCH_FIELD_BACKGROUND) 0 else 100,
)
@@ -242,7 +242,10 @@ class AllAppsSearchInput(context: Context, attrs: AttributeSet?) :
},
)
LawnchairTheme {
// Flexera Launcher: dark, as the field is inflated with the dark theme
// (LawnchairSearchUiDelegate). The light scheme's press ripple is dark and did not
// show on the dark pill.
LawnchairTheme(darkTheme = true) {
ProvideLifecycleState {
LawnQsbUi(
state = state,
@@ -16,6 +16,7 @@ import app.lawnchair.gestures.handlers.OpenAppTarget
import app.lawnchair.gestures.handlers.OpenAssistantHandler
import app.lawnchair.gestures.handlers.OpenNotificationsHandler
import app.lawnchair.gestures.handlers.OpenQuickSettingsHandler
import app.lawnchair.gestures.handlers.OpenRssReaderGestureHandler
import app.lawnchair.gestures.handlers.OpenSearchGestureHandler
import app.lawnchair.gestures.handlers.RecentsGestureHandler
import app.lawnchair.gestures.handlers.SleepGestureHandler
@@ -129,6 +130,18 @@ sealed class GestureHandlerConfig {
override val iconRes = R.drawable.ic_mic_flat
}
// Flexera Launcher: the RSS reader's page (app.flexera.reader.ReaderPage). A swipe past the
// first or the last home screen page brings it in with the finger (app.flexera.home.QuickLaunch);
// other gestures, and a shortcut on the home screen, bring it in on their own.
@Serializable
@SerialName("flexeraRssReader")
data object OpenRssReader :
Simple(R.string.flexera_gesture_open_rss_reader, ::OpenRssReaderGestureHandler) {
override val iconRes = R.drawable.ic_flexera_rss
override fun isExternallyInvokable() = true
}
@Serializable
@SerialName("openApp")
data class OpenApp(val appName: String, val target: OpenAppTarget) : GestureHandlerConfig() {
@@ -32,6 +32,9 @@ sealed class GestureHandlerOption(
data object OpenSearch : Simple(GestureHandlerConfig.OpenSearch)
data object OpenAssistant : Simple(GestureHandlerConfig.OpenAssistant)
// Flexera Launcher: see GestureHandlerConfig.OpenRssReader.
data object OpenRssReader : Simple(GestureHandlerConfig.OpenRssReader)
data object OpenApp : GestureHandlerOption(
R.string.gesture_handler_open_app_option,
R.drawable.ic_launcher_home,
@@ -13,6 +13,7 @@ val gestureHandlerOptions = listOf(
GestureHandlerOption.OpenAppSearch,
GestureHandlerOption.OpenSearch,
GestureHandlerOption.OpenApp,
GestureHandlerOption.OpenRssReader, // Flexera Launcher
GestureHandlerOption.OpenAssistant,
)
@@ -51,6 +51,7 @@ import app.lawnchair.util.navigationBarsOrDisplayCutoutPadding
import com.android.launcher3.LauncherAppState
import com.android.launcher3.LauncherState
import com.android.launcher3.R
import com.android.launcher3.pm.UserCache
import com.android.launcher3.util.ComponentKey
import com.google.accompanist.drawablepainter.rememberDrawablePainter
import kotlinx.coroutines.launch
@@ -190,6 +191,10 @@ fun CustomizeAppDialog(
description = componentKey.componentName.flattenToString(),
showDescription = showComponentNames,
) {
// Flexera Launcher: no switch for an app in Private Space. The list's Private Space
// section ignores the hidden list, so the app would stay in view; locking the space is
// what hides its apps. "Hide app" (app.flexera.drawer.HideApp) leaves them out too.
if (UserCache.INSTANCE.get(context).getUserInfo(componentKey.user).isPrivate) return@PreferenceGroup
val stringKey = componentKey.toString()
SwitchPreference(
checked = hiddenApps.contains(stringKey),
@@ -218,7 +218,14 @@ class PreferenceManager @Inject constructor(
val flexeraAlphabetOnLeft = BoolPref("pref_flexeraAlphabetOnLeft", false, recreate)
// Flexera Launcher: whether a slide along the home screen's edge opens the drawer at a letter (PRD AD-10).
val flexeraScrubFromHome = BoolPref("pref_flexeraScrubFromHome", false)
// On unless switched off, by the owner's decision of 12 November 2026.
val flexeraScrubFromHome = BoolPref("pref_flexeraScrubFromHome", true)
// Flexera Launcher: whether drawer rows show the app's latest notification under its name (PRD AD-11).
val flexeraNotificationPreviews = BoolPref("pref_flexeraNotificationPreviews", true, recreate)
// Flexera Launcher: how large the rows of the drawer list are, "compact" or "comfy" (FlexeraDrawer.RowSize).
val flexeraDrawerRowSize = StringPref("pref_flexeraDrawerRowSize", "compact", recreate)
override fun close() {
TODO("Not yet implemented")
@@ -874,6 +874,74 @@ class PreferenceManager2 @Inject constructor(
defaultValue = GestureHandlerConfig.NoOp,
)
// Flexera Launcher: quick launch. What a swipe on from the first home screen page, towards
// the page that is not there, does; and the same past the last page (app.flexera.home.QuickLaunch).
val firstPageSwipeGestureHandler = serializablePreference<GestureHandlerConfig>(
key = stringPreferencesKey("flexera_first_page_swipe_gesture_handler"),
defaultValue = GestureHandlerConfig.NoOp,
)
val lastPageSwipeGestureHandler = serializablePreference<GestureHandlerConfig>(
key = stringPreferencesKey("flexera_last_page_swipe_gesture_handler"),
defaultValue = GestureHandlerConfig.NoOp,
)
// Flexera Launcher: whether the edges of every widget meet the edges of the icons in the
// rows and columns it covers, as the launcher's own widgets do
// (app.flexera.widget.FlexeraWidgets.appWidgetPadding). Read with the grid.
val alignWidgetsWithIcons = preference(
key = booleanPreferencesKey(name = "flexera_align_widgets_with_icons"),
defaultValue = true,
onSet = { reloadHelper.reloadGrid() },
)
// Flexera Launcher: the home screen's margins in dp, in place of the padding factors
// workspacePaddingHorizontalFactor and workspacePaddingVerticalFactor (app.flexera.home.HomeMargins).
val homeSideMargin = preference(
key = intPreferencesKey(name = "flexera_home_side_margin"),
defaultValue = app.flexera.home.HomeMargins.DEFAULT_SIDE_DP,
onSet = { reloadHelper.reloadGrid() },
)
val homeTopMargin = preference(
key = intPreferencesKey(name = "flexera_home_top_margin"),
defaultValue = 0,
onSet = { reloadHelper.reloadGrid() },
)
val homeBottomMargin = preference(
key = intPreferencesKey(name = "flexera_home_bottom_margin"),
defaultValue = 0,
onSet = { reloadHelper.reloadGrid() },
)
// Flexera Launcher: whether the home screen behind an open folder is blurred
// (app.flexera.home.FolderBlur). Read when a folder opens, so nothing has to be reloaded.
val folderBlur = preference(
key = booleanPreferencesKey(name = "flexera_folder_blur"),
defaultValue = true,
)
// Flexera Launcher: whether a folder on the home screen opens full screen, with its apps at
// the bottom of the screen (app.flexera.home.FullScreenFolders). Read when a folder opens.
val fullScreenFolders = preference(
key = booleanPreferencesKey(name = "flexera_full_screen_folders"),
defaultValue = true,
)
// Flexera Launcher: how many columns a full-screen folder has
// (app.flexera.home.FullScreenFolders.columns); 0, the default, is as many as the home
// screen has. Read when a folder opens, so nothing has to be reloaded.
val fullScreenFolderColumns = preference(
key = intPreferencesKey(name = "flexera_full_screen_folder_columns"),
defaultValue = 0,
)
// Flexera Launcher: the RSS reader's feeds (app.flexera.reader.RssFeed), in the owner's
// order. Here rather than in a file of the reader's own so that a backup carries them.
val rssFeeds = serializablePreference<List<app.flexera.reader.RssFeed>>(
key = stringPreferencesKey("flexera_rss_feeds"),
defaultValue = emptyList(),
)
val autoUpdaterNightly = preference(
key = booleanPreferencesKey(name = "enable_nightly_auto_updater"),
defaultValue = if (BuildConfig.APPLICATION_ID.contains("nightly")) {
@@ -900,10 +968,16 @@ class PreferenceManager2 @Inject constructor(
.onEach { cachedPreferences = it }
.launchIn(scope)
// Flexera Launcher: in the five collectors below, distinctUntilChanged comes before
// drop(1). Upstream has them the other way round, which lets the first emission after
// the dropped one through whatever its value: the first write of any preference after
// the launcher started then reloaded the model, rebuilt the grid three times and
// recreated the launcher. Hiding an app from the app list is such a write, made while
// the owner looks at the launcher.
initializeIconShape(iconShape.firstCached(this))
iconShape.get()
.drop(1)
.distinctUntilChanged()
.drop(1) // Flexera Launcher: after distinctUntilChanged, not before.
.onEach { shape ->
initializeIconShape(shape)
L3ThemeManager.INSTANCE.get(context)
@@ -912,14 +986,14 @@ class PreferenceManager2 @Inject constructor(
.launchIn(scope)
hotseatMode.get()
.drop(1)
.distinctUntilChanged()
.drop(1) // Flexera Launcher: after distinctUntilChanged, not before.
.onEach { reloadHelper.restart() }
.launchIn(scope)
isHotseatEnabled.get()
.drop(1)
.distinctUntilChanged()
.drop(1) // Flexera Launcher: after distinctUntilChanged, not before.
.onEach {
reloadHelper.recreate()
reloadHelper.reloadGrid()
@@ -927,14 +1001,14 @@ class PreferenceManager2 @Inject constructor(
.launchIn(scope)
hotseatQsbProvider.get()
.drop(1)
.distinctUntilChanged()
.drop(1) // Flexera Launcher: after distinctUntilChanged, not before.
.onEach { reloadHelper.recreate() }
.launchIn(scope)
enableLabelInDock.get()
.drop(1)
.distinctUntilChanged()
.drop(1) // Flexera Launcher: after distinctUntilChanged, not before.
.onEach { reloadHelper.reloadGrid() }
.launchIn(scope)
}
@@ -38,6 +38,11 @@ class LawnchairSearchAdapterProvider(
append(SEARCH_RESULT_EMPTY_STATE, R.layout.search_result_empty_state)
append(SEARCH_RESULT_SEARCH_SETTINGS, R.layout.search_result_search_settings)
}
// Flexera Launcher: the results lie on the drawer's backdrop, which is dark whatever the theme,
// so they are inflated with the dark theme (FlexeraDrawer.backdropContext).
private val resultContext by lazy { app.flexera.drawer.FlexeraDrawer.backdropContext(appsView.context) }
private var quickLaunchItem: SearchResultView? = null
set(value) {
field = value
@@ -69,7 +74,8 @@ class LawnchairSearchAdapterProvider(
parent: ViewGroup?,
viewType: Int,
): BaseAllAppsAdapter.ViewHolder {
val view = layoutInflater.inflate(layoutIdMap[viewType], parent, false)
// Flexera Launcher: in the dark theme; see resultContext.
val view = layoutInflater.cloneInContext(resultContext).inflate(layoutIdMap[viewType], parent, false)
val grid: DeviceProfile = mLauncher.deviceProfile
val leftMargin = grid.allAppsPadding.left
val rightMargin = grid.allAppsPadding.right
@@ -1,5 +1,7 @@
package app.lawnchair.search
import android.view.View
import com.android.launcher3.R
import com.android.launcher3.allapps.ActivityAllAppsContainerView
import com.android.launcher3.allapps.search.AllAppsSearchUiDelegate
import com.android.launcher3.allapps.search.SearchAdapterProvider
@@ -10,4 +12,12 @@ class LawnchairSearchUiDelegate(private val appsView: ActivityAllAppsContainerVi
override fun createMainAdapterProvider(): SearchAdapterProvider<*> {
return LawnchairSearchAdapterProvider(ActivityContext.lookupContext(appsView.context), appsView)
}
// Flexera Launcher: the search field lies on the drawer's backdrop, which is dark whatever the
// theme, so it is inflated with the dark theme, like the results (FlexeraDrawer.backdropContext).
// In the light theme its grey placeholder could hardly be read on the pill. The field makes the
// search algorithm with its own context, so the cards and icons the search draws are dark too.
override fun inflateSearchBar(): View = layoutInflater
.cloneInContext(app.flexera.drawer.FlexeraDrawer.backdropContext(appsView.context))
.inflate(R.layout.search_container_all_apps, appsView, false)
}
@@ -1,6 +1,7 @@
package app.lawnchair.ui.preferences.components
import android.content.res.Configuration
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.fillMaxSize
@@ -26,6 +27,8 @@ fun ColumnScope.GridOverridesPreview(
modifier: Modifier = Modifier,
expandToAvailableSpace: Boolean = true,
previewOverrides: DeviceProfileOverrides.PreviewOverrides = DeviceProfileOverrides.PreviewOverrides(),
// Flexera Launcher: drawn over the preview, such as the margins (app.flexera.home.HomeMargins).
overlay: @Composable BoxScope.(InvariantDeviceProfile) -> Unit = {},
updateGridOptions: DeviceProfileOverrides.DBGridInfo.() -> DeviceProfileOverrides.DBGridInfo,
) {
val previewIdp = createPreviewIdp(updateGridOptions, previewOverrides)
@@ -81,6 +84,7 @@ fun ColumnScope.GridOverridesPreview(
idp = previewIdp,
modifier = Modifier.fillMaxSize(),
)
overlay(previewIdp)
}
}
}
@@ -40,6 +40,12 @@ fun BackupAndRestorePreference(
subtitle = stringResource(R.string.restore_nova_backup_description),
onClick = restoreNovaBackupOpener(),
)
// Flexera Launcher: home screens from a Smart Launcher backup (app.flexera.backup).
ClickablePreference(
label = stringResource(R.string.flexera_import_smart_launcher),
subtitle = stringResource(R.string.flexera_import_smart_launcher_description),
onClick = app.flexera.backup.smartLauncherImportOpener(),
)
}
}
}
@@ -20,8 +20,10 @@ import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import app.flexera.home.FullScreenFolders
import app.lawnchair.preferences.getAdapter
import app.lawnchair.preferences.preferenceManager
import app.lawnchair.preferences.rememberTransformAdapter
import app.lawnchair.preferences2.preferenceManager2
import app.lawnchair.ui.preferences.LocalIsExpandedScreen
import app.lawnchair.ui.preferences.components.NavigationActionPreference
@@ -32,7 +34,9 @@ import app.lawnchair.ui.preferences.components.layout.ExpandAndShrink
import app.lawnchair.ui.preferences.components.layout.PreferenceGroup
import app.lawnchair.ui.preferences.components.layout.PreferenceLayout
import app.lawnchair.ui.preferences.navigation.GeneralIconShape
import com.android.launcher3.InvariantDeviceProfile
import com.android.launcher3.R
import com.android.launcher3.Utilities
@Composable
fun FolderPreferences(
@@ -51,7 +55,16 @@ fun FolderPreferences(
.firstOrNull { it.value == folderIconShapeAdapter.state.value }
?.label?.invoke()
?: stringResource(id = R.string.custom)
// Flexera Launcher: full-screen folders have no panel, and columns of their own, so the
// panel's opacity and the floating folder's column count are hidden while they are on.
val fullScreenFoldersAdapter = prefs2.fullScreenFolders.getAdapter()
PreferenceGroup(heading = stringResource(id = R.string.general_label)) {
// Flexera Launcher: full-screen folders (app.flexera.home.FullScreenFolders).
SwitchPreference(
adapter = fullScreenFoldersAdapter,
label = stringResource(id = R.string.flexera_full_screen_folders),
description = stringResource(id = R.string.flexera_full_screen_folders_description),
)
NavigationActionPreference(
label = stringResource(id = R.string.folder_shape_label),
destination = GeneralIconShape(ShapeRoute.FOLDER_SHAPE),
@@ -68,21 +81,50 @@ fun FolderPreferences(
valueRange = 0F..1F,
showAsPercentage = true,
)
SliderPreference(
label = stringResource(id = R.string.folder_bg_opacity_label),
adapter = prefs2.folderBackgroundOpacity.getAdapter(),
step = 0.1F,
valueRange = 0F..1F,
showAsPercentage = true,
)
// Flexera Launcher: hidden for full-screen folders; see fullScreenFoldersAdapter.
ExpandAndShrink(visible = !fullScreenFoldersAdapter.state.value) {
SliderPreference(
label = stringResource(id = R.string.folder_bg_opacity_label),
adapter = prefs2.folderBackgroundOpacity.getAdapter(),
step = 0.1F,
valueRange = 0F..1F,
showAsPercentage = true,
)
}
// Flexera Launcher: blurring a view needs Android 12.
if (Utilities.ATLEAST_S) {
SwitchPreference(
adapter = prefs2.folderBlur.getAdapter(),
label = stringResource(id = R.string.flexera_folder_blur),
description = stringResource(id = R.string.flexera_folder_blur_description),
)
}
}
PreferenceGroup(heading = stringResource(id = R.string.grid)) {
SliderPreference(
label = stringResource(id = R.string.max_folder_columns),
adapter = prefs2.folderColumns.getAdapter(),
step = 1,
valueRange = 2..5,
)
// Flexera Launcher: a full-screen folder has columns of its own
// (app.flexera.home.FullScreenFolders.columns), as many as the home screen's until
// the owner picks a number; the floating folder's slider is hidden meanwhile.
ExpandAndShrink(visible = fullScreenFoldersAdapter.state.value) {
val homeColumns = InvariantDeviceProfile.INSTANCE.get(context).numColumns
SliderPreference(
label = stringResource(id = R.string.columns),
adapter = rememberTransformAdapter(
adapter = prefs2.fullScreenFolderColumns.getAdapter(),
transformGet = { if (it > 0) it else homeColumns },
transformSet = { it },
),
step = 1,
valueRange = FullScreenFolders.MIN_COLUMNS..maxOf(FullScreenFolders.MAX_COLUMNS, homeColumns),
)
}
ExpandAndShrink(visible = !fullScreenFoldersAdapter.state.value) {
SliderPreference(
label = stringResource(id = R.string.max_folder_columns),
adapter = prefs2.folderColumns.getAdapter(),
step = 1,
valueRange = 2..5,
)
}
SliderPreference(
label = stringResource(id = R.string.max_folder_rows),
adapter = prefs.folderRows.getAdapter(),
@@ -1,16 +1,20 @@
package app.lawnchair.ui.preferences.destinations
import android.os.Build
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import app.lawnchair.gestures.handlers.SleepMode
import app.lawnchair.preferences.getAdapter
import app.lawnchair.preferences2.preferenceManager2
import app.lawnchair.ui.preferences.LocalIsExpandedScreen
import app.lawnchair.ui.preferences.components.GestureHandlerPreference
import app.lawnchair.ui.preferences.components.NavigationActionPreference
import app.lawnchair.ui.preferences.components.controls.ListPreference
import app.lawnchair.ui.preferences.components.layout.PreferenceGroup
import app.lawnchair.ui.preferences.components.layout.PreferenceLayout
import app.lawnchair.ui.preferences.navigation.GesturesRssReader
import com.android.launcher3.R
@Composable
@@ -53,6 +57,36 @@ fun GesturePreferences(
label = stringResource(id = R.string.gesture_back_tap),
)
}
// Flexera Launcher: quick launch, a swipe on past the first or the last home screen page
// (app.flexera.home.QuickLaunch). It rides on Android's own page stretch, new in Android 12.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PreferenceGroup(
heading = stringResource(id = R.string.flexera_quick_launch),
description = stringResource(id = R.string.flexera_quick_launch_description),
) {
GestureHandlerPreference(
adapter = prefs.firstPageSwipeGestureHandler.getAdapter(),
label = stringResource(id = R.string.flexera_quick_launch_first_page),
)
GestureHandlerPreference(
adapter = prefs.lastPageSwipeGestureHandler.getAdapter(),
label = stringResource(id = R.string.flexera_quick_launch_last_page),
)
}
}
// Flexera Launcher: the RSS reader's feeds (app.flexera.reader.RssReaderSettings); the
// reader opens with any gesture above set to it.
val rssFeeds = prefs.rssFeeds.getAdapter().state.value
PreferenceGroup(
heading = stringResource(id = R.string.flexera_rss_reader),
description = stringResource(id = R.string.flexera_rss_gestures_description),
) {
NavigationActionPreference(
label = stringResource(id = R.string.flexera_rss_feeds_heading),
destination = GesturesRssReader,
subtitle = pluralStringResource(id = R.plurals.flexera_rss_feed_count, count = rssFeeds.size, rssFeeds.size),
)
}
PreferenceGroup(heading = stringResource(id = R.string.sleep_mode_label)) {
ListPreference(
adapter = prefs.sleepMode.getAdapter(),
@@ -22,9 +22,12 @@ import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
@@ -35,6 +38,7 @@ import app.lawnchair.DeviceProfileOverrides
import app.lawnchair.preferences.asPreferenceAdapter
import app.lawnchair.preferences.getAdapter
import app.lawnchair.preferences.preferenceManager
import app.lawnchair.preferences2.preferenceManager2
import app.lawnchair.ui.preferences.LocalIsExpandedScreen
import app.lawnchair.ui.preferences.LocalNavController
import app.lawnchair.ui.preferences.components.GridOverridesPreview
@@ -78,6 +82,21 @@ fun HomeScreenGridPreferences(
mutableIntStateOf(originalHotseatColumnsUnfolded.coerceAtLeast(originalHotseatColumns))
}
// Flexera Launcher: the home screen's margins, shown in the preview and kept on Apply with
// the grid (app.flexera.home.HomeMargins).
val prefs2 = preferenceManager2()
val sideMarginAdapter = prefs2.homeSideMargin.getAdapter()
val topMarginAdapter = prefs2.homeTopMargin.getAdapter()
val bottomMarginAdapter = prefs2.homeBottomMargin.getAdapter()
val originalSideMargin = remember { sideMarginAdapter.state.value }
val originalTopMargin = remember { topMarginAdapter.state.value }
val originalBottomMargin = remember { bottomMarginAdapter.state.value }
val sideMargin = rememberSaveable { mutableIntStateOf(originalSideMargin) }
val topMargin = rememberSaveable { mutableIntStateOf(originalTopMargin) }
val bottomMargin = rememberSaveable { mutableIntStateOf(originalBottomMargin) }
// Whether the previewed grid has room for less than these margins.
var marginsLimited by remember { mutableStateOf(false) }
LaunchedEffect(hotseatColumns.intValue) {
if (hotseatColumnsUnfolded.intValue < hotseatColumns.intValue) {
hotseatColumnsUnfolded.intValue = hotseatColumns.intValue
@@ -101,7 +120,8 @@ fun HomeScreenGridPreferences(
// This should be enough for 3 preferences, they can't scroll beyond this.
// Should you introduce another prefs, raise the value by a little so that they
// have an indication that you can scroll the entries.
isPortrait -> (maxHeight * 0.40f).coerceAtLeast(315.dp)
// Flexera Launcher: raised from 0.40 for the margins below the grid.
isPortrait -> (maxHeight * 0.46f).coerceAtLeast(315.dp)
// Landscape mode
else -> (maxHeight * 0.52f).coerceAtLeast(280.dp)
@@ -125,12 +145,21 @@ fun HomeScreenGridPreferences(
numHotseatColumns = hotseatColumns.intValue,
)
},
previewOverrides = if (isFoldable) {
DeviceProfileOverrides.PreviewOverrides(
foldableDatabaseHotseatIcons = hotseatColumnsUnfolded.intValue,
)
} else {
DeviceProfileOverrides.PreviewOverrides()
previewOverrides = DeviceProfileOverrides.PreviewOverrides(
foldableDatabaseHotseatIcons = if (isFoldable) hotseatColumnsUnfolded.intValue else null,
homeSideMarginDp = sideMargin.intValue,
homeTopMarginDp = topMargin.intValue,
homeBottomMarginDp = bottomMargin.intValue,
),
// Flexera Launcher: the margins drawn over the preview, and whether they fit.
overlay = { idp ->
app.flexera.home.HomeMargins.Guides(idp)
val context = LocalContext.current
LaunchedEffect(idp) {
marginsLimited = app.flexera.home.HomeMargins.isLimited(
context, idp, sideMargin.intValue, topMargin.intValue, bottomMargin.intValue,
)
}
},
)
@@ -208,6 +237,15 @@ fun HomeScreenGridPreferences(
)
}
}
// Flexera Launcher: the margins, below the grid.
PreferenceGroup(heading = stringResource(id = R.string.flexera_home_margins)) {
app.flexera.home.HomeMargins.Preferences(
side = sideMargin.asPreferenceAdapter(),
top = topMargin.asPreferenceAdapter(),
bottom = bottomMargin.asPreferenceAdapter(),
limited = marginsLimited,
)
}
}
val navController = LocalNavController.current
@@ -219,6 +257,10 @@ fun HomeScreenGridPreferences(
hotseatColumnsAdapter.onChange(hotseatColumns.intValue)
hotseatColumnsUnfoldedAdapter.onChange(hotseatColumnsUnfolded.intValue)
}
// Flexera Launcher: the margins, which reload the grid again once kept.
sideMarginAdapter.onChange(sideMargin.intValue)
topMarginAdapter.onChange(topMargin.intValue)
bottomMarginAdapter.onChange(bottomMargin.intValue)
InvariantDeviceProfile.INSTANCE.get(context).onPreferencesChanged(context)
navController.popBackStack()
}
@@ -226,7 +268,10 @@ fun HomeScreenGridPreferences(
val isChanged = columns.intValue != originalColumns ||
rows.intValue != originalRows ||
hotseatColumns.intValue != originalHotseatColumns ||
hotseatColumnsUnfolded.intValue != originalHotseatColumnsUnfolded
hotseatColumnsUnfolded.intValue != originalHotseatColumnsUnfolded ||
sideMargin.intValue != originalSideMargin ||
topMargin.intValue != originalTopMargin ||
bottomMargin.intValue != originalBottomMargin
Box(
modifier = Modifier
@@ -189,20 +189,9 @@ fun HomeScreenPreferences(
destination = HomeScreenGrid,
subtitle = stringResource(id = R.string.x_by_y, columns, rows),
)
SliderPreference(
label = stringResource(id = R.string.horizontal_padding_label),
adapter = prefs2.workspacePaddingHorizontalFactor.getAdapter(),
step = 0.05f,
valueRange = 0F..2F,
showAsPercentage = true,
)
SliderPreference(
label = stringResource(id = R.string.vertical_padding_label),
adapter = prefs2.workspacePaddingVerticalFactor.getAdapter(),
step = 0.05f,
valueRange = 0F..2F,
showAsPercentage = true,
)
// Flexera Launcher: Horizontal and Vertical padding scaled margins too small to see.
// The margins in dp that replace them are on the grid page, with its preview
// (app.flexera.home.HomeMargins).
SwitchPreference(
adapter = lockHomeScreenAdapter,
label = stringResource(id = R.string.home_screen_lock),
@@ -285,13 +274,24 @@ fun HomeScreenPreferences(
label = stringResource(id = R.string.force_widget_resize_label),
description = stringResource(id = R.string.force_widget_resize_description),
)
SliderPreference(
label = stringResource(id = R.string.widget_padding_label),
adapter = prefs2.widgetPaddingFactor.getAdapter(),
step = 0.05f,
valueRange = 0F..2F,
showAsPercentage = true,
// Flexera Launcher: widgets lined up with the icons; Lawnchair's padding is for
// when they are not (app.flexera.widget.FlexeraWidgets.appWidgetPadding).
val alignWidgetsAdapter = prefs2.alignWidgetsWithIcons.getAdapter()
SwitchPreference(
adapter = alignWidgetsAdapter,
label = stringResource(id = R.string.flexera_align_widgets),
description = stringResource(id = R.string.flexera_align_widgets_description),
)
// Flexera Launcher: hidden for aligned widgets; see alignWidgetsAdapter.
ExpandAndShrink(visible = !alignWidgetsAdapter.state.value) {
SliderPreference(
label = stringResource(id = R.string.widget_padding_label),
adapter = prefs2.widgetPaddingFactor.getAdapter(),
step = 0.05f,
valueRange = 0F..2F,
showAsPercentage = true,
)
}
}
}
}
@@ -14,6 +14,7 @@ import androidx.navigation.compose.composable
import androidx.navigation.navDeepLink
import androidx.navigation.toRoute
import app.lawnchair.backup.ui.CreateBackupScreen
import app.flexera.backup.smartLauncherImportGraph
import app.lawnchair.backup.ui.restoreBackupGraph
import app.lawnchair.backup.ui.restoreNovaBackupGraph
import app.lawnchair.preferences.BasePreferenceManager
@@ -80,7 +81,15 @@ fun PreferenceNavigation(
// TODO: navigate to nav3: https://developer.android.com/guide/navigation/navigation-3
NavHost(
navController = navController,
startDestination = startDestination,
// Flexera Launcher: a screen that opens a file is reached from inside the settings, once
// the owner has picked the file. Other apps can start the settings at any route; at one
// of these they could choose the file that replaces the home screens, or end the
// launcher's process with a route that does not decode, so from them the settings open
// at their main page instead.
startDestination = when (startDestination) {
is RestoreBackup, is RestoreNovaBackup, is ImportSmartLauncherBackup -> Root
else -> startDestination
},
enterTransition = { materialSharedAxisXIn(!isRtl, slideDistance) },
exitTransition = { materialSharedAxisXOut(!isRtl, slideDistance) },
popEnterTransition = { materialSharedAxisXIn(isRtl, slideDistance) },
@@ -198,6 +207,10 @@ fun PreferenceNavigation(
deepLinks = getDeepLink(Gestures),
) { GesturePreferences() }
composable<GesturesPickApp> { PickAppForGesture() }
// Flexera Launcher: the RSS reader's feeds.
composable<GesturesRssReader>(
deepLinks = getDeepLink(GesturesRssReader),
) { app.flexera.reader.RssReaderSettings() }
composable<Quickstep>(
deepLinks = getDeepLink(Quickstep),
@@ -252,5 +265,6 @@ fun PreferenceNavigation(
restoreBackupGraph()
restoreNovaBackupGraph()
smartLauncherImportGraph() // Flexera Launcher: Smart Launcher import
}
}
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff. Show more