**! ! Warning**: Do not merge before testing every API call and database
read involving JSON !
**Gson** is obsolete and has been superseded by **Moshi**. But more
importantly, parsing Kotlin objects using Gson is _dangerous_ because
Gson uses Java serialization and is **not Kotlin-aware**. This has two
main consequences:
- Fields of non-null types may end up null at runtime. Parsing will
succeed, but the code may crash later with a `NullPointerException` when
trying to access a field member;
- Default values of constructor parameters are always ignored. When
absent, reference types will be null, booleans will be false and
integers will be zero.
On the other hand, Kotlin-aware parsers like **Moshi** or **Kotlin
Serialization** will validate at parsing time that all received fields
comply with the Kotlin contract and avoid errors at runtime, making apps
more stable and schema mismatches easier to detect (as long as logs are
accessible):
- Receiving a null value for a non-null type will generate a parsing
error;
- Optional types are declared explicitly by adding a default value. **A
missing value with no default value declaration will generate a parsing
error.**
Migrating the entity declarations from Gson to Moshi will make the code
more robust but is not an easy task because of the semantic differences.
With Gson, both nullable and optional fields are represented with a null
value. After converting to Moshi, some nullable entities can become
non-null with a default value (if they are optional and not nullable),
others can stay nullable with no default value (if they are mandatory
and nullable), and others can become **nullable with a default value of
null** (if they are optional _or_ nullable _or_ both). That third option
is the safest bet when it's not clear if a field is optional or not,
except for lists which can usually be declared as non-null with a
default value of an empty list (I have yet to see a nullable array type
in the Mastodon API).
Fields that are currently declared as non-null present another
challenge. In theory, they should remain as-is and everything will work
fine. In practice, **because Gson is not aware of nullable types at
all**, it's possible that some non-null fields currently hold a null
value in some cases but the app does not report any error because the
field is not accessed by Kotlin code in that scenario. After migrating
to Moshi however, parsing such a field will now fail early if a null
value or no value is received.
These fields will have to be identified by heavily testing the app and
looking for parsing errors (`JsonDataException`) and/or by going through
the Mastodon documentation. A default value needs to be added for
missing optional fields, and their type could optionally be changed to
nullable, depending on the case.
Gson is also currently used to serialize and deserialize objects to and
from the local database, which is also challenging because backwards
compatibility needs to be preserved. Fortunately, by default Gson omits
writing null fields, so a field of type `List<T>?` could be replaced
with a field of type `List<T>` with a default value of `emptyList()` and
reading back the old data should still work. However, nullable lists
that are written directly (not as a field of another object) will still
be serialized to JSON as `"null"` so the deserializing code must still
be handling null properly.
Finally, changing the database schema is out of scope for this pull
request, so database entities that also happen to be serialized with
Gson will keep their original types even if they could be made non-null
as an improvement.
In the end this is all for the best, because the app will be more
reliable and errors will be easier to detect by showing up earlier with
a clear error message. Not to mention the performance benefits of using
Moshi compared to Gson.
- Replace Gson reflection with Moshi Kotlin codegen to generate all
parsers at compile time.
- Replace custom `Rfc3339DateJsonAdapter` with the one provided by
moshi-adapters.
- Replace custom `JsonDeserializer` classes for Enum types with
`EnumJsonAdapter.create(T).withUnknownFallback()` from moshi-adapters to
support fallback values.
- Replace `GuardedBooleanAdapter` with the more generic `GuardedAdapter`
which works with any type. Any nullable field may now be annotated with
`@Guarded`.
- Remove Proguard rules related to Json entities. Each Json entity needs
to be annotated with `@JsonClass` with no exception, and adding this
annotation will ensure that R8/Proguard will handle the entities
properly.
- Replace some nullable Boolean fields with non-null Boolean fields with
a default value where possible.
- Replace some nullable list fields with non-null list fields with a
default value of `emptyList()` where possible.
- Update `TimelineDao` to perform all Json conversions internally using
`Converters` so no Gson or Moshi instance has to be passed to its
methods.
- ~~Create a custom `DraftAttachmentJsonAdapter` to serialize and
deserialize `DraftAttachment` which is a special entity that supports
more than one json name per field. A custom adapter is necessary because
there is not direct equivalent of `@SerializedName(alternate = [...])`
in Moshi.~~ Remove alternate names for some `DraftAttachment` fields
which were used as a workaround to deserialize local data in 2-years old
builds of Tusky.
- Update tests to make them work with Moshi.
- Simplify a few `equals()` implementations.
- Change a few functions to `val`s
- Turn `NetworkModule` into an `object` (since it contains no abstract
methods).
Please test the app thoroughly before merging. There may be some fields
currently declared as mandatory that are actually optional.
builds upon work from #4082
Additionally fixes some deprecations and adds support for [predictive
back](https://developer.android.com/guide/navigation/custom-back/predictive-back-gesture).
I also refactored how the activity transitions work because they are
closely related to predictive back. The awkward
`finishWithoutSlideOutAnimation` is gone, activities that have been
started with slide in will now automatically close with slide out.
To test predictive back you need an emulator or device with Sdk 34
(Android 14) and then enable it in the developer settings.
Predictive back requires the back action to be determined before it
actually occurs so the system can play the right predictive animation,
which made a few reorganisations necessary.
closes#4082closes#4005
unlocks a bunch of dependency upgrades that require sdk 34
---------
Co-authored-by: Goooler <wangzongler@gmail.com>
There are some new rules, I think they mostly make sense, except for the
max line length which I had to disable because we are over it in a lot
of places.
---------
Co-authored-by: Goooler <wangzongler@gmail.com>
# Overview
In the previous code, when you open preferences, there is a section
headed "Filters" with a section called "Tabs"
This is confusing.
# Changes
- Change the section title from "Filters" to "Per-timeline preferences."
- Change the current "Tabs" section to "Home timeline" since it is only
for home timelines
# Screenshots
account preference screen | detail screen
:--: | :--:
|<image
src="https://github.com/tuskyapp/Tusky/assets/62137820/12694f24-b7e3-4ba3-90f5-53740e9c4269"
width="250" />|<image
src="https://github.com/tuskyapp/Tusky/assets/62137820/796e9ac1-76d6-43ef-a087-a1cd2d899ef8"
width="250" />
# Note
- Maybe string resources should have a new property? (for translation)
# Related link
Fixes#3536
---------
Co-authored-by: mcc <andi.m.mcclure@gmail.com>
Set the "System Design" as the default theme.
This ensures that the app's initial behaviour respect's the user's system-wide theme choice, while still allowing the user to adjust it later.
This is only done for new installs of Tusky. If the user is upgrading from a previous release and they did not have an explicit theme set then the dark theme is used, and the UX does not change.
Previously the notification filter and clear actions were shown as
buttons in the UI, with a preference that determined whether they were
displayed.
Remove this preference, and display them as menu items.
- "Filter notifications" is shown as an icon, if possible
- "Clear notifications" is only ever shown as a menu item, to reduce the
chance the user inadvertently selects it
To ensure that the options menu appears correctly, remove the code that
creates a "fake" action bar, and adjust the layouts so that there are
three toolbars;
- mainToolbar -- displays the icons, and the current "location" (Home,
Notifications, etc)
- topNav -- displays the row of tabs at the top
- bottomNav -- displays the row of tabs at the bottom
Only one of them is set as the support action bar (depending on the
user's preferences). This provides the "show a logo" and "show the
options menu" functionality as standard, without needing to re-implement
as the previous code did.
Font scaling is applied in addition to any scaling set in Android system preferences. So if the user set the Android font size to largest (a 1.3x increase) and then sets the preference to 120%, the total change is 1.56x.
Create SliderPreference to adjust the preference.
- Use Slider, which supports float values and step sizes > 1
- Display the selected value in the preference's summary
- Provide buttons to increment / decrement the value
Restart the activity if the preference changes so that the user sees the impact of the change immediately. Fix a bug in PreferencesActivity where the "EXTRA_RESTART_ON_BACK" intent was never processed. Fix this to ensure that other activities are restarted so the new font scale takes effect.
Implement the scaling in BaseActivity by overriding onAttachBaseContext, and providing a wrapped context with the font scaling applied.
Fixes https://github.com/tuskyapp/Tusky/issues/2982, https://github.com/tuskyapp/Tusky/issues/2461
This will make tests that need it easier.
- Rename from AccountPreferenceHandler
- Inject its dependencies
- Create an injectable CoroutineScope it can use for launching coroutines
- Use it in AccountPreferences
* Show toot stat inline
* Correct elements position
* Format stats and show it according to setting
* inline toot statistics setting
* Code formatting
* Use kotlin functions
* Change the statistics setting description
* Use capital letters for all variants
* increase the statistics margin
* Merge fixes
* Code review fixes
* move setReblogsCount and setFavouritedCount to StatusViewHolder
* code cleaning
* code cleaning
* import lexicographical order
---------
Co-authored-by: Grigorii Ioffe <zikasaks@gmail.com>
Co-authored-by: grigoriiioffe <zikasaks@icloud.com>
* Replace "warn"-filtered posts in timelines and thread view with placeholders
* Adapt hashtag muting interface
* Rework filter UI
* Add icon for account preferences
* Clean up UI
* WIP: Use chips instead of a list. Adjust padding
* Scroll the filter edit activity
Nested scrolling views (e.g., an activity that scrolls with an embedded list
that also scrolls) can be difficult UI.
Since the list of contexts is fixed, replace it with a fixed collection of
switches, so there's no need to scroll the list.
Since the list of actions is only two (warn, hide), and are mutually
exclusive, replace the spinner with two radio buttons.
Use the accent colour and title styles on the different heading titles in
the layout, to match the presentation in Preferences.
Add an explicit "Cancel" button.
The layout is a straightforward LinearLayout, so use that instead of
ConstraintLayout, and remove some unncessary IDs.
Update EditFilterActivity to handle the new layout.
* Cleanup
* Add more information to the filter list view
* First pass on code review comments
* Add view model to filters activity
* Add view model to edit filters activity
* Only use the status wrapper for filtered statuses
* Relint
---------
Co-authored-by: Nik Clayton <nik@ngo.org.uk>
* 3204: Add an account based preference store
* 3204: (related) reformat a bit, add todo
* 3204: Use the preference data store for all three account settings
* 3204: Move event handling to account settings handler
* 3204: Correct includes
* 3204: Appease linter
* 3204: Appease linter again
* 3204: Add an account based preference store
* 3204: Use the preference data store for all three account settings
* 3204: Move event handling to account settings handler
* 3204: Correct includes
* 3204: Add general "preference upgrade loop stepper"; use it for removing obsolete account settings (in shared)
* 3204: Add missing spaces
* 3204: Key is non-nullable
* 3204: Upgrade to new settings migration code
* 3204: Remove (commented) DI code
* Kotlin 1.8.10
https://github.com/JetBrains/kotlin/releases/tag/v1.8.10
* Migrate onActivityCreated to onViewCreated
* More final modifiers
* Java Cleanups
* Kotlin cleanups
* More final modifiers
* Const value TOOLBAR_HIDE_DELAY_MS
* Revert
* make BlocksAdapter use viewbinding
* remove LoadingFooterViewHolder
* cleanup code
* move accountlist to component packes
* make FollowRequestsHeaderAdapter use viewbinding
* add license to MutesAdapter
* move accountlist to component packages
* use ConstraintLayout in item_blocked_user.xml
* support the bot badge everywhere
* cleanup code
* cleanup xml files
* ktlint
* ktlint
* Handle preference fragments using the framework
The previous code started new preference "screens" as activities, even though
each one hosted a single fragment.
Modify this to use the framework's support for swapping in/out different
preference fragments.
PreferencesActivity:
- Remove the code for launching tab and proxy preferences
- Remove the code for setting titles, each fragment is responsible for that
- Implement OnPreferenceStartFragmentCallback to swap fragments in/out with
the correct animation
PreferencesFragment:
- Use `fragment` property instead of `setOnPreferenceClickListener`
- Set the activity title when resuming
Everything else:
- Set the activity title when resuming
* Implement HTTP proxy summary as a SummaryProvider
Uses the frameworks's support for setting summaries instead of rolling our
own.
Also fix a tiny bug -- the minimum port number to connect to should be 1,
not 0.
* Lint
* Change "Load more" to load oldest statuses first in home timeline
Previous behaviour loaded missing statuses by using "since_id" and "max_id".
This loads the most recent N statuses, looking backwards from "max_id".
Change to load the oldest statuses first, assuming the user is scrolling
up through the timeline and will want to load statuses in reverse
chronological order.
* Scroll to the bottom of new entries added by "Load more"
- Remember the position of the "Load more" placeholder
- Check the position of inserted entries
- If they match, scroll to the bottom
* Change "Load more" to load oldest statuses first in home timeline
Previous behaviour loaded missing statuses by using "since_id" and "max_id".
This loads the most recent N statuses, looking backwards from "max_id".
Change to load the oldest statuses first, assuming the user is scrolling
up through the timeline and will want to load statuses in reverse
chronological order.
* Scroll to the bottom of new entries added by "Load more"
- Remember the position of the "Load more" placeholder
- Check the position of inserted entries
- If they match, scroll to the bottom
* Ensure the user can't have two simultaneous "Load more" coroutines
Having two simultanous coroutines would break the calculation used to figure
out which item in the list to scroll to after a "Load more" in the timeline.
Do this by:
- Creating a TimelineUiState and associated flow that tracks the "Load more"
state
- Updating this in the (Cached|Network)TimelineViewModel
- Listening for changes to it in TimelineFragment, and notifying the adapter
- The adapter will disable any placeholder views while "Load more" is active
* Revert changes that loaded the oldest statuses instead of the newest
* Be more robust about locating the status to scroll to
Weirdness with the PagingData library meant that positionStart could still be
wrong after "Load more" was clicked.
Instead, remember the position of the "Load more" item and the ID of the
status immediately after it.
When new items are added, search for the remembered status at the position of
the "Load more" item. This is quick, testing at most LOAD_AT_ONCE items in
the adapter.
If the remembered status is not visible on screen then scroll to it.
* Lint
* Add a preference to specify the reading order
Default behaviour (oldest first) is for "load more" to load statuses and
stay at the oldest of the new statuses.
Alternative behaviour (if the user is reading from top to bottom) is to
stay at the newest of the new statuses.
* Move ReadingOrder enum construction logic in to the enum
* Jump to top if swipe/refresh while preferring newest-first order
* Show a circular progress spinner during "Load more" operations
Remove a dedicated view, and use an icon on the button instead.
Adjust the placeholder attributes and styles accordingly.
* Remove the "loadMoreActive" property
Complicates the code and doesn't really achieve the desired effect. If the
user wants to tap multiple "Load more" buttons they can.
* Update comments in TimelineFragment
* Respect the user's reading order preference if it changes
* Add developer tools
This is for functionality that makes it easier for developers to interact
with the app, or get it in to a known-state.
These features are for use by users, so are only visible in debug builds.
* Adjust how content is loaded based on preferred reading order
- Add the readingOrder to TimelineViewModel so derived classes can use it.
- Update the homeTimeline API to support the `minId` parameter and update
calls in NetworkTimelineViewModel
In CachedTimelineViewModel:
- Set the bounds of the load to be the status IDs on either side of the
placeholder ID (update TimelineDao with a new query for this)
- Load statuses using either minId or sinceId depending on the reading order
- Is there was no overlap then insert the new placeholder at the start/end
of the list depending on reading order
* Lint
* Rename unused dialog parameter to _
* Update API arguments in tests
* Simplify ReadingOrder preference handling
* Fix bug with Placeholder and the "expanded" property
If a status is a Placeholder the "expanded" propery is used to indicate
whether or not it is loading.
replaceStatusRange() set this property based on the old value, and the user's
alwaysOpenSpoiler preference setting.
This shouldn't have been used if the status is a Placeholder, as it can lead
to incorrect loading states.
Fix this.
While I'm here, introduce an explicit computed property for whether a
TimelineStatusEntity is a placeholder, and use that for code clarity.
* Set the "Load more" button background to transparent
* Fix typo.
* Inline spec, update comment
* Revert 1480c6aa3a
Turns out the behaviour is not desired.
* Remove unnecessary Log call
* Extract function
* Change default to newest first
* Handle preference fragments using the framework
The previous code started new preference "screens" as activities, even though
each one hosted a single fragment.
Modify this to use the framework's support for swapping in/out different
preference fragments.
PreferencesActivity:
- Remove the code for launching tab and proxy preferences
- Remove the code for setting titles, each fragment is responsible for that
- Implement OnPreferenceStartFragmentCallback to swap fragments in/out with
the correct animation
PreferencesFragment:
- Use `fragment` property instead of `setOnPreferenceClickListener`
- Set the activity title when resuming
Everything else:
- Set the activity title when resuming
* Lint
* Use the commit extension function
* Fix off-by-one error in HttpHeaderLink
Link headers with multiple URLs with multiple parameters were being parsed
incorrectly.
Detected by adding unit tests ahead of converting to Kotlin.
* Convert util/HttpHeaderLink from Java to Kotlin
* Convert util/ThemeUtils from Java to Kotlin
* Convert util/TimestampUtils from Java to Kotlin
* Add tests for PairedList
* Convert util/PairedList from Java to Kotlin
* Implement feedback from PR
* Relicense as GPL
* replace hard-coded strings with existing constants
* proxy port
* * custom proxy port and hostname inputs
* typesafety, refactor, linting, unit tests
* relocate ProxyConfiguration in app structure
* remove unused editTextPreference fn
* allow preference category to have no title
* refactor proxy prefs hierarchy/dependency
* Add view for browsing and unfollowing followed hashtags.
Implements #2785
* Improve list interface
* Remove superfluous suspend modifier
* Migrate to paginated loading for followed tags view
* Update app/src/main/java/com/keylesspalace/tusky/components/followedtags/FollowedTagsViewModel.kt
Co-authored-by: Konrad Pozniak <connyduck@users.noreply.github.com>
* Fix unhandled exception when opening the followed tags view while offline
Co-authored-by: Konrad Pozniak <connyduck@users.noreply.github.com>
* Fix duplicated language entries from system and app language sets.
Closes#2900
* Prefer modern language codes.
Closes#2903
* Synchronize per-account default posting language with server.
Closes#2902
* Allow users to post in languages android doesn't know about yet (e.g. toki pona)
* Always put the preselected language at the top of the list
* update to Api 33, fix some deprecations
* fix deprecated serializable/parcelable methods
* ask for notification permission
* fix code formatting
* add back comment in PreferencesActivity
* Preference to disable multiple-login usernames (with problems)
* Fix problem where 'show self username disambiguation' does not take effect immediately because MainActivity needed to be restarted
* Make 'show username in toolbars' a 3-option selector, default when multiple accounts logged in
* Move SHOW_SELF_USERNAME higher in preference fragment
* Fix unintended [mismatched] show-replies preference and add a comment to prevent confusion.
* Change the key on TAB_FILTER_HOME_REPLIES to reset everyone's value here once.
Fixes#793.
This is an implementation for push notifications based on UnifiedPush
for Tusky. No push gateway (other than UP itself) is needed, since
UnifiedPush is simple enough such that it can act as a catch-all
endpoint for WebPush messages. When a UnifiedPush distributor is present
on-device, we will by default register Tusky as a receiver; if no
UnifiedPush distributor is available, then pull notifications are used
as a fallback mechanism.
Because WebPush messages are encrypted, and Mastodon does not send the
keys and IV needed for decryption in the request body, for now the push
handler simply acts as a trigger for the pre-existing NotificationWorker
which is also used for pull notifications. Nevertheless, I have
implemented proper key generation and storage, just in case we would
like to implement full decryption support in the future when Mastodon
upgrades to the latest WebPush encryption scheme that includes all
information in the request body.
For users with existing accounts, push notifications will not be enabled
until all of the accounts have been re-logged in to grant the new push
OAuth scope. A small prompt will be shown (until dismissed) as a
Snackbar to explain to the user about this, and an option is added in
Account Preferences to facilitate re-login without deleting local drafts
and cache.
* Update to Emoji2
* Hopefully fix the emoji picker preference
* Switch to released Filemojicompat version
* Filemojicompat version as an own var
* Remove an unused import
* Small cleanup
* Correct onDisplayPreferenceDialog; test TuskyApplication
* Use TextViews instead of EmojiTextViews
* Recreate the Main Activity if the emoji pack is updated
* Enable coreLibraryDesugaring (for Java Streams); update Filemojicompat, downgrade Emoji2
* Update emoji font versions to 14
* Use FilemojiCompat 3.2.0-beta01
* Make ktLint happy again
* Remove coreLibraryDesugaring and a FIXME
* Use EmojiPickerPreference.get()
* Disable emoji pack import
* Update FilemojiCompat to Beta 2
* Update FilemojiCompat to Beta 3
* Update FilemojiCompat to Beta 3.2.0 final
* Update FilemojiCompat to 3.2.1