diff --git "a/kotlin_code_documentation_test.tsv" "b/kotlin_code_documentation_test.tsv" new file mode 100644--- /dev/null +++ "b/kotlin_code_documentation_test.tsv" @@ -0,0 +1,600 @@ +code_function message +@Throws(IOException::class) fun execute(): Response actual fun enqueue(responseCallback: Callback) actual fun cancel() actual fun isExecuted(): Boolean actual fun isCanceled(): Boolean fun timeout(): Timeout public actual override fun clone(): Call actual fun interface Factory { actual fun newCall(request: Request): Call } } "Invokes the request immediately, and blocks until the response can be processed or is in error.To avoid leaking resources callers should close the [Response] which in turn will close the underlying [ResponseBody]. The caller may read the response body with the response's [Response.body] method. To avoid leaking resources callers must [close the response body][ResponseBody] or the response. Note that transport-layer success (receiving a HTTP response code, headers and body) does not necessarily indicate application-layer success: `response` may still indicate an unhappy HTTP response code like 404 or 500. @throws IOException if the request could not be executed due to cancellation, a connectivity problem or timeout. Because networks can fail during an exchange, it is possible that the remote server accepted the request before the failure. @throws IllegalStateException when the call has already been executed." +"class Handshake internal constructor( @get:JvmName(""tlsVersion"") val tlsVersion: TlsVersion, @get:JvmName(""cipherSuite"") val cipherSuite: CipherSuite, @get:JvmName(""localCertificates"") val localCertificates: List, peerCertificatesFn: () -> List ) { @get:JvmName(""peerCertificates"") val peerCertificates: List by lazy { try { peerCertificatesFn() } catch (spue: SSLPeerUnverifiedException) { listOf() } } @JvmName(""-deprecated_tlsVersion"") @Deprecated( message = ""moved to val"", replaceWith = ReplaceWith(expression = ""tlsVersion""), level = DeprecationLevel.ERROR) fun tlsVersion(): TlsVersion = tlsVersion @JvmName(""-deprecated_cipherSuite"") @Deprecated( message = ""moved to val"", replaceWith = ReplaceWith(expression = ""cipherSuite""), level = DeprecationLevel.ERROR) fun cipherSuite(): CipherSuite = cipherSuite @JvmName(""-deprecated_peerCertificates"") @Deprecated( message = ""moved to val"", replaceWith = ReplaceWith(expression = ""peerCertificates""), level = DeprecationLevel.ERROR) fun peerCertificates(): List = peerCertificates /** Returns the remote peer's principle, or null if that peer is anonymous. */ @get:JvmName(""peerPrincipal"") val peerPrincipal: Principal? get() = (peerCertificates.firstOrNull() as? X509Certificate)?.subjectX500Principal @JvmName(""-deprecated_peerPrincipal"") @Deprecated( message = ""moved to val"", replaceWith = ReplaceWith(expression = ""peerPrincipal""), level = DeprecationLevel.ERROR) fun peerPrincipal(): Principal? = peerPrincipal @JvmName(""-deprecated_localCertificates"") @Deprecated( message = ""moved to val"", replaceWith = ReplaceWith(expression = ""localCertificates""), level = DeprecationLevel.ERROR) fun localCertificates(): List = localCertificates @get:JvmName(""localPrincipal"") val localPrincipal: Principal? get() = (localCertificates.firstOrNull() as? X509Certificate)?.subjectX500Principal @JvmName(""-deprecated_localPrincipal"") @Deprecated( message = ""moved to val"", replaceWith = ReplaceWith(expression = ""localPrincipal""), level = DeprecationLevel.ERROR) fun localPrincipal(): Principal? = localPrincipal override fun equals(other: Any?): Boolean { return other is Handshake && other.tlsVersion == tlsVersion && other.cipherSuite == cipherSuite && other.peerCertificates == peerCertificates && other.localCertificates == localCertificates } override fun hashCode(): Int { var result = 17 result = 31 * result + tlsVersion.hashCode() result = 31 * result + cipherSuite.hashCode() result = 31 * result + peerCertificates.hashCode() result = 31 * result + localCertificates.hashCode() return result } override fun toString(): String { val peerCertificatesString = peerCertificates.map { it.name }.toString() return ""Handshake{"" + ""tlsVersion=$tlsVersion "" + ""cipherSuite=$cipherSuite "" + ""peerCertificates=$peerCertificatesString "" + ""localCertificates=${localCertificates.map { it.name }}}"" } private val Certificate.name: String get() = when (this) { is X509Certificate -> subjectDN.toString() else -> type } companion object { @Throws(IOException::class) @JvmStatic @JvmName(""get"") fun SSLSession.handshake(): Handshake { val cipherSuite = when (val cipherSuiteString = checkNotNull(cipherSuite) { ""cipherSuite == null"" }) { ""TLS_NULL_WITH_NULL_NULL"", ""SSL_NULL_WITH_NULL_NULL"" -> { throw IOException(""cipherSuite == $cipherSuiteString"") } else -> CipherSuite.forJavaName(cipherSuiteString) } val tlsVersionString = checkNotNull(protocol) { ""tlsVersion == null"" } if (""NONE"" == tlsVersionString) throw IOException(""tlsVersion == NONE"") val tlsVersion = TlsVersion.forJavaName(tlsVersionString) val peerCertificatesCopy = try { peerCertificates.toImmutableList() } catch (_: SSLPeerUnverifiedException) { listOf() } return Handshake(tlsVersion, cipherSuite, localCertificates.toImmutableList()) { peerCertificatesCopy } } private fun Array?.toImmutableList(): List { return if (this != null) { immutableListOf(*this) } else { emptyList() } } @Throws(IOException::class) @JvmName(""-deprecated_get"") @Deprecated( message = ""moved to extension function"", replaceWith = ReplaceWith(expression = ""sslSession.handshake()""), level = DeprecationLevel.ERROR) fun get(sslSession: SSLSession) = sslSession.handshake() @JvmStatic fun get( tlsVersion: TlsVersion, cipherSuite: CipherSuite, peerCertificates: List, localCertificates: List ): Handshake { val peerCertificatesCopy = peerCertificates.toImmutableList() return Handshake(tlsVersion, cipherSuite, localCertificates.toImmutableList()) { peerCertificatesCopy } } } }" "A record of a TLS handshake. For HTTPS clients, the client is *local* and the remote server is its *peer*. This value object describes a completed handshake. Use [ConnectionSpec] to set policy for new handshakes." +"fun interface Dns {@Throws(UnknownHostException::class) fun lookup(hostname: String): List companion object { @JvmField val SYSTEM: Dns = DnsSystem() private class DnsSystem : Dns { override fun lookup(hostname: String): List { try { return InetAddress.getAllByName(hostname).toList() } catch (e: NullPointerException) { throw UnknownHostException(""Broken system behaviour for dns lookup of $hostname"").apply { initCause(e) } } } } } }" "A domain name service that resolves IP addresses for host names. Most applications will use the [system DNS service][SYSTEM], which is the default. Some applications may provide their own implementation to use a different DNS server, to prefer IPv6 addresses, to prefer IPv4 addresses, or to force a specific known IP address. Implementations of this interface must be safe for concurrent use." +"class Dispatcher() { @get:Synchronized var maxRequests = 64 set(maxRequests) { require(maxRequests >= 1) { ""max < 1: $maxRequests"" } synchronized(this) { field = maxRequests } promoteAndExecute() } @get:Synchronized var maxRequestsPerHost = 5 set(maxRequestsPerHost) { require(maxRequestsPerHost >= 1) { ""max < 1: $maxRequestsPerHost"" } synchronized(this) { field = maxRequestsPerHost } promoteAndExecute() } @set:Synchronized @get:Synchronized var idleCallback: Runnable? = null private var executorServiceOrNull: ExecutorService? = null @get:Synchronized @get:JvmName(""executorService"") val executorService: ExecutorService get() { if (executorServiceOrNull == null) { executorServiceOrNull = ThreadPoolExecutor(0, Int.MAX_VALUE, 60, TimeUnit.SECONDS, SynchronousQueue(), threadFactory(""$okHttpName Dispatcher"", false)) } return executorServiceOrNull!! } private val readyAsyncCalls = ArrayDeque() private val runningAsyncCalls = ArrayDeque() private val runningSyncCalls = ArrayDeque() constructor(executorService: ExecutorService) : this() { this.executorServiceOrNull = executorService } internal fun enqueue(call: AsyncCall) { synchronized(this) { readyAsyncCalls.add(call) if (!call.call.forWebSocket) { val existingCall = findExistingCallWithHost(call.host) if (existingCall != null) call.reuseCallsPerHostFrom(existingCall) } } promoteAndExecute() } private fun findExistingCallWithHost(host: String): AsyncCall? { for (existingCall in runningAsyncCalls) { if (existingCall.host == host) return existingCall } for (existingCall in readyAsyncCalls) { if (existingCall.host == host) return existingCall } return null } @Synchronized fun cancelAll() { for (call in readyAsyncCalls) { call.call.cancel() } for (call in runningAsyncCalls) { call.call.cancel() } for (call in runningSyncCalls) { call.cancel() } } private fun promoteAndExecute(): Boolean { this.assertThreadDoesntHoldLock() val executableCalls = mutableListOf() val isRunning: Boolean synchronized(this) { val i = readyAsyncCalls.iterator() while (i.hasNext()) { val asyncCall = i.next() if (runningAsyncCalls.size >= this.maxRequests) break // Max capacity. if (asyncCall.callsPerHost.get() >= this.maxRequestsPerHost) continue // Host max capacity. i.remove() asyncCall.callsPerHost.incrementAndGet() executableCalls.add(asyncCall) runningAsyncCalls.add(asyncCall) } isRunning = runningCallsCount() > 0 } if (executorService.isShutdown) { for (i in 0 until executableCalls.size) { val asyncCall = executableCalls[i] asyncCall.callsPerHost.decrementAndGet() synchronized(this) { runningAsyncCalls.remove(asyncCall) } asyncCall.failRejected() } idleCallback?.run() } else { for (i in 0 until executableCalls.size) { val asyncCall = executableCalls[i] asyncCall.executeOn(executorService) } } return isRunning } @Synchronized internal fun executed(call: RealCall) { runningSyncCalls.add(call) } internal fun finished(call: AsyncCall) { call.callsPerHost.decrementAndGet() finished(runningAsyncCalls, call) } internal fun finished(call: RealCall) { finished(runningSyncCalls, call) } private fun finished(calls: Deque, call: T) { val idleCallback: Runnable? synchronized(this) { if (!calls.remove(call)) throw AssertionError(""Call wasn't in-flight!"") idleCallback = this.idleCallback } val isRunning = promoteAndExecute() if (!isRunning && idleCallback != null) { idleCallback.run() } } @Synchronized fun queuedCalls(): List { return Collections.unmodifiableList(readyAsyncCalls.map { it.call }) } @Synchronized fun runningCalls(): List { return Collections.unmodifiableList(runningSyncCalls + runningAsyncCalls.map { it.call }) } @Synchronized fun queuedCallsCount(): Int = readyAsyncCalls.size @Synchronized fun runningCallsCount(): Int = runningAsyncCalls.size + runningSyncCalls.size @JvmName(""-deprecated_executorService"") @Deprecated( message = ""moved to val"", replaceWith = ReplaceWith(expression = ""executorService""), level = DeprecationLevel.ERROR) fun executorService(): ExecutorService = executorService }" "Policy on when async requests are executed. Each dispatcher uses an [ExecutorService] to run calls internally. If you supply your own executor, it should be able to run [the configured maximum][maxRequests] number of calls concurrently." +"class ConnectionPool internal constructor( internal val delegate: RealConnectionPool ) { internal constructor( maxIdleConnections: Int = 5, keepAliveDuration: Long = 5, timeUnit: TimeUnit = TimeUnit.MINUTES, taskRunner: TaskRunner = TaskRunner.INSTANCE, connectionListener: ConnectionListener = ConnectionListener.NONE, ) : this(RealConnectionPool( taskRunner = taskRunner, maxIdleConnections = maxIdleConnections, keepAliveDuration = keepAliveDuration, timeUnit = timeUnit, connectionListener = connectionListener )) constructor( maxIdleConnections: Int = 5, keepAliveDuration: Long = 5, timeUnit: TimeUnit = TimeUnit.MINUTES, connectionListener: ConnectionListener = ConnectionListener.NONE, ) : this( taskRunner = TaskRunner.INSTANCE, maxIdleConnections = maxIdleConnections, keepAliveDuration = keepAliveDuration, timeUnit = timeUnit, connectionListener = connectionListener ) constructor( maxIdleConnections: Int, keepAliveDuration: Long, timeUnit: TimeUnit, ) : this( maxIdleConnections = maxIdleConnections, keepAliveDuration = keepAliveDuration, timeUnit = timeUnit, taskRunner = TaskRunner.INSTANCE, connectionListener = ConnectionListener.NONE ) constructor() : this(5, 5, TimeUnit.MINUTES) fun idleConnectionCount(): Int = delegate.idleConnectionCount() fun connectionCount(): Int = delegate.connectionCount() internal val connectionListener: ConnectionListener get() = delegate.connectionListener fun evictAll() { delegate.evictAll() } }" Manages reuse of HTTP and HTTP/2 connections for reduced network latency. HTTP requests that share the same [Address] may share a [Connection]. This class implements the policy of which connections to keep open for future use. @constructor Create a new connection pool with tuning parameters appropriate for a single-user application. The tuning parameters in this pool are subject to change in future OkHttp releases. Currently this pool holds up to 5 idle connections which will be evicted after 5 minutes of inactivity. +"abstract class ConnectionListener { open fun connectStart(route: Route, call: Call) {} open fun connectFailed(route: Route, call: Call, failure: IOException) {} open fun connectEnd(connection: Connection, route: Route, call: RealCall) {} open fun connectionClosed(connection: Connection) {} open fun connectionAcquired(connection: Connection, call: Call) {} open fun connectionReleased(connection: Connection, call: Call) {} open fun noNewExchanges(connection: Connection) {} companion object { val NONE: ConnectionListener = object : ConnectionListener() {} } }" "Listener for connection events. Extend this class to monitor the new connections and closes.All event methods must execute fast, without external locking, cannot throw exceptions,attempt to mutate the event parameters, or be reentrant back into the client.Any IO - writing to files or network should be done asynchronously." +"@RequiresApi(Build.VERSION_CODES.Q) class AndroidAsyncDns( private val dnsClass: AsyncDns.DnsClass, private val network: Network? = null, ) : AsyncDns { @RequiresApi(Build.VERSION_CODES.Q) private val resolver = DnsResolver.getInstance() private val executor = Executors.newSingleThreadExecutor() override fun query(hostname: String, callback: AsyncDns.Callback) { resolver.query( network, hostname, dnsClass.type, DnsResolver.FLAG_EMPTY, executor, null, object : DnsResolver.Callback> { override fun onAnswer(addresses: List, rCode: Int) { callback.onResponse(hostname, addresses) } override fun onError(e: DnsResolver.DnsException) { callback.onFailure(hostname, UnknownHostException(e.message).apply { initCause(e) }) } } ) } companion object { val IPv4 = AndroidAsyncDns(dnsClass = AsyncDns.DnsClass.IPV4) val IPv6 = AndroidAsyncDns(dnsClass = AsyncDns.DnsClass.IPV6) } }" "DNS implementation based on android.net.DnsResolver, which submits a request for A or AAAA records, and returns the addresses or exception. Two instances must be used to get all results for an address.@param network network to use, if not selects the default network." +Application that sets up Timber in the DEBUG BuildConfig.Read Timber's documentation for production setups. @HiltAndroidApp class TodoApplication : Application() { override fun onCreate() { super.onCreate() if (BuildConfig.DEBUG) Timber.plant(DebugTree()) } } +sealed class Async { object Loading : Async() data class Success(val data: T) : Async() } A generic class that holds a loading signal or the result of an async operation. +"@Composable fun LoadingContent( loading: Boolean, empty: Boolean, emptyContent: @Composable () -> Unit, onRefresh: () -> Unit, modifier: Modifier = Modifier, content: @Composable () -> Unit ) { if (empty) { emptyContent() } else { SwipeRefresh( state = rememberSwipeRefreshState(loading), onRefresh = onRefresh, modifier = modifier, content = content, ) } }" "Display an initial empty state or swipe to refresh content. @param loading (state) when true, display a loading spinner over [content] @param empty (state) when true, display [emptyContent] @param emptyContent (slot) the content to display for the empty state @param onRefresh (event) event to request refresh @param modifier the modifier to apply to this layout. @param content (slot) the main content to show" +"class SimpleCountingIdlingResource(private val resourceName: String) : IdlingResource { private val counter = AtomicInteger(0) @Volatile private var resourceCallback: IdlingResource.ResourceCallback? = null override fun getName() = resourceName override fun isIdleNow() = counter.get() == 0 override fun registerIdleTransitionCallback(resourceCallback: IdlingResource.ResourceCallback) { this.resourceCallback = resourceCallback } fun increment() { counter.getAndIncrement() } fun decrement() { val counterVal = counter.decrementAndGet() if (counterVal == 0) { // we've gone from non-zero to zero. That means we're idle now! Tell espresso. resourceCallback?.onTransitionToIdle() } else if (counterVal < 0) { throw IllegalStateException(""Counter has been corrupted!"") } } }" "An simple counter implementation of [IdlingResource] that determines idleness by maintaining an internal counter. When the counter is 0 - it is considered to be idle, when it is non-zero it is not idle. This is very similar to the way a [java.util.concurrent.Semaphore] behaves. This class can then be used to wrap up operations that while in progress should block tests from accessing the UI." +"@AndroidEntryPoint class ReminderReceiver : BroadcastReceiver() { @Inject lateinit var settings: PresentlySettings override fun onReceive(context: Context, intent: Intent) { val openActivityIntent = Intent(context, ContainerActivity::class.java) openActivityIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP //set flag to restart/relaunch the app openActivityIntent.putExtra(fromNotification, true) val pendingIntent = PendingIntent.getActivity( context, ALARM_TYPE_RTC, openActivityIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT ) createLocalNotification(context, pendingIntent) NotificationScheduler().configureNotifications(context, settings) } private fun createLocalNotification(context: Context, pendingIntent: PendingIntent) { val title = context.getString(R.string.reminder_title) val content = context.getString(R.string.what_are_you_thankful_for_today) val notificationBuilder = NotificationCompat.Builder(context, CHANNEL_ID) .setSmallIcon(R.drawable.ic_app_icon) .setContentTitle(title) .setContentText(content) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(pendingIntent) .setCategory(Notification.CATEGORY_REMINDER) .setAutoCancel(true) val notificationManager = NotificationManagerCompat.from(context) notificationManager.notify(ALARM_TYPE_RTC, notificationBuilder.build()) } companion object { const val fromNotification = ""fromNotification"" } }" Receives broadcasts from an alarm and creates notifications +"@LogLifecykle @AndroidEntryPoint @Suppress(""TooManyFunctions"") class Activity : AppCompatActivity(), AuthCaster.AuthCasterListener, Flow { @Inject lateinit var authCaster: AuthCaster private val viewModel by viewModels() private lateinit var activityDrawer: DrawerLayout private lateinit var appBarConfiguration: AppBarConfiguration override fun onCreate(savedInstanceState: Bundle?) { setTheme(R.style.AppTheme_NoActionBar) super.onCreate(savedInstanceState) setContentView(R.layout.activity) activityDrawer = findViewById(R.id.activityDrawer) setSupportActionBar(findViewById(R.id.appBarToolbar)) setupNavController() observeViewModel() authCaster.subscribeToAuthError(this) } private fun observeViewModel() { viewModel.user.observe(this) { user -> if (user is User.Found) { updateAvatar(findViewById(R.id.activityNavigationView), user.domain) } } viewModel.navigation.observe(this) { findNavController(R.id.activityNavigation).navigate(it) } viewModel.snackBar.observe(this) { showSnackbarError() } } private fun showSnackbarError() { findViewById(R.id.activityDrawer)?.let { view -> Snackbar.make(view, R.string.logout_forced, Snackbar.LENGTH_LONG).show() } } override fun onDestroy() { authCaster.unsubscribeFromAuthError(this) super.onDestroy() } override fun onBackPressed() { if (activityDrawer.isDrawerOpen(GravityCompat.START)) { activityDrawer.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } private fun setupNavController() { appBarConfiguration = AppBarConfiguration( setOf( R.id.animeFragment, R.id.mangaFragment, R.id.discoverFragment, R.id.hostFragment, R.id.timelineFragment ), findViewById(R.id.activityDrawer) ) with(findNavController(R.id.activityNavigation)) { findViewById(R.id.activityNavigationView).setupWithNavController(this) setupActionBarWithNavController(this, appBarConfiguration) addOnDestinationChangedListener { _, destination, _ -> when (destination.id) { R.id.credentialsFragment, R.id.syncingFragment -> disableDrawer() else -> enableDrawer() } } } } override fun onSupportNavigateUp() = findNavController(R.id.activityNavigation).navigateUp(appBarConfiguration) override fun unableToRefresh() { Timber.w(""unableToRefresh has occurred"") performLogout(true) } /** * Shows a dialog asking the user if they wish to logout. * This is called from the menu_navigation.xml menu resource in order to allow it to still * function while using the nav component. */ fun requestUserLogout(@Suppress(""UNUSED_PARAMETER"") item: MenuItem) { MaterialDialog(this).show { message(R.string.menu_logout_prompt_message) positiveButton(R.string.menu_logout_prompt_confirm) { performLogout() } negativeButton(R.string.menu_logout_prompt_cancel) lifecycleOwner(this@Activity) } } private fun performLogout(isFailure: Boolean = false) { Timber.w(""Logout called, now attempting"") viewModel.logout(isFailure) } private fun disableDrawer() { supportActionBar?.hide() activityDrawer.setDrawerLockMode(LOCK_MODE_LOCKED_CLOSED) } private fun enableDrawer() { supportActionBar?.show() activityDrawer.setDrawerLockMode(LOCK_MODE_UNLOCKED) } override fun finishLogin() { viewModel.navigateToDefaultHome() } }" "Single host activity for the application, handles all required logic of the activity such as hiding/showing the drawer." +"@HiltWorker class RefreshAuthWorker @AssistedInject constructor( @Assisted appContext: Context, @Assisted workerParams: WorkerParameters, private val userRepo: UserRepository, private val auth: AccessTokenRepository ) : CoroutineWorker(appContext, workerParams) { override suspend fun doWork(): Result { Timber.i(""doWork RefreshAuthWorker"") if (userRepo.retrieveUserId() == null) { Timber.i(""doWork no userId found, so cancelling"") return Result.success() } Timber.i(""doWork userId found, beginning to refresh"") return if (auth.refresh() !is AccessTokenResult.Success) { Result.retry() } else { Result.success() } } }" Worker object that handles updating a users authenticated state. When scheduled to run it will send a request to the [userRepo] to try to refresh the current user. +"@HiltWorker class RefreshSeriesWorker @AssistedInject constructor( @Assisted appContext: Context, @Assisted workerParams: WorkerParameters, private val seriesRepo: SeriesRepository, private val userRepo: UserRepository ) : CoroutineWorker(appContext, workerParams) { override suspend fun doWork(): Result { Timber.i(""doWork RefreshSeriesWorker"") if (userRepo.retrieveUserId() == null) { Timber.i(""doWork no userId found, so cancelling"") return Result.success() } Timber.i(""doWork userId found, beginning to refresh"") return if ( listOf( seriesRepo.refreshAnime(), seriesRepo.refreshManga() ).any { it is Resource.Error } ) { Result.retry() } else { Result.success() } } }" "Worker object that handles updating a users Series if possible. When scheduled to run it will send a request to the [seriesRepo] to try to update the series,letting the [seriesRepo] handle what to do with the results." +"@HiltWorker class RefreshUserWorker @AssistedInject constructor( @Assisted appContext: Context, @Assisted workerParams: WorkerParameters, private val userRepo: UserRepository ) : CoroutineWorker(appContext, workerParams) { override suspend fun doWork(): Result { Timber.i(""doWork RefreshUserWorker"") if (userRepo.retrieveUserId() == null) { Timber.i(""doWork no userId found, so cancelling"") return Result.success() } Timber.i(""doWork userId found, beginning to refresh"") return if (userRepo.refreshUser() is Resource.Error) { Result.retry() } else { Result.success() } } }" Worker object that handles updating the information for a user. When scheduled to run it will send a request to the [userRepo] to try to refresh the current user data. +"class WorkerQueue @Inject constructor(private val workManager: WorkManager) { private val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build() fun enqueueAuthRefresh() { val request = PeriodicWorkRequestBuilder(7, TimeUnit.DAYS) .setConstraints(constraints) .addTag(AUTH_REFRESH_TAG) .build() workManager.enqueueUniquePeriodicWork( AUTH_UNIQUE_NAME, ExistingPeriodicWorkPolicy.KEEP, request ) } fun enqueueSeriesRefresh() { val request = PeriodicWorkRequestBuilder(12, TimeUnit.HOURS) .setConstraints(constraints) .addTag(SERIES_REFRESH_TAG) .build() workManager.enqueueUniquePeriodicWork( SERIES_UNIQUE_NAME, ExistingPeriodicWorkPolicy.KEEP, request ) } Starts up the worker to perform user refreshing. fun enqueueUserRefresh() { val request = PeriodicWorkRequestBuilder(12, TimeUnit.HOURS) .setConstraints(constraints) .addTag(USER_REFRESH_TAG) .build() workManager.enqueueUniquePeriodicWork( USER_UNIQUE_NAME, ExistingPeriodicWorkPolicy.KEEP, request ) } }" Allows starting up workers. Starts up the worker to perform auth refreshing. Starts up the worker to perform series refreshing. Starts up the worker to perform user refreshing. +@Module @InstallIn(ViewModelComponent::class) abstract class ActivityModule { companion object { @Provides @Reusable fun providesActivityService(httpClient: OkHttpClient): KitsuActivityService { val moshi = Moshi.Builder() .add(ChangedDataContainerAdapter()) .build() return Retrofit.Builder() .baseUrl(KITSU_URL) .client(httpClient) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() .create(KitsuActivityService::class.java) } } @Binds abstract fun bindApi(api: KitsuActivity): ActivityApi } Provides a Hilt module for usage of [ActivityApi] and Builds and provides the instance of [KitsuActivityService]. Binds [api] to an instance of [ActivityApi]. +@Module @InstallIn(SingletonComponent::class) object WorkerModule { @Provides fun providesWorkManager(@ApplicationContext context: Context) = WorkManager.getInstance(context) } Dagger [Module] to provide the systems [WorkManager] and Provides a [WorkManager] instance to the dependency graph. +@Module @InstallIn(SingletonComponent::class) abstract class UserModule { companion object { @Provides @Reusable fun providesUserService(httpClient: OkHttpClient): KitsuUserService { val moshi = Moshi.Builder() .add(RatingSystemAdapter()) .add(ImageModelAdapter()) .build() return Retrofit.Builder() .baseUrl(KITSU_URL) .client(httpClient) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() .create(KitsuUserService::class.java) } } @Binds abstract fun bindApi(api: KitsuUser): UserApi } Provides a Hilt module for usage of [UserApi]. Builds and provides the instance of [KitsuUserService]. Binds [api] to an instance of [UserApi]. +@Module @InstallIn(SingletonComponent::class) abstract class UrlModule { @Binds abstract fun providesUrlHandler(urlHandler: CustomTabsUrl): UrlHandler } Dagger [Module] to bind [UrlHandler]. Binds the instance of [CustomTabsUrl] to [UrlHandler]. +@Module @InstallIn(SingletonComponent::class) abstract class TrendingModule { companion object { @Provides @Reusable fun providesTrendingService(httpClient: OkHttpClient): KitsuTrendingService { val moshi = Moshi.Builder() .add(ImageModelAdapter()) .add(SeriesStatusAdapter()) .add(SeriesTypeAdapter()) .add(SubtypeAdapter()) .build() return Retrofit.Builder() .baseUrl(KITSU_URL) .client(httpClient) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() .create(KitsuTrendingService::class.java) } } Binds [api] to an instance of [TrendingApi]. @Binds abstract fun bindApi(api: KitsuTrending): TrendingApi } Provides a Hilt module for usage of [TrendingApi]. Builds and provides the instance of [KitsuTrendingService]. +"@Module @InstallIn(SingletonComponent::class) object ServerModule { @Provides @Reusable fun providesAuthenticatedClient( authInjection: AuthInjectionInterceptor, authRefresh: AuthRefreshInterceptor ): OkHttpClient { return OkHttpClient() .newBuilder() .addInterceptor(authInjection) .addInterceptor(authRefresh) .also { httpClient -> if (BuildConfig.DEBUG) { httpClient.addInterceptor( HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } ) } } .build() } } Footer" "Dagger [Module] for the [com.chesire.nekome.server] package and Provides an instance of [OkHttpClient] with the authentication injectors pre-setup, so that authentication is already handled." +"@Module @InstallIn(SingletonComponent::class) object SeriesModule { @Provides fun bindUserProvider(binder: UserProviderBinder): UserProvider = binder @Provides fun provideSeriesRepository( dao: SeriesDao, api: SeriesApi, user: UserProvider, map: SeriesMapper ) = SeriesRepository(dao, api, user, map) }" Dagger [Module] for the [com.chesire.nekome.series] package. Provides a [UserProvider] to the series repository. Provides the [SeriesRepository] to the dependency graph. +@Module @InstallIn(SingletonComponent::class) abstract class SearchModule { companion object { @Provides @Reusable fun providesSearchService(httpClient: OkHttpClient): KitsuSearchService { val moshi = Moshi.Builder() .add(ImageModelAdapter()) .add(SeriesStatusAdapter()) .add(SeriesTypeAdapter()) .add(SubtypeAdapter()) .build() return Retrofit.Builder() .baseUrl(KITSU_URL) .client(httpClient) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() .create(KitsuSearchService::class.java) } } @Binds abstract fun bindApi(api: KitsuSearch): SearchApi } Provides a Hilt module for usage of [SearchApi]. Builds and provides the instance of [KitsuSearchService]. Binds [api] to an instance of [SearchApi]. +@Module @InstallIn(SingletonComponent::class) abstract class LibraryModule { companion object { @Provides @Reusable fun providesLibraryService(httpClient: OkHttpClient): KitsuLibraryService { val moshi = Moshi.Builder() .add(ImageModelAdapter()) .add(SeriesStatusAdapter()) .add(SeriesTypeAdapter()) .add(SubtypeAdapter()) .add(UserSeriesStatusAdapter()) .build() return Retrofit.Builder() .baseUrl(KITSU_URL) .client(httpClient) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() .create(KitsuLibraryService::class.java) } } @Binds abstract fun bindApi(api: KitsuLibrary): SeriesApi } Provides a Hilt module for usage of [SeriesApi]. Builds and provides the instance of [KitsuTrendingService]. Binds [api] to an instance of [SeriesApi]. +@Module @InstallIn(FragmentComponent::class) object FieldProvider { @Provides fun provideFields(): Array = R.string::class.java.fields } Footer Dagger [Module] to provide the application [Field] and Provides the string fields. For use to show the open source libraries used. +@Module @InstallIn(SingletonComponent::class) object DatabaseModule { @Provides @Singleton fun provideDB(@ApplicationContext context: Context) = RoomDB.build(context) @Provides @Singleton fun provideSeries(db: RoomDB) = db.series() @Provides @Singleton fun provideUser(db: RoomDB) = db.user() } Dagger [Module] for the [com.chesire.nekome.database] package and Provides the build [RoomDB] and Provides the [SeriesDao] table from [RoomDB] and Provides the [UserDao] table from [RoomDB]. +@Module @InstallIn(SingletonComponent::class) object CoroutineModule { @Provides @IOContext fun providesIOContext(): CoroutineContext = Dispatchers.IO } Footer Dagger [Module] for providing [CoroutineContext] to parts of the application and Provides a [CoroutineContext] of [Dispatchers.IO] providing the annotation [IOContext] is used. +@Module @InstallIn(SingletonComponent::class) abstract class AuthModule { companion object { @Provides @Reusable fun providesAuthService(): KitsuAuthService { return Retrofit.Builder() .baseUrl(KITSU_URL) .client(OkHttpClient()) .addConverterFactory( MoshiConverterFactory.create(Moshi.Builder().build()) ) .build() .create(KitsuAuthService::class.java) } } @Binds abstract fun bindApi(api: KitsuAuth): AuthApi } Provides a Hilt module for usage of [AuthApi] and Builds and provides the instance of [KitsuAuthService] and Binds [api] to an instance of [AuthApi]. +@Module @InstallIn(SingletonComponent::class) object AppModule { @Provides @Reusable fun provideSharedPreferences(@ApplicationContext context: Context): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) } Dagger [Module] for generic application items and Provides the default [SharedPreferences] for the application. +"@Database(entities = [Sleep::class], version = 3, exportSchema = false) abstract class AppDatabase : RoomDatabase() { abstract fun sleepDao(): SleepDao }" Contains the database holder and serves as the main access point for the stored data. +"object DataModel { lateinit var preferences: SharedPreferences var preferencesActivity: PreferencesActivity? = null var start: Date? = null set(start) { field = start val editor = preferences.edit() field?.let { editor.putLong(""start"", it.time) } editor.apply() } var stop: Date? = null lateinit var database: AppDatabase val sleepsLive: LiveData> get() = database.sleepDao().getAllLive() private var initialized: Boolean = false fun init(context: Context, preferences: SharedPreferences) { if (initialized) { return } this.preferences = preferences val start = preferences.getLong(""start"", 0) if (start > 0) { this.start = Date(start) } database = Room.databaseBuilder(context, AppDatabase::class.java, ""database"") .addMigrations(MIGRATION_1_2) .addMigrations(MIGRATION_2_3) .build() initialized = true } private fun getStartDelay(): Int { val startDelayStr = preferences.getString(""sleep_start_delta"", ""0"") ?: ""0"" return startDelayStr.toIntOrNull() ?: 0 } fun getCompactView(): Boolean { return preferences.getBoolean(""compact_view"", false) } suspend fun storeSleep() { val sleep = Sleep() start?.let { sleep.start = it.time } stop?.let { sleep.stop = it.time } val startDelayMS = getStartDelay() * 60 * 1000 if (sleep.start + startDelayMS > sleep.stop) { sleep.start = sleep.stop } else { sleep.start += startDelayMS } database.sleepDao().insert(sleep) val editor = preferences.edit() editor.remove(""start"") editor.apply() } suspend fun insertSleep(sleep: Sleep) { database.sleepDao().insert(sleep) } private suspend fun insertSleeps(sleepList: List) { database.sleepDao().insert(sleepList) } suspend fun updateSleep(sleep: Sleep) { database.sleepDao().update(sleep) } suspend fun deleteSleep(sleep: Sleep) { database.sleepDao().delete(sleep) } suspend fun deleteAllSleep() { database.sleepDao().deleteAll() } suspend fun getSleepById(sid: Int): Sleep { return database.sleepDao().getById(sid) } fun getSleepsAfterLive(after: Date): LiveData> { return database.sleepDao().getAfterLive(after.time) } suspend fun importData(context: Context, cr: ContentResolver, uri: Uri) { val inputStream = cr.openInputStream(uri) val records: Iterable = CSVFormat.DEFAULT.parse(InputStreamReader(inputStream)) val importedSleeps = mutableListOf() try { var first = true for (cells in records) { if (first) { first = false continue } val sleep = Sleep() sleep.start = cells[1].toLong() sleep.stop = cells[2].toLong() if (cells.isSet(3)) { sleep.rating = cells[3].toLong() } if (cells.isSet(4)) { sleep.comment = cells[4] } importedSleeps.add(sleep) } val oldSleeps = database.sleepDao().getAll() val newSleeps = importedSleeps.subtract(oldSleeps.toSet()) database.sleepDao().insert(newSleeps.toList()) } catch (e: IOException) { Log.e(TAG, ""importData: readLine() failed"") return } finally { if (inputStream != null) { try { inputStream.close() } catch (_: Exception) { } } } val text = context.getString(R.string.import_success) val duration = Toast.LENGTH_SHORT val toast = Toast.makeText(context, text, duration) toast.show() } suspend fun importDataFromCalendar(context: Context, calendarId: String) { val importedSleeps = CalendarImport.queryForEvents( context, calendarId ).map(CalendarImport::mapEventToSleep) val oldSleeps = database.sleepDao().getAll() val newSleeps = importedSleeps.subtract(oldSleeps.toSet()) insertSleeps(newSleeps.toList()) val text = context.resources.getQuantityString( R.plurals.imported_items, newSleeps.size, newSleeps.size ) val duration = Toast.LENGTH_SHORT val toast = Toast.makeText(context, text, duration) toast.show() } suspend fun exportDataToCalendar(context: Context, calendarId: String) { val calendarSleeps = CalendarImport.queryForEvents( context, calendarId ).map(CalendarImport::mapEventToSleep) val sleeps = database.sleepDao().getAll() val exportedSleeps = sleeps.subtract(calendarSleeps.toSet()) CalendarExport.exportSleep(context, calendarId, exportedSleeps.toList()) val text = context.resources.getQuantityString( R.plurals.exported_items, exportedSleeps.size, exportedSleeps.size ) val duration = Toast.LENGTH_SHORT val toast = Toast.makeText(context, text, duration) toast.show() } suspend fun backupSleeps(context: Context, cr: ContentResolver) { val autoBackup = preferences.getBoolean(""auto_backup"", false) val autoBackupPath = preferences.getString(""auto_backup_path"", """") if (!autoBackup || autoBackupPath == null || autoBackupPath.isEmpty()) { return } val folder = DocumentFile.fromTreeUri(context, Uri.parse(autoBackupPath)) ?: return val oldBackup = folder.findFile(""backup.csv"") if (oldBackup != null && oldBackup.exists()) { oldBackup.delete() } val backup = folder.createFile(""text/csv"", ""backup.csv"") ?: return exportDataToFile( context, cr, backup.uri, showToast = false ) } suspend fun exportDataToFile( context: Context, cr: ContentResolver, uri: Uri, showToast: Boolean ) { val sleeps = database.sleepDao().getAll() try { cr.takePersistableUriPermission( uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION ) } catch (e: SecurityException) { Log.e(TAG, ""exportData: takePersistableUriPermission() failed for write"") } val os: OutputStream? = cr.openOutputStream(uri) if (os == null) { Log.e(TAG, ""exportData: openOutputStream() failed"") return } try { val writer = CSVPrinter(OutputStreamWriter(os, ""UTF-8""), CSVFormat.DEFAULT) writer.printRecord(""sid"", ""start"", ""stop"", ""rating"", ""comment"") for (sleep in sleeps) { writer.printRecord(sleep.sid, sleep.start, sleep.stop, sleep.rating, sleep.comment) } writer.close() } catch (e: IOException) { Log.e(TAG, ""exportData: write() failed"") return } finally { try { os.close() } catch (_: Exception) { } } if (!showToast) { return } val text = context.getString(R.string.export_success) val duration = Toast.LENGTH_SHORT val toast = Toast.makeText(context, text, duration) toast.show() } private const val TAG = ""DataModel"" fun getSleepCountStat(sleeps: List): String { return sleeps.size.toString() } fun getSleepDurationStat(sleeps: List, compactView: Boolean): String { var sum: Long = 0 for (sleep in sleeps) { var diff = sleep.stop - sleep.start diff /= 1000 sum += diff } val count = sleeps.size return if (count == 0) { """" } else formatDuration(sum / count, compactView) } fun getSleepDurationDailyStat(sleeps: List, compactView: Boolean): String { // Day -> sum (in seconds) map. val sums = HashMap() var minKey: Long = Long.MAX_VALUE var maxKey: Long = 0 for (sleep in sleeps) { var diff = sleep.stop - sleep.start diff /= 1000 // Calculate stop day val stopDate = Calendar.getInstance() stopDate.timeInMillis = sleep.stop val day = Calendar.getInstance() day.timeInMillis = 0 val startYear = stopDate.get(Calendar.YEAR) day.set(Calendar.YEAR, startYear) val startMonth = stopDate.get(Calendar.MONTH) day.set(Calendar.MONTH, startMonth) val startDay = stopDate.get(Calendar.DAY_OF_MONTH) day.set(Calendar.DAY_OF_MONTH, startDay) val key = day.timeInMillis minKey = minOf(minKey, key) maxKey = maxOf(maxKey, key) val sum = sums[key] if (sum != null) { sums[key] = sum + diff } else { sums[key] = diff } } if (sums.size == 0) { return """" } val msPerDay = 86400 * 1000 val count = (maxKey - minKey) / msPerDay + 1 return formatDuration(sums.values.sum() / count, compactView) } fun formatDuration(seconds: Long, compactView: Boolean): String { if (compactView) { return String.format( Locale.getDefault(), ""%d:%02d"", seconds / 3600, seconds % 3600 / 60 ) } return String.format( Locale.getDefault(), ""%d:%02d:%02d"", seconds / 3600, seconds % 3600 / 60, seconds % 60 ) } fun formatTimestamp(date: Date, compactView: Boolean): String { val sdf = if (compactView) { SimpleDateFormat(""yyyy-MM-dd HH:mm"", Locale.getDefault()) } else if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { SimpleDateFormat(""yyyy-MM-dd HH:mm:ss XXX"", Locale.getDefault()) } else { SimpleDateFormat(""yyyy-MM-dd HH:mm:ss"", Locale.getDefault()) } return sdf.format(date) } fun filterSleeps(sleeps: List, after: Date): List { return sleeps.filter { it.stop > after.time } } }" Data model is the singleton shared state between the activity and the service. +"class UserEvent(cursor: Cursor) { val id: String = cursor.getString(CalendarImport.EVENT_PROJECTION_ID) val calendarId: String = cursor.getString(CalendarImport.EVENT_PROJECTION_CAL_ID) val title: String = cursor.getString(CalendarImport.EVENT_PROJECTION_TITLE) val start: Long = cursor.getLong(CalendarImport.EVENT_PROJECTION_START) val end: Long = cursor.getLong(CalendarImport.EVENT_PROJECTION_END) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as UserEvent if (id != other.id) return false if (calendarId != other.calendarId) return false if (title != other.title) return false if (start != other.start) return false if (end != other.end) return false return true } override fun hashCode(): Int { var result = id.hashCode() result = 31 * result + calendarId.hashCode() result = 31 * result + title.hashCode() result = 31 * result + start.hashCode() result = 31 * result + end.hashCode() return result } override fun toString(): String { return """""" UserEvent(id='$id', calendarId='$calendarId', title='$title', start='$start', end='$end') """""".trimIndent() } }" "Represents a single event record, as found in a user's calendar" +"class UserCalendar(cursor: Cursor) { val id: String = cursor.getString(CalendarImport.CALENDAR_PROJECTION_ID) val name: String = cursor.getString(CalendarImport.CALENDAR_PROJECTION_DISPLAY_NAME) val owner: String = cursor.getString(CalendarImport.CALENDAR_PROJECTION_ACCOUNT_NAME) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as UserCalendar if (id != other.id) return false if (name != other.name) return false if (owner != other.owner) return false return true } override fun hashCode(): Int { var result = id.hashCode() result = 31 * result + name.hashCode() result = 31 * result + owner.hashCode() return result } override fun toString(): String { return ""UserCalendar(id='$id', name='$name', owner='$owner')"" } }" "Represents a single calendar record, as found within the user's connected calendar" +fun Cursor.map(block: (Cursor) -> T): List { val items = mutableListOf() use { while (!it.isClosed && it.moveToNext()) { items += block(it) } } return items } Apply a transformation [block] to all records in a Cursor +"object CalendarImport { private const val DEFAULT_EVENT_TITLE = ""Sleep"" const val CALENDAR_PROJECTION_ID = 0 const val CALENDAR_PROJECTION_ACCOUNT_NAME = 1 const val CALENDAR_PROJECTION_DISPLAY_NAME = 2 private val CALENDAR_PROJECTION: Array = arrayOf( Calendars._ID, // 0 Calendars.ACCOUNT_NAME, // 1 Calendars.CALENDAR_DISPLAY_NAME, // 2 ) const val EVENT_PROJECTION_CAL_ID = 0 const val EVENT_PROJECTION_TITLE = 1 const val EVENT_PROJECTION_ID = 2 const val EVENT_PROJECTION_START = 3 const val EVENT_PROJECTION_END = 4 private val EVENT_PROJECTION: Array = arrayOf( Events.CALENDAR_ID, // 0 Events.TITLE, // 1 Events._ID, // 2 Events.DTSTART, // 3 Events.DTEND, // 4 ) fun queryForCalendars(context: Context): List { val uri: Uri = Calendars.CONTENT_URI val contentResolver: ContentResolver = context.contentResolver contentResolver.query( uri, CALENDAR_PROJECTION, null, null, null ).use { cursor -> return cursor?.map(::UserCalendar).orEmpty() } } fun queryForEvents( context: Context, calendarId: String, title: String = DEFAULT_EVENT_TITLE ): List { val uri = Events.CONTENT_URI val contentResolver: ContentResolver = context.contentResolver val selection = """""" (${Events.CALENDAR_ID} = ?) AND (${Events.TITLE} LIKE ? COLLATE NOCASE) AND (${Events.DTSTART} IS NOT NULL) AND (${Events.DTEND} IS NOT NULL AND ${Events.DTEND} != 0) """""".trimIndent() val selectionArgs = arrayOf(calendarId, ""%$title%"") contentResolver.query( uri, EVENT_PROJECTION, selection, selectionArgs, null ).use { cursor -> return cursor?.map(::UserEvent).orEmpty() } } fun mapEventToSleep(event: UserEvent): Sleep { return Sleep().apply { start = event.start stop = event.end } } }" Singleton helper for importing sleeps from a user's local calendars +"object CalendarExport { fun exportSleep(context: Context, calendarId: String, sleepList: List) { sleepList.forEach { sleep -> val values = ContentValues().apply { put(CalendarContract.Events.DTSTART, sleep.start) put(CalendarContract.Events.DTEND, sleep.stop) put(CalendarContract.Events.TITLE, context.getString(R.string.exported_event_title)) val description = context.getString(R.string.exported_event_description) put(CalendarContract.Events.DESCRIPTION, description) put(CalendarContract.Events.CALENDAR_ID, calendarId) put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().id) } context.contentResolver.insert(CalendarContract.Events.CONTENT_URI, values) } } }" Singleton helper for exporting sleeps to a user's local calendars and Exports a list of Sleep [sleepList] to the selected user calendar +"class ToggleWidget : AppWidgetProvider() { override fun onUpdate( context: Context?, appWidgetManager: AppWidgetManager?, appWidgetIds: IntArray? ) { if (context == null) { return } if (appWidgetManager == null) { return } if (appWidgetIds == null) { return } for (appWidgetId in appWidgetIds) { val intent = Intent(context, MainActivity::class.java) intent.putExtra(""startStop"", true) val pendingIntent = PendingIntent.getActivity( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT ) val remoteViews = RemoteViews(context.packageName, R.layout.widget_layout_toggle) remoteViews.setOnClickPendingIntent(R.id.widget_toggle, pendingIntent) appWidgetManager.updateAppWidget(appWidgetId, remoteViews) } } }" Provides a widget that opens the main activity and immediately toggles between started/stopped sleep tracking. +"@RequiresApi(api = Build.VERSION_CODES.N) class TileService : android.service.quicksettings.TileService() { override fun onStartListening() { refreshTile() } override fun onTileAdded() { refreshTile() } private fun refreshTile() { val preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext) DataModel.init(applicationContext, preferences) val active = DataModel.start != null && DataModel.stop == null if (active) { qsTile.state = Tile.STATE_ACTIVE } else { qsTile.state = Tile.STATE_INACTIVE } qsTile.updateTile() } override fun onClick() { try { if (qsTile.state == Tile.STATE_ACTIVE) { qsTile.state = Tile.STATE_INACTIVE } else { qsTile.state = Tile.STATE_ACTIVE } qsTile.updateTile() val intent = Intent(applicationContext, MainActivity::class.java) intent.putExtra(""startStop"", true) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivityAndCollapse(intent) } catch (e: Exception) { Log.e(TAG, ""onClick: uncaught exception: $e"") } } companion object { private const val TAG = ""TileService"" } }" Provides a quick settings tile that opens the main activity and immediately toggles between started/stopped sleep tracking. +"class StatsFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_stats, container, false) } }" "Shows stats, counting sleeps after a certain point in the past." +"class StatsActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_stats) title = getString(R.string.stats) // Show a back button. actionBar?.setDisplayHomeAsUpEnabled(true) DataModel.sleepsLive.observe( this, { sleeps -> if (sleeps != null) { val fragments = supportFragmentManager // Last week val lastWeek = Calendar.getInstance() lastWeek.add(Calendar.DATE, -7) val lastWeekSleeps = DataModel.filterSleeps(sleeps, lastWeek.time) val lastWeekFragment = fragments.findFragmentById(R.id.last_week_body) populateFragment(lastWeekFragment, lastWeekSleeps) // Last two weeks val lastTwoWeeks = Calendar.getInstance() lastTwoWeeks.add(Calendar.DATE, -14) val lastTwoWeekSleeps = DataModel.filterSleeps(sleeps, lastTwoWeeks.time) val lastTwoWeeksFragment = fragments.findFragmentById(R.id.last_two_weeks_body) populateFragment(lastTwoWeeksFragment, lastTwoWeekSleeps) // Last month val lastMonth = Calendar.getInstance() lastMonth.add(Calendar.DATE, -30) val lastMonthSleeps = DataModel.filterSleeps(sleeps, lastMonth.time) val lastMonthFragments = fragments.findFragmentById(R.id.last_month_body) populateFragment(lastMonthFragments, lastMonthSleeps) // Last year val lastYear = Calendar.getInstance() lastYear.add(Calendar.DATE, -365) val lastYearSleeps = DataModel.filterSleeps(sleeps, lastYear.time) val lastYearFragment = fragments.findFragmentById(R.id.last_year_body) populateFragment(lastYearFragment, lastYearSleeps) // All time, i.e. no filter val allTimeFragment = fragments.findFragmentById(R.id.all_time_body) populateFragment(allTimeFragment, sleeps) } } ) } private fun populateFragment(fragment: Fragment?, sleeps: List) { val view = fragment?.view val count = view?.findViewById(R.id.fragment_stats_sleeps) count?.text = DataModel.getSleepCountStat(sleeps) val average = view?.findViewById(R.id.fragment_stats_average) average?.text = DataModel.getSleepDurationStat(sleeps, DataModel.getCompactView()) val daily = view?.findViewById(R.id.fragment_stats_daily) daily?.text = DataModel.getSleepDurationDailyStat(sleeps, DataModel.getCompactView()) } }" "This activity provides additional stats for a limited period of time. This is in contrast with the main activity, which considers all sleeps within the specified duration." +inner class SleepViewHolder(view: View) : RecyclerView.ViewHolder(view) { val start: TextView = view.findViewById(R.id.sleep_item_start) val stop: TextView = view.findViewById(R.id.sleep_item_stop) val duration: TextView = view.findViewById(R.id.sleep_item_duration) val durationWakeImage: View = view.findViewById(R.id.wake_time_image) val durationWakeHeader: View = view.findViewById(R.id.wake_time_header) val durationWake: TextView = view.findViewById(R.id.wake_item_duration) val rating: RatingBar = view.findViewById(R.id.sleep_item_rating) val swipeable: View = view.findViewById(R.id.sleep_swipeable) private val deleteLeft: ImageView = view.findViewById(R.id.sleep_delete_left) private val deleteRight: ImageView = view.findViewById(R.id.sleep_delete_right) fun showSwipeDelete(left: Boolean) { deleteLeft.visibility = if (left) View.VISIBLE else View.INVISIBLE deleteRight.visibility = if (left) View.INVISIBLE else View.VISIBLE } } The view holder holds all views that will display one Sleep. +"class SleepsAdapter( private val preferences: SharedPreferences ) : RecyclerView.Adapter() { var data: List = ArrayList() set(newData) { val previousData = field field = newData DiffUtil.calculateDiff(object : DiffUtil.Callback() { override fun getOldListSize(): Int { return previousData.size } override fun getNewListSize(): Int { return newData.size } /** * Compares old and new based on their ID only. */ override fun areItemsTheSame( oldItemPosition: Int, newItemPosition: Int ): Boolean { val oldSid = previousData[oldItemPosition].sid val newSid = newData[newItemPosition].sid return oldSid == newSid } /** * Compares old and new based on their value. */ override fun areContentsTheSame( oldItemPosition: Int, newItemPosition: Int ): Boolean { return previousData[oldItemPosition] == newData[newItemPosition] } }).dispatchUpdatesTo(this) }" This is the adapter between RecyclerView and SleepDao. +"class SleepViewModel : ViewModel() { private var sleepCommentCallback: SleepCommentCallback? = null fun showSleep(activity: SleepActivity, sid: Int) { val viewModel = this viewModelScope.launch { val sleep = DataModel.getSleepById(sid) val start = activity.findViewById(R.id.sleep_start) start.text = DataModel.formatTimestamp(Date(sleep.start), DataModel.getCompactView()) val stop = activity.findViewById(R.id.sleep_stop) stop.text = DataModel.formatTimestamp(Date(sleep.stop), DataModel.getCompactView()) val rating = activity.findViewById(R.id.sleep_item_rating) rating.rating = sleep.rating.toFloat() rating.onRatingBarChangeListener = SleepRateCallback(viewModel, sleep) val comment = activity.findViewById(R.id.sleep_item_comment) viewModel.sleepCommentCallback?.let { comment.removeTextChangedListener(it) } comment.setText(sleep.comment) viewModel.sleepCommentCallback = SleepCommentCallback(viewModel, sleep) comment.addTextChangedListener(viewModel.sleepCommentCallback) } } fun editSleep( activity: SleepActivity, sid: Int, isStart: Boolean, context: Context, cr: ContentResolver ) { viewModelScope.launch { val sleep = DataModel.getSleepById(sid) val dateTime = Calendar.getInstance() dateTime.time = if (isStart) { Date(sleep.start) } else { Date(sleep.stop) } DatePickerDialog( activity, { _/*view*/, year, monthOfYear, dayOfMonth -> dateTime.set(year, monthOfYear, dayOfMonth) TimePickerDialog( activity, { _/*view*/, hourOfDay, minute -> dateTime[Calendar.HOUR_OF_DAY] = hourOfDay dateTime[Calendar.MINUTE] = minute if (isStart) { sleep.start = dateTime.time.time } else { sleep.stop = dateTime.time.time } if (sleep.start < sleep.stop) { updateSleep(activity, sleep, context, cr) } else { val text = context.getString(R.string.negative_duration) val duration = Toast.LENGTH_SHORT val toast = Toast.makeText(context, text, duration) toast.show() } }, dateTime[Calendar.HOUR_OF_DAY], dateTime[Calendar.MINUTE], /*is24HourView=*/DateFormat.is24HourFormat(activity) ).show() }, dateTime[Calendar.YEAR], dateTime[Calendar.MONTH], dateTime[Calendar.DATE] ).show() } } private fun updateSleep( activity: SleepActivity, sleep: Sleep, context: Context, cr: ContentResolver ) { viewModelScope.launch { DataModel.updateSleep(sleep) DataModel.backupSleeps(context, cr) showSleep(activity, sleep.sid) } } fun updateSleep(sleep: Sleep) { viewModelScope.launch { DataModel.updateSleep(sleep) } } }" "This is the view model of SleepActivity, providing coroutine scopes." +"class SleepTouchCallback( private val context: Context, private val contentResolver: ContentResolver, private val viewModel: MainViewModel, private val adapter: SleepsAdapter ) : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) { override fun onMove( recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder ): Boolean { return false } override fun onSwiped( viewHolder: RecyclerView.ViewHolder, direction: Int ) { val sleep = adapter.data[viewHolder.adapterPosition] viewModel.deleteSleep(sleep, context, contentResolver) val view = viewHolder.itemView val snackbar = Snackbar.make(view, R.string.deleted, Snackbar.LENGTH_LONG) snackbar.setAction(context.getString(R.string.undo)) { viewModel.insertSleep(sleep) } snackbar.show() } override fun onChildDraw( c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean ) { if (viewHolder is SleepsAdapter.SleepViewHolder) { viewHolder.showSwipeDelete(dX > 0) getDefaultUIUtil().onDraw( c, recyclerView, viewHolder.swipeable, dX, dY, actionState, isCurrentlyActive ) } } override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) { if (viewHolder is SleepsAdapter.SleepViewHolder) { getDefaultUIUtil().clearView(viewHolder.swipeable) } } }" This callback handles deletion of one recorded sleep in the sleep list. Listens to left/right swipes only. +"class SleepRateCallback( private val viewModel: SleepViewModel, private val sleep: Sleep ) : RatingBar.OnRatingBarChangeListener { override fun onRatingChanged(ratingBar: RatingBar?, rating: Float, fromUser: Boolean) { if (sleep.rating != rating.toLong()) { sleep.rating = rating.toLong() viewModel.updateSleep(sleep) } } }" This callback handles the rating of an individual sleep. +"@Dao interface SleepDao { @Query(""SELECT * FROM sleep ORDER BY sid ASC"") suspend fun getAll(): List @Query(""SELECT * FROM sleep ORDER BY start_date DESC"") fun getAllLive(): LiveData> @Query(""SELECT * from sleep where sid = :id LIMIT 1"") suspend fun getById(id: Int): Sleep @Query(""SELECT * FROM sleep WHERE stop_date > :after ORDER BY start_date DESC"") fun getAfterLive(after: Long): LiveData> @Insert suspend fun insert(sleepList: List) @Insert suspend fun insert(sleep: Sleep) @Update suspend fun update(sleep: Sleep) @Delete suspend fun delete(sleep: Sleep) @Query(""delete from sleep"") suspend fun deleteAll() }" Accesses the database of Sleep objects. +"class SleepClickCallback( private val mainActivity: MainActivity, private val adapter: SleepsAdapter, private val recyclerView: RecyclerView ) : View.OnClickListener { override fun onClick(view: View?) { if (view == null) { return } val itemPosition = recyclerView.getChildLayoutPosition(view) val sleep = adapter.data[itemPosition] val intent = Intent(mainActivity, SleepActivity::class.java) val bundle = Bundle() bundle.putInt(""sid"", sleep.sid) intent.putExtras(bundle) mainActivity.startActivity(intent) } }" This callback handles editing of one recorded sleep in the sleep list. Listens to clicks only. +"class SleepActivity : AppCompatActivity(), View.OnClickListener { private lateinit var viewModel: SleepViewModel private var sid: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = ViewModelProvider.NewInstanceFactory().create(SleepViewModel::class.java) setContentView(R.layout.activity_sleep) val start = findViewById(R.id.sleep_start) start.setOnClickListener(this) val stop = findViewById(R.id.sleep_stop) stop.setOnClickListener(this) val bundle = intent.extras ?: return sid = bundle.getInt(""sid"") title = String.format(getString(R.string.sleep_id), sid) // Show a back button. actionBar?.setDisplayHomeAsUpEnabled(true) viewModel.showSleep(this, sid) } override fun onClick(view: View?) { val isStart = view == findViewById(R.id.sleep_start) viewModel.editSleep(this, sid, isStart, applicationContext, contentResolver) } }" The activity is the editing UI of a single sleep. +"@Entity class Sleep { @PrimaryKey(autoGenerate = true) var sid: Int = 0 @ColumnInfo(name = ""start_date"") var start: Long = 0 @ColumnInfo(name = ""stop_date"") var stop: Long = 0 @ColumnInfo(name = ""rating"") var rating: Long = 0 @ColumnInfo(name = ""comment"") var comment: String = """" private val lengthMs get() = stop - start val lengthHours get() = lengthMs.toFloat() / DateUtils.HOUR_IN_MILLIS override fun equals(other: Any?): Boolean = other is Sleep && other.start == start && other.stop == stop override fun hashCode(): Int { var result = start.hashCode() result = 31 * result + stop.hashCode() return result } }" Represents one tracked sleep. +"class MainViewModel(application: Application) : AndroidViewModel(application) { private val preferences = PreferenceManager.getDefaultSharedPreferences(application) val durationSleepsLive: LiveData> = Transformations.switchMap(preferences.liveData(""dashboard_duration"", ""0"")) { durationStr -> val duration = durationStr?.toInt() ?: 0 val date = if (duration == 0) { Date(0) } else { val cal = Calendar.getInstance() cal.add(Calendar.DATE, duration) cal.time } DataModel.getSleepsAfterLive(date) } fun stopSleep(context: Context, cr: ContentResolver) { viewModelScope.launch { DataModel.storeSleep() DataModel.backupSleeps(context, cr) } } fun exportDataToFile(context: Context, cr: ContentResolver, uri: Uri, showToast: Boolean) { viewModelScope.launch { DataModel.exportDataToFile(context, cr, uri, showToast) } } fun importDataFromCalendar(context: Context, calendarId: String) { viewModelScope.launch { DataModel.importDataFromCalendar(context, calendarId) } } fun exportDataToCalendar(context: Context, calendarId: String) { viewModelScope.launch { DataModel.exportDataToCalendar(context, calendarId) } } fun importData(context: Context, cr: ContentResolver, uri: Uri) { viewModelScope.launch { DataModel.importData(context, cr, uri) } } fun insertSleep(sleep: Sleep) { viewModelScope.launch { DataModel.insertSleep(sleep) } } fun deleteSleep(sleep: Sleep, context: Context, cr: ContentResolver) { viewModelScope.launch { DataModel.deleteSleep(sleep) DataModel.backupSleeps(context, cr) } } fun deleteAllSleep() { viewModelScope.launch { DataModel.deleteAllSleep() } } }" "This is the view model of MainActivity, providing coroutine scopes." +"class MainService : Service() { override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { val channel = NotificationChannel( NOTIFICATION_CHANNEL_ID, getString(R.string.notification_channel_name), NotificationManager.IMPORTANCE_DEFAULT ) // Avoid unwanted vibration. channel.vibrationPattern = longArrayOf(0) channel.enableVibration(true) notificationManager.createNotificationChannel(channel) } val notificationIntent = Intent(this, MainActivity::class.java) val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, FLAG_IMMUTABLE) var contentText = """" DataModel.start?.let { start -> contentText = String.format( getString(R.string.sleeping_since), DataModel.formatTimestamp(start, DataModel.getCompactView()) ) } val notification = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID) .setContentText(contentText) .setSmallIcon(R.drawable.ic_launcher_foreground) .setContentIntent(pendingIntent) .build() startForeground(NOTIFICATION_CODE, notification) return START_STICKY } override fun onBind(intent: Intent): IBinder? { // We don't provide binding, so return null return null } companion object { private const val NOTIFICATION_CHANNEL_ID = ""Notification"" private const val NOTIFICATION_CODE = 1 } }" "A foreground service that just keeps the app alive, so the state is not lost while tracking is on." +"/** * The activity is the primary UI of the app: allows starting and stopping the * tracking. */ class MainActivity : AppCompatActivity(), View.OnClickListener { private lateinit var viewModel: MainViewModel // SharedPreferences keeps listeners in a WeakHashMap, so keep this as a member. private val sharedPreferenceListener = SharedPreferencesChangeListener() private val exportPermissionLauncher = registerForActivityResult( RequestMultiplePermissions() ) { permissions: Map -> checkCalendarPermissionGranted(permissions, ::exportCalendarData) } private val importPermissionLauncher = registerForActivityResult( RequestMultiplePermissions() ) { permissions: Map -> checkCalendarPermissionGranted(permissions, ::importCalendarData) } private val importActivityResult = registerForActivityResult(StartActivityForResult()) { result -> try { result.data?.data?.let { uri -> viewModel.importData(applicationContext, contentResolver, uri) updateView() } } catch (e: Exception) { Log.e(TAG, ""onActivityResult: importData() failed"") } } private val exportActivityResult = registerForActivityResult(StartActivityForResult()) { result -> try { result.data?.data?.let { uri -> viewModel.exportDataToFile( applicationContext, contentResolver, uri, showToast = true ) } } catch (e: Exception) { Log.e(TAG, ""onActivityResult: exportData() failed"") } } private fun setDashboardText(durationStr: String) { var index = resources.getStringArray(R.array.duration_entry_values).indexOf(durationStr) val durations = resources.getStringArray(R.array.duration_entries) if (index == -1) { index = durations.size - 1 // indexOf may return -1, which will out of bounds. } val durationHeaderStr = resources.getStringArray(R.array.duration_entries)[index] findViewById(R.id.dashboard_header)?.text = getString(R.string.dashboard, durationHeaderStr) } private fun handleIntent(intent: Intent?) { intent?.let { if (it.getBooleanExtra(""startStop"", false)) { onClick(findViewById(R.id.start_stop_layout)) } } } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) handleIntent(intent) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) sharedPreferenceListener.applyTheme(PreferenceManager.getDefaultSharedPreferences(this)) viewModel = ViewModelProvider.AndroidViewModelFactory(application) .create(MainViewModel::class.java) setContentView(R.layout.activity_main) val startStop = findViewById(R.id.start_stop_layout) startStop.setOnClickListener(this) val preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext) preferences.registerOnSharedPreferenceChangeListener(sharedPreferenceListener) DataModel.init(applicationContext, preferences) preferences.liveData(""dashboard_duration"", ""-7"").observe( this ) { setDashboardText(it ?: ""0"") } // Hide plain avg and avg(daily sum) if requested: preferences.liveDataBoolean(""show_average_sleep_durations"", false).observe( this ) { it?.let { val fragments = supportFragmentManager val stats = fragments.findFragmentById(R.id.dashboard_body)?.view val layout = stats?.findViewById(R.id.fragment_stats_average_layout) if (it) { layout?.visibility = View.VISIBLE } else { layout?.visibility = View.GONE } } } preferences.liveDataBoolean(""show_average_daily_sums"", true).observe( this ) { it?.let { val fragments = supportFragmentManager val stats = fragments.findFragmentById(R.id.dashboard_body)?.view val layout = stats?.findViewById(R.id.fragment_stats_daily_layout) if (it) { layout?.visibility = View.VISIBLE } else { layout?.visibility = View.GONE } } } val sleepsAdapter = SleepsAdapter(preferences) val recyclerView = findViewById(R.id.sleeps) viewModel.durationSleepsLive.observe( this ) { sleeps -> if (sleeps != null) { val fragments = supportFragmentManager val stats = fragments.findFragmentById(R.id.dashboard_body)?.view val countStat = stats?.findViewById(R.id.fragment_stats_sleeps) countStat?.text = DataModel.getSleepCountStat(sleeps) val durationStat = stats?.findViewById(R.id.fragment_stats_average) durationStat?.text = DataModel.getSleepDurationStat( sleeps, DataModel.getCompactView() ) val durationDailyStat = stats?.findViewById(R.id.fragment_stats_daily) durationDailyStat?.text = DataModel.getSleepDurationDailyStat( sleeps, DataModel.getCompactView() ) sleepsAdapter.data = sleeps // Set up placeholder text if there are no sleeps. val noSleepsView = findViewById(R.id.no_sleeps) if (sleeps.isEmpty()) { recyclerView.visibility = View.GONE noSleepsView.visibility = View.VISIBLE } else { recyclerView.visibility = View.VISIBLE noSleepsView.visibility = View.GONE } } } val recyclerViewLayout = LinearLayoutManager(this) recyclerView.layoutManager = recyclerViewLayout recyclerView.setHasFixedSize(true) recyclerView.itemAnimator = DefaultItemAnimator() recyclerView.adapter = sleepsAdapter // Enable separators between sleep items. val dividerItemDecoration = DividerItemDecoration( recyclerView.context, recyclerViewLayout.orientation ) recyclerView.addItemDecoration(dividerItemDecoration) sleepsAdapter.registerAdapterDataObserver( object : RecyclerView.AdapterDataObserver() { override fun onItemRangeInserted( positionStart: Int, itemCount: Int ) { recyclerView.scrollToPosition(positionStart) } }) // Otherwise swipe on a card view deletes it. val itemTouchHelper = ItemTouchHelper( SleepTouchCallback( applicationContext, contentResolver, viewModel, sleepsAdapter ) ) itemTouchHelper.attachToRecyclerView(recyclerView) val sleepClickCallback = SleepClickCallback(this, sleepsAdapter, recyclerView) sleepsAdapter.clickCallback = sleepClickCallback // Hide label of FAB on scroll. val fabText = findViewById(R.id.start_stop_text) val listener = View.OnScrollChangeListener { _, _, scrollY, _, oldScrollY -> if (scrollY > oldScrollY) { fabText.visibility = View.GONE } else { fabText.visibility = View.VISIBLE } } recyclerView.setOnScrollChangeListener(listener) // See if the activity is triggered from the widget. If so, toggle the start/stop state. handleIntent(intent) updateView() } override fun onStart() { super.onStart() val intent = Intent(this, MainService::class.java) stopService(intent) val recyclerView = findViewById(R.id.sleeps) recyclerView.findViewHolderForAdapterPosition(0)?.let { // Since the adapter unconditionally gets assigned in `onCreate()` // it shouldn't be necessary to consider fixing it here. // If it is null at this point a lot more must have gone wrong as well. recyclerView.adapter?.onBindViewHolder(it, 0) } } override fun onStop() { super.onStop() val intent = Intent(this, MainService::class.java) if (DataModel.start != null && DataModel.stop == null) { startService(intent) } } override fun onClick(view: View?) { when (view?.id) { R.id.start_stop_layout -> { if (DataModel.start != null && DataModel.stop == null) { DataModel.stop = Calendar.getInstance().time viewModel.stopSleep(applicationContext, contentResolver) } else { DataModel.start = Calendar.getInstance().time DataModel.stop = null } updateView() } } } private fun exportFileData() { val intent = Intent(Intent.ACTION_CREATE_DOCUMENT) intent.addCategory(Intent.CATEGORY_OPENABLE) intent.type = ""text/csv"" intent.putExtra(Intent.EXTRA_TITLE, ""plees-tracker.csv"") exportActivityResult.launch(intent) } private fun importFileData() { val intent = Intent(Intent.ACTION_GET_CONTENT) intent.type = ""text/*"" val mimeTypes = arrayOf(""text/csv"", ""text/comma-separated-values"") intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes) importActivityResult.launch(intent) } private fun createColorStateList(color: Int): ColorStateList { return ColorStateList.valueOf(ContextCompat.getColor(this, color)) } private fun updateView() { val status = findViewById(R.id.status) val startStopLayout = findViewById(R.id.start_stop_layout) val startStop = findViewById(R.id.start_stop) val startStopText = findViewById(R.id.start_stop_text) if (DataModel.start != null && DataModel.stop != null) { status.text = getString(R.string.tracking_stopped) startStop.contentDescription = getString(R.string.start_again) startStop.setImageResource(R.drawable.ic_start) startStopText.text = getString(R.string.start) // Set to custom, ~blue. startStop.backgroundTintList = createColorStateList(R.color.colorFabPrimary) startStopLayout.backgroundTintList = startStop.backgroundTintList return } DataModel.start?.let { start -> status.text = String.format( getString(R.string.sleeping_since), DataModel.formatTimestamp(start, DataModel.getCompactView()) ) startStop.contentDescription = getString(R.string.stop) startStop.setImageResource(R.drawable.ic_stop) startStopText.text = getString(R.string.stop) // Back to default, ~red. startStop.backgroundTintList = createColorStateList(R.color.colorFabAccent) startStopLayout.backgroundTintList = startStop.backgroundTintList return } // Set to custom, ~blue. startStop.backgroundTintList = createColorStateList(R.color.colorFabPrimary) startStopLayout.backgroundTintList = startStop.backgroundTintList } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.import_calendar_data -> { checkForCalendarPermission(importPermissionLauncher, ::importCalendarData) return true } R.id.import_file_data -> { importFileData() return true } R.id.export_file_data -> { exportFileData() return true } R.id.export_calendar_data -> { checkForCalendarPermission(exportPermissionLauncher, ::exportCalendarData) return true } R.id.about -> { LibsBuilder() .withActivityTitle(getString(R.string.about_toolbar)) .withAboutAppName(getString(R.string.app_name)) .withActivityStyle(Libs.ActivityStyle.LIGHT_DARK_TOOLBAR) .withAboutDescription(getString(R.string.app_description)) .start(this) return true } R.id.documentation -> { val website = getString(R.string.website_link) open(Uri.parse(website)) return true } R.id.settings -> { startActivity(Intent(this, PreferencesActivity::class.java)) return true } R.id.delete_all_sleep -> { val builder = AlertDialog.Builder(this) builder.setMessage(getString(R.string.delete_all_message)) .setCancelable(false) .setPositiveButton(getString(R.string.delete_all_positive)) { _, _ -> viewModel.deleteAllSleep() } .setNegativeButton(getString(R.string.delete_all_negative)) { dialog, _ -> dialog.dismiss() } val alert = builder.create() alert.show() return true } R.id.stats -> { startActivity(Intent(this, StatsActivity::class.java)) return true } R.id.graphs -> { startActivity(Intent(this, GraphsActivity::class.java)) return true } else -> return super.onOptionsItemSelected(item) } } private fun checkCalendarPermissionGranted( granted: Map, onSuccess: (UserCalendar) -> Unit ) { // Check all permissions were granted if (granted.values.all { it }) { // Start picker for calendar showUserCalendarPicker(onSuccess) } else { // Permission denied Toast.makeText( this, getString(R.string.calendar_permission_required), Toast.LENGTH_LONG ).show() } } private fun checkForCalendarPermission( permissionLauncher: ActivityResultLauncher>, block: (UserCalendar) -> Unit ) { when (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR)) { PackageManager.PERMISSION_GRANTED -> showUserCalendarPicker(block) else -> { // Directly ask for the permissions permissionLauncher.launch( arrayOf( Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR ) ) } } } private inline fun showUserCalendarPicker(crossinline block: (cal: UserCalendar) -> Unit) { // Fetch calendar data val calendars = CalendarImport.queryForCalendars(this) // No user calendars found, show dialog informing user if (calendars.isEmpty()) { showNoCalendarsFoundDialog() return } // Get name of calendar(s) val titles = calendars.map(UserCalendar::name).toTypedArray() var selectedItem = 0 // Show User Calendar picker MaterialAlertDialogBuilder(this) .setTitle(getString(R.string.select_calendar_dialog_title)) .setNeutralButton(getString(R.string.select_calendar_dialog_negative), null) .setPositiveButton(getString(R.string.select_calendar_dialog_positive)) { _, _ -> block.invoke(calendars[selectedItem]) }.setSingleChoiceItems(titles, selectedItem) { _, newSelection -> selectedItem = newSelection }.show() } private fun importCalendarData(selectedItem: UserCalendar) { viewModel.importDataFromCalendar(this, selectedItem.id) } private fun exportCalendarData(selectedItem: UserCalendar) { viewModel.exportDataToCalendar(this, selectedItem.id) } private fun showNoCalendarsFoundDialog() { MaterialAlertDialogBuilder(this) .setTitle(getString(R.string.select_calendar_dialog_title)) .setMessage(getString(R.string.import_dialog_error_message)) .setNegativeButton(getString(R.string.dismiss), null) .show() } private fun open(link: Uri) { val intent = Intent(Intent.ACTION_VIEW, link) startActivity(intent) } companion object { private const val TAG = ""MainActivity"" } }" "A foreground service that just keeps the app alive, so the state is not lost while tracking is on." +"@InstallIn(SingletonComponent::class) @Module class AppModule { @Provides fun provideWifiManager(@ApplicationContext context: Context): WifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager @Provides fun provideConnectivityManager(@ApplicationContext context: Context): ConnectivityManager = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager @Provides fun provideClipboardManager(@ApplicationContext context: Context): ClipboardManager = context.applicationContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager @ApplicationScope @Singleton @Provides fun providesApplicationScope( @DefaultDispatcher defaultDispatcher: CoroutineDispatcher ): CoroutineScope = CoroutineScope(SupervisorJob() + defaultDispatcher) @Singleton @Provides @MainThreadHandler fun provideMainThreadHandler(): IOSchedHandler = IOSchedMainHandler() @Singleton @Provides fun provideAnalyticsHelper( @ApplicationScope applicationScope: CoroutineScope, signInDelegate: SignInViewModelDelegate, preferenceStorage: PreferenceStorage ): AnalyticsHelper = FirebaseAnalyticsHelper(applicationScope, signInDelegate, preferenceStorage) @Singleton @Provides fun provideAgendaRepository(appConfigDataSource: AppConfigDataSource): AgendaRepository = DefaultAgendaRepository(appConfigDataSource) @Singleton @Provides fun provideAppDatabase(@ApplicationContext context: Context): AppDatabase { return AppDatabase.buildDatabase(context) } @Singleton @Provides fun provideGson(): Gson { return GsonBuilder().create() } }" "Defines all the classes that need to be provided in the scope of the app. Define here all objects that are shared throughout the app, like SharedPreferences, navigators or others. If some of those objects are singletons, they should be annotated with `@Singleton`." +"class AgendaHeadersDecoration( context: Context, blocks: List, inConferenceTimeZone: Boolean ) : ItemDecoration() { private val paint: TextPaint private val textWidth: Int private val decorHeight: Int private val verticalBias: Float init { val attrs = context.obtainStyledAttributes( R.style.Widget_IOSched_DateHeaders, R.styleable.DateHeader ) paint = TextPaint(Paint.ANTI_ALIAS_FLAG or Paint.SUBPIXEL_TEXT_FLAG).apply { color = attrs.getColorOrThrow(R.styleable.DateHeader_android_textColor) textSize = attrs.getDimensionOrThrow(R.styleable.DateHeader_android_textSize) try { typeface = ResourcesCompat.getFont( context, attrs.getResourceIdOrThrow(R.styleable.DateHeader_android_fontFamily) ) } catch (_: Exception) { // ignore } } textWidth = attrs.getDimensionPixelSizeOrThrow(R.styleable.DateHeader_android_width) val height = attrs.getDimensionPixelSizeOrThrow(R.styleable.DateHeader_android_height) val minHeight = ceil(paint.textSize).toInt() decorHeight = Math.max(height, minHeight) verticalBias = attrs.getFloat(R.styleable.DateHeader_verticalBias, 0.5f).coerceIn(0f, 1f) attrs.recycle() } // Get the block index:day and create header layouts for each private val daySlots: Map = indexAgendaHeaders(blocks).map { it.first to createHeader(context, it.second, inConferenceTimeZone) }.toMap() override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: State) { val position = parent.getChildAdapterPosition(view) outRect.top = if (daySlots.containsKey(position)) decorHeight else 0 } override fun onDraw(canvas: Canvas, parent: RecyclerView, state: State) { val layoutManager = parent.layoutManager ?: return val centerX = parent.width / 2f parent.forEach { child -> if (child.top < parent.height && child.bottom > 0) { // Child is visible val layout = daySlots[parent.getChildAdapterPosition(child)] if (layout != null) { val dx = centerX - (layout.width / 2) val dy = layoutManager.getDecoratedTop(child) + child.translationY + // offset vertically within the space according to the bias (decorHeight - layout.height) * verticalBias canvas.withTranslation(x = dx, y = dy) { layout.draw(this) } } } } } /** * Create a header layout for the given [time] */ private fun createHeader( context: Context, time: ZonedDateTime, inConferenceTimeZone: Boolean ): StaticLayout { val labelRes = TimeUtils.getLabelResForTime(time, inConferenceTimeZone) val text = context.getText(labelRes) return newStaticLayout(text, paint, textWidth, ALIGN_CENTER, 1f, 0f, false) } }" A [RecyclerView.ItemDecoration] which draws sticky headers marking the days in a given list of [Block]s. It also inserts gaps between days. +"fun indexAgendaHeaders(agendaItems: List): List> { return agendaItems .mapIndexed { index, block -> index to block.startTime } .distinctBy { it.second.dayOfMonth } }" Find the first block of each day (rounded down to nearest day) and return pairs of iindex to start time. Assumes that [agendaItems] are sorted by ascending start time. +"class WifiInstaller @Inject constructor( private val wifiManager: WifiManager, private val clipboardManager: ClipboardManager ) { fun installConferenceWifi(rawWifiConfig: WifiConfiguration): Boolean { val conferenceWifiConfig = rawWifiConfig.quoteSsidAndPassword() if (!wifiManager.isWifiEnabled) { wifiManager.isWifiEnabled = true } var success = false val netId = wifiManager.addNetwork(conferenceWifiConfig) if (netId != -1) { wifiManager.enableNetwork(netId, false) success = true } else { val clip: ClipData = ClipData.newPlainText( ""wifi_password"", conferenceWifiConfig.unquoteSsidAndPassword().preSharedKey ) clipboardManager.setPrimaryClip(clip) } return success } }" Installs WiFi on device given a WiFi configuration. +"object FirebaseAuthErrorCodeConverter { fun convert(code: Int): Int { return when (code) { ErrorCodes.NO_NETWORK -> { Timber.e(""FirebaseAuth error: no_network"") R.string.firebase_auth_no_network_connection } ErrorCodes.DEVELOPER_ERROR -> { Timber.e(""FirebaseAuth error: developer_error"") R.string.firebase_auth_unknown_error } ErrorCodes.PLAY_SERVICES_UPDATE_CANCELLED -> { Timber.e(""FirebaseAuth error: play_services_update_cancelled"") R.string.firebase_auth_unknown_error } ErrorCodes.PROVIDER_ERROR -> { Timber.e(""FirebaseAuth error: provider_error"") R.string.firebase_auth_unknown_error } else -> { Timber.e(""FirebaseAuth error: unknown_error"") R.string.firebase_auth_unknown_error } } } }" Converts [ErrorCodes] from firebase to translatable strings. +"@HiltViewModel class FeedViewModel @Inject constructor( private val loadCurrentMomentUseCase: LoadCurrentMomentUseCase, loadAnnouncementsUseCase: LoadAnnouncementsUseCase, private val loadStarredAndReservedSessionsUseCase: LoadStarredAndReservedSessionsUseCase, getTimeZoneUseCase: GetTimeZoneUseCase, getConferenceStateUseCase: GetConferenceStateUseCase, private val timeProvider: TimeProvider, private val analyticsHelper: AnalyticsHelper, private val signInViewModelDelegate: SignInViewModelDelegate, themedActivityDelegate: ThemedActivityDelegate, private val snackbarMessageManager: SnackbarMessageManager ) : ViewModel(), FeedEventListener, ThemedActivityDelegate by themedActivityDelegate, SignInViewModelDelegate by signInViewModelDelegate { companion object { // Show at max 10 sessions in the horizontal sessions list as user can click on // View All sessions and go to schedule to view the full list private const val MAX_SESSIONS = 10 // Indicates there is no header to show at the current time. private object NoHeader // Indicates there is no sessions related display on the home screen as the conference is // over. private object NoSessionsContainer } @Inject @JvmField @ReservationEnabledFlag var isReservationEnabledByRemoteConfig: Boolean = false @Inject @JvmField @MapFeatureEnabledFlag var isMapEnabledByRemoteConfig: Boolean = false // Exposed to the view as a StateFlow but it's a one-shot operation. val timeZoneId = flow { if (getTimeZoneUseCase(Unit).successOr(true)) { emit(TimeUtils.CONFERENCE_TIMEZONE) } else { emit(ZoneId.systemDefault()) } }.stateIn(viewModelScope, Eagerly, TimeUtils.CONFERENCE_TIMEZONE) private val loadSessionsResult: StateFlow>> = signInViewModelDelegate.userId .flatMapLatest { // TODO(jdkoren): might need to show sessions for not signed in users too... loadStarredAndReservedSessionsUseCase(it) } .stateIn(viewModelScope, WhileViewSubscribed, Result.Loading) private val conferenceState: StateFlow = getConferenceStateUseCase(Unit) .onEach { if (it is Result.Error) { snackbarMessageManager.addMessage(SnackbarMessage(R.string.feed_loading_error)) } } .map { it.successOr(UPCOMING) } .stateIn(viewModelScope, WhileViewSubscribed, UPCOMING) // SIDE EFFECTS: Navigation actions private val _navigationActions = Channel(capacity = Channel.CONFLATED) // Exposed with receiveAsFlow to make sure that only one observer receives updates. val navigationActions = _navigationActions.receiveAsFlow() private val currentMomentResult: StateFlow> = conferenceState.map { // Reload if conferenceState changes loadCurrentMomentUseCase(timeProvider.now()) }.stateIn(viewModelScope, WhileViewSubscribed, Result.Loading) private val loadAnnouncementsResult: StateFlow>> = flow { emit(loadAnnouncementsUseCase(timeProvider.now())) }.onEach { if (it is Result.Error) { snackbarMessageManager.addMessage(SnackbarMessage(R.string.feed_loading_error)) } }.stateIn(viewModelScope, WhileViewSubscribed, Result.Loading) private val announcementsPreview: StateFlow> = loadAnnouncementsResult.map { val announcementsHeader = AnnouncementsHeader( showPastNotificationsButton = it.successOr(emptyList()).size > 1 ) if (it is Result.Loading) { listOf(announcementsHeader, LoadingIndicator) } else { listOf( announcementsHeader, it.successOr(emptyList()).firstOrNull() ?: AnnouncementsEmpty ) } }.stateIn(viewModelScope, WhileViewSubscribed, emptyList()) private val feedSessionsContainer: Flow = loadSessionsResult .combine(timeZoneId) { sessions, timeZone -> createFeedSessionsContainer(sessions, timeZone) } private val sessionContainer: StateFlow = combine( feedSessionsContainer, conferenceState, signInViewModelDelegate.userInfo ) { sessionsContainer: FeedSessions, conferenceState: ConferenceState, userInfo: AuthenticatedUserInfo? -> val isSignedIn = userInfo?.isSignedIn() ?: false val isRegistered = userInfo?.isRegistered() ?: false if (conferenceState != ENDED && isSignedIn && isRegistered && isReservationEnabledByRemoteConfig ) { sessionsContainer } else { NoSessionsContainer } }.stateIn(viewModelScope, WhileViewSubscribed, NoSessionsContainer) private val currentFeedHeader: StateFlow = conferenceState.combine( currentMomentResult ) { conferenceStarted: ConferenceState, momentResult -> if (conferenceStarted == UPCOMING) { CountdownItem } else { // Use case can return null even on success, so replace nulls with a sentinel momentResult.successOr(null) ?: NoHeader } }.stateIn(viewModelScope, WhileViewSubscribed, NoHeader) // TODO: Replace Any with something meaningful. val feed: StateFlow> = combine( currentFeedHeader, sessionContainer, announcementsPreview ) { feedHeader: Any, sessionContainer: Any, announcementsPreview: List -> val feedItems = mutableListOf() if (feedHeader != NoHeader) { feedItems.add(feedHeader) } if (sessionContainer != NoSessionsContainer) { feedItems.add(sessionContainer) } feedItems .plus(announcementsPreview) .plus(FeedSustainabilitySection) .plus(FeedSocialChannelsSection) }.stateIn(viewModelScope, WhileViewSubscribed, emptyList()) private fun createFeedSessionsContainer( sessionsResult: Result>, timeZoneId: ZoneId ): FeedSessions { val sessions = sessionsResult.successOr(emptyList()) val now = ZonedDateTime.ofInstant(timeProvider.now(), timeZoneId) // TODO: Making conferenceState a sealed class and moving currentDay in STARTED // state might be a better option val currentDayEndTime = TimeUtils.getCurrentConferenceDay()?.end // Treat start of the conference as endTime as sessions shouldn't be shown if the // currentConferenceDay is null ?: ConferenceDays.first().start val upcomingReservedSessions = sessions .filter { it.userEvent.isReserved() && it.session.endTime.isAfter(now) && it.session.endTime.isBefore(currentDayEndTime) } .take(MAX_SESSIONS) val titleId = R.string.feed_sessions_title val actionId = R.string.feed_view_full_schedule return FeedSessions( titleId = titleId, actionTextId = actionId, userSessions = upcomingReservedSessions, timeZoneId = timeZoneId, isLoading = sessionsResult is Result.Loading, isMapFeatureEnabled = isMapEnabledByRemoteConfig ) } override fun openEventDetail(id: SessionId) { analyticsHelper.logUiEvent( ""Home to event detail"", AnalyticsActions.HOME_TO_SESSION_DETAIL ) _navigationActions.tryOffer(FeedNavigationAction.NavigateToSession(id)) } override fun openSchedule(showOnlyPinnedSessions: Boolean) { analyticsHelper.logUiEvent(""Home to Schedule"", AnalyticsActions.HOME_TO_SCHEDULE) _navigationActions.tryOffer(FeedNavigationAction.NavigateToScheduleAction) } override fun onStarClicked(userSession: UserSession) { TODO(""not implemented"") } override fun signIn() { analyticsHelper.logUiEvent(""Home to Sign In"", AnalyticsActions.HOME_TO_SIGN_IN) _navigationActions.tryOffer(FeedNavigationAction.OpenSignInDialogAction) } override fun openMap(moment: Moment) { analyticsHelper.logUiEvent(moment.title.toString(), AnalyticsActions.HOME_TO_MAP) _navigationActions.tryOffer( FeedNavigationAction.NavigateAction( FeedFragmentDirections.toMap( featureId = moment.featureId, startTime = moment.startTime.toEpochMilli() ) ) ) } override fun openLiveStream(liveStreamUrl: String) { analyticsHelper.logUiEvent(liveStreamUrl, AnalyticsActions.HOME_TO_LIVESTREAM) _navigationActions.tryOffer(FeedNavigationAction.OpenLiveStreamAction(liveStreamUrl)) } override fun openMapForSession(session: Session) { analyticsHelper.logUiEvent(session.id, AnalyticsActions.HOME_TO_MAP) val directions = FeedFragmentDirections.toMap( featureId = session.room?.id, startTime = session.startTime.toEpochMilli() ) _navigationActions.tryOffer(FeedNavigationAction.NavigateAction(directions)) } override fun openPastAnnouncements() { analyticsHelper.logUiEvent("""", AnalyticsActions.HOME_TO_ANNOUNCEMENTS) val directions = FeedFragmentDirections.toAnnouncementsFragment() _navigationActions.tryOffer(FeedNavigationAction.NavigateAction(directions)) } }" "Loads data and exposes it to the view. By annotating the constructor with [@Inject], Dagger will use that constructor when needing to create the object, so defining a [@Provides] method for this class won't be needed." +"abstract class FiltersFragment : Fragment() { companion object { private const val ALPHA_CONTENT_START = 0.1f private const val ALPHA_CONTENT_END = 0.3f } private lateinit var viewModel: FiltersViewModelDelegate private lateinit var filterAdapter: SelectableFilterChipAdapter private lateinit var binding: FragmentFiltersBinding private lateinit var behavior: BottomSheetBehavior<*> private var contentAlpha = ObservableFloat(1f) private val backPressedCallback = object : OnBackPressedCallback(false) { override fun handleOnBackPressed() { if (::behavior.isInitialized && behavior.state == STATE_EXPANDED) { behavior.state = STATE_HIDDEN } } } private var pendingSheetState = -1 abstract fun resolveViewModelDelegate(): FiltersViewModelDelegate override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requireActivity().onBackPressedDispatcher.addCallback(this, backPressedCallback) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentFiltersBinding.inflate(inflater, container, false).apply { lifecycleOwner = viewLifecycleOwner contentAlpha = this@FiltersFragment.contentAlpha } binding.recyclerviewFilters.doOnApplyWindowInsets { v, insets, padding -> val systemInsets = insets.getInsets( WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime() ) v.updatePadding(bottom = padding.bottom + systemInsets.bottom) } return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = resolveViewModelDelegate() binding.viewModel = viewModel behavior = BottomSheetBehavior.from(binding.filterSheet) filterAdapter = SelectableFilterChipAdapter(viewModel) binding.recyclerviewFilters.apply { adapter = filterAdapter setHasFixedSize(true) itemAnimator = null addOnScrollListener(object : OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { binding.filtersHeaderShadow.isActivated = recyclerView.canScrollVertically(-1) } }) addItemDecoration( FlexboxItemDecoration(context).apply { setDrawable(context.getDrawable(R.drawable.divider_empty_margin_small)) setOrientation(FlexboxItemDecoration.VERTICAL) } ) } val peekHeight = behavior.peekHeight val marginBottom = binding.root.marginBottom binding.root.doOnApplyWindowInsets { v, insets, _ -> val gestureInsets = insets.getInsets(WindowInsetsCompat.Type.systemGestures()) // Update the peek height so that it is above the navigation bar behavior.peekHeight = gestureInsets.bottom + peekHeight v.updateLayoutParams { bottomMargin = marginBottom + gestureInsets.top } } behavior.addBottomSheetCallback(object : BottomSheetCallback { override fun onSlide(bottomSheet: View, slideOffset: Float) { updateFilterContentsAlpha(slideOffset) } override fun onStateChanged(bottomSheet: View, newState: Int) { updateBackPressedCallbackEnabled(newState) } }) binding.collapseArrow.setOnClickListener { behavior.state = if (behavior.skipCollapsed) STATE_HIDDEN else STATE_COLLAPSED } binding.filterSheet.doOnLayout { val slideOffset = when (behavior.state) { STATE_EXPANDED -> 1f STATE_COLLAPSED -> 0f else /*BottomSheetBehavior.STATE_HIDDEN*/ -> -1f } updateFilterContentsAlpha(slideOffset) } if (pendingSheetState != -1) { behavior.state = pendingSheetState pendingSheetState = -1 } updateBackPressedCallbackEnabled(behavior.state) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) launchAndRepeatWithViewLifecycle { viewModel.filterChips.collect { filterAdapter.submitFilterList(it) } } } private fun updateFilterContentsAlpha(slideOffset: Float) { contentAlpha.set( slideOffsetToAlpha(slideOffset, ALPHA_CONTENT_START, ALPHA_CONTENT_END) ) } private fun updateBackPressedCallbackEnabled(state: Int) { backPressedCallback.isEnabled = !(state == STATE_COLLAPSED || state == STATE_HIDDEN) } fun showFiltersSheet() { if (::behavior.isInitialized) { behavior.state = STATE_EXPANDED } else { pendingSheetState = STATE_EXPANDED } } fun hideFiltersSheet() { if (::behavior.isInitialized) { behavior.state = STATE_HIDDEN } else { pendingSheetState = STATE_HIDDEN } } }" Fragment that shows the list of filters for the Schedule +"@DrawableRes fun getDrawableResourceForIcon(context: Context, iconType: String?): Int { if (iconType == null) { return 0 } return context.resources.getIdentifier( iconType.toLowerCase(Locale.US), ""drawable"", context.packageName ) }" "Returns the drawable resource id for an icon marker, or 0 if no resource with this name exists." +"private fun createIconMarker( context: Context, drawableRes: Int, title: String ): GeoJsonPointStyle { val bitmap = drawableToBitmap(context, drawableRes) val icon = BitmapDescriptorFactory.fromBitmap(bitmap) return GeoJsonPointStyle().apply { setAnchor(0.5f, 1f) setTitle(title) setIcon(icon) } }" Creates a GeoJsonPointStyle for a map icon. The icon is chosen based on the marker type and is anchored at the bottom center of the marker's location. +"enum class MapVariant( val start: Instant, val end: Instant, @StringRes val labelResId: Int, @DrawableRes val iconResId: Int, @RawRes val markersResId: Int, @RawRes val styleResId: Int, val mapTilePrefix: String ) { AFTER_DARK( ZonedDateTime.parse(BuildConfig.CONFERENCE_DAY1_AFTERHOURS_START).toInstant(), ZonedDateTime.parse(BuildConfig.CONFERENCE_DAY1_END).toInstant(), R.string.map_variant_after_dark, R.drawable.ic_map_after_dark, R.raw.map_markers_night, R.raw.map_style_night, ""night"" ), CONCERT( ZonedDateTime.parse(BuildConfig.CONFERENCE_DAY2_CONCERT_START).toInstant(), ZonedDateTime.parse(BuildConfig.CONFERENCE_DAY2_END).toInstant(), R.string.map_variant_concert, R.drawable.ic_map_concert, R.raw.map_markers_concert, R.raw.map_style_night, ""concert"" ), // Note: must be last to facilitate [forTime] DAY( ZonedDateTime.parse(BuildConfig.CONFERENCE_DAY1_START).toInstant(), ZonedDateTime.parse(BuildConfig.CONFERENCE_DAY3_END).toInstant(), R.string.map_variant_daytime, R.drawable.ic_map_daytime, R.raw.map_markers_day, R.raw.map_style_day, ""day"" ); operator fun contains(time: Instant): Boolean { return time in start..end } companion object { /** Returns the first variant containing the specified time, or [DAY] if none is found. */ fun forTime(time: Instant = Instant.now()): MapVariant { return values().find { variant -> time in variant } ?: DAY } } }" "A variant of the map UI. Depending on the variant, Map UI may show different markers, tile overlays, etc." +"fun Fragment.setupSnackbarManager( snackbarMessageManager: SnackbarMessageManager, fadingSnackbar: FadingSnackbar ) { launchAndRepeatWithViewLifecycle { snackbarMessageManager.currentSnackbar.collect { message -> if (message == null) { return@collect } val messageText = HtmlCompat.fromHtml( requireContext().getString(message.messageId, message.session?.title), FROM_HTML_MODE_LEGACY ) fadingSnackbar.show( messageText = messageText, actionId = message.actionId, longDuration = message.longDuration, actionClick = { snackbarMessageManager.processDismissedMessage(message) fadingSnackbar.dismiss() }, // When the snackbar is dismissed, ping the snackbar message manager in case there // are pending messages. dismissListener = { snackbarMessageManager.removeMessageAndLoadNext(message) } ) } } }" An extension for Fragments that sets up a Snackbar with a [SnackbarMessageManager]. +"@Singleton open class SnackbarMessageManager @Inject constructor( private val preferenceStorage: PreferenceStorage, @ApplicationScope private val coroutineScope: CoroutineScope, private val stopSnackbarActionUseCase: StopSnackbarActionUseCase ) { companion object { // Keep a fixed number of old items @VisibleForTesting const val MAX_ITEMS = 10 } private val messages = mutableListOf() private val _currentSnackbar = MutableStateFlow(null) val currentSnackbar: StateFlow = _currentSnackbar fun addMessage(msg: SnackbarMessage) { coroutineScope.launch { if (!shouldSnackbarBeIgnored(msg)) { // Limit amount of pending messages if (messages.size > MAX_ITEMS) { Timber.e(""Too many Snackbar messages. Message id: ${msg.messageId}"") return@launch } // If the new message is about the same change as a pending one, keep the old one. (rare) val sameRequestId = messages.find { it.requestChangeId == msg.requestChangeId } if (sameRequestId == null) { messages.add(msg) } loadNext() } } } private fun loadNext() { if (_currentSnackbar.value == null) { _currentSnackbar.value = messages.firstOrNull() } } fun removeMessageAndLoadNext(shownMsg: SnackbarMessage?) { messages.removeAll { it == shownMsg } if (_currentSnackbar.value == shownMsg) { _currentSnackbar.value = null } loadNext() } fun processDismissedMessage(message: SnackbarMessage) { if (message.actionId == R.string.dont_show) { coroutineScope.launch { stopSnackbarActionUseCase(true) } } } private suspend fun shouldSnackbarBeIgnored(msg: SnackbarMessage): Boolean { return preferenceStorage.isSnackbarStopped() && msg.actionId == R.string.dont_show } }" "A single source of Snackbar messages related to reservations. Only shows one Snackbar related to one change across all screens Emits new values on request (when a Snackbar is dismissed and ready to show a new message) It keeps a list of [MAX_ITEMS] items, enough to figure out if a message has already been shown, but limited to avoid wasting resources." +"@HiltViewModel class OnboardingViewModel @Inject constructor( private val onboardingCompleteActionUseCase: OnboardingCompleteActionUseCase, signInViewModelDelegate: SignInViewModelDelegate ) : ViewModel(), SignInViewModelDelegate by signInViewModelDelegate { private val _navigationActions = Channel(Channel.CONFLATED) val navigationActions = _navigationActions.receiveAsFlow() fun getStartedClick() { viewModelScope.launch { onboardingCompleteActionUseCase(true) _navigationActions.send(OnboardingNavigationAction.NavigateToMainScreen) } } fun onSigninClicked() { _navigationActions.tryOffer(OnboardingNavigationAction.NavigateToSignInDialog) } }" Records that onboarding has been completed and navigates user onward. +"class ViewPagerPager(private val viewPager: ViewPager) { private val fastOutSlowIn = AnimationUtils.loadInterpolator(viewPager.context, android.R.interpolator.fast_out_slow_in) fun advance() { if (viewPager.width <= 0) return val current = viewPager.currentItem val next = ((current + 1) % requireNotNull(viewPager.adapter).count) val pages = next - current val dragDistance = pages * viewPager.width ValueAnimator.ofInt(0, dragDistance).apply { var dragProgress = 0 var draggedPages = 0 addListener( onStart = { viewPager.beginFakeDrag() }, onEnd = { viewPager.endFakeDrag() } ) addUpdateListener { if (!viewPager.isFakeDragging) { return@addUpdateListener } val dragPoint = (animatedValue as Int) val dragBy = dragPoint - dragProgress viewPager.fakeDragBy(-dragBy.toFloat()) dragProgress = dragPoint val draggedPagesProgress = dragProgress / viewPager.width if (draggedPagesProgress != draggedPages) { viewPager.endFakeDrag() viewPager.beginFakeDrag() draggedPages = draggedPagesProgress } } duration = if (pages == 1) PAGE_CHANGE_DURATION else MULTI_PAGE_CHANGE_DURATION interpolator = fastOutSlowIn }.start() } companion object { private const val PAGE_CHANGE_DURATION = 400L private const val MULTI_PAGE_CHANGE_DURATION = 600L } }" Helper class for automatically scrolling pages of a [ViewPager] which does not allow you to customize the speed at which it changes page when directly setting the current page. +"@AndroidEntryPoint class WelcomeDuringConferenceFragment : Fragment() { private lateinit var binding: FragmentOnboardingWelcomeDuringBinding private val viewModel: OnboardingViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentOnboardingWelcomeDuringBinding.inflate(inflater, container, false).apply { lifecycleOwner = viewLifecycleOwner } return binding.root } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) binding.activityViewModel = viewModel binding.buttonSignin.doOnLayout { activity?.reportFullyDrawn() } } }" First page of onboarding showing a welcome message during the conference. +"@AndroidEntryPoint class RemoveReservationDialogFragment : AppCompatDialogFragment() { companion object { const val DIALOG_REMOVE_RESERVATION = ""dialog_remove_reservation"" private const val USER_ID_KEY = ""user_id"" private const val SESSION_ID_KEY = ""session_id"" private const val SESSION_TITLE_KEY = ""session_title"" fun newInstance( parameters: RemoveReservationDialogParameters ): RemoveReservationDialogFragment { val bundle = Bundle().apply { putString(USER_ID_KEY, parameters.userId) putString(SESSION_ID_KEY, parameters.sessionId) putString(SESSION_TITLE_KEY, parameters.sessionTitle) } return RemoveReservationDialogFragment().apply { arguments = bundle } } } private val viewModel: RemoveReservationViewModel by viewModels() override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val context = requireContext() val args = requireNotNull(arguments) val sessionTitle = requireNotNull(args.getString(SESSION_TITLE_KEY)) return MaterialAlertDialogBuilder(context) .setTitle(R.string.remove_reservation_title) .setMessage(formatRemoveReservationMessage(context.resources, sessionTitle)) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.remove) { _, _ -> viewModel.removeReservation() } .create() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val sessionId = arguments?.getString(SESSION_ID_KEY) if (sessionId == null) { dismiss() } return super.onCreateView(inflater, container, savedInstanceState) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) lifecycleScope.launch { lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.snackbarMessages.collect { // Using Toast instead of Snackbar as it's easier for DialogFragment Toast.makeText( requireContext(), it.messageId, if (it.longDuration) Toast.LENGTH_LONG else Toast.LENGTH_SHORT ).show() } } } } private fun formatRemoveReservationMessage( res: Resources, sessionTitle: String ): CharSequence { val text = res.getString(R.string.remove_reservation_content, sessionTitle) return text.makeBold(sessionTitle) } } data class RemoveReservationDialogParameters( val userId: String, val sessionId: SessionId, val sessionTitle: String )" Dialog that confirms the user really wants to cancel their reservation +"@AndroidEntryPoint class SwapReservationDialogFragment : AppCompatDialogFragment() { companion object { const val DIALOG_SWAP_RESERVATION = ""dialog_swap_reservation"" private const val USER_ID_KEY = ""user_id"" private const val FROM_ID_KEY = ""from_id"" private const val FROM_TITLE_KEY = ""from_title"" private const val TO_ID_KEY = ""to_id"" private const val TO_TITLE_KEY = ""to_title"" fun newInstance(parameters: SwapRequestParameters): SwapReservationDialogFragment { val bundle = Bundle().apply { putString(USER_ID_KEY, parameters.userId) putString(FROM_ID_KEY, parameters.fromId) putString(FROM_TITLE_KEY, parameters.fromTitle) putString(TO_ID_KEY, parameters.toId) putString(TO_TITLE_KEY, parameters.toTitle) } return SwapReservationDialogFragment().apply { arguments = bundle } } } @Inject lateinit var swapActionUseCase: SwapActionUseCase override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val context = requireContext() val args = requireNotNull(arguments) val userId = requireNotNull(args.getString(USER_ID_KEY)) val fromId = requireNotNull(args.getString(FROM_ID_KEY)) val fromTitle = requireNotNull(args.getString(FROM_TITLE_KEY)) val toId = requireNotNull(args.getString(TO_ID_KEY)) val toTitle = requireNotNull(args.getString(TO_TITLE_KEY)) return MaterialAlertDialogBuilder(context) .setTitle(R.string.swap_reservation_title) .setMessage(formatSwapReservationMessage(context.resources, fromTitle, toTitle)) .setNegativeButton(R.string.cancel, null) .setPositiveButton(R.string.swap) { _, _ -> viewLifecycleOwner.lifecycle.coroutineScope.launch { swapActionUseCase( SwapRequestParameters(userId, fromId, fromTitle, toId, toTitle) ) } } .create() } private fun formatSwapReservationMessage( res: Resources, fromTitle: String, toTitle: String ): CharSequence { val text = res.getString(R.string.swap_reservation_content, fromTitle, toTitle) return text.makeBold(fromTitle).makeBold(toTitle) } }" Dialog that confirms the user wants to replace their reservations +"class StarReserveFab( context: Context, attrs: AttributeSet ) : FloatingActionButton(context, attrs), Checkable { private var mode = RESERVE private var _checked = false set(value) { if (field != value || mode != STAR) { field = value currentDrawable = R.drawable.asld_star_event mode = STAR val contentDescRes = if (value) R.string.a11y_starred else R.string.a11y_unstarred contentDescription = context.getString(contentDescRes) refreshDrawableState() } } var reservationStatus: ReservationViewState? = null set(value) { if (value != field || mode != RESERVE) { field = value currentDrawable = R.drawable.asld_reservation mode = RESERVE if (value != null) { contentDescription = context.getString(value.contentDescription) } refreshDrawableState() } } @DrawableRes private var currentDrawable = 0 set(value) { if (field != value) { field = value setImageResource(value) } } override fun isChecked() = _checked override fun setChecked(checked: Boolean) { _checked = checked } override fun toggle() { _checked = !_checked } override fun onCreateDrawableState(extraSpace: Int): IntArray { if (!isShowingStar() && !isShowingReservation()) { return super.onCreateDrawableState(extraSpace) } val drawableState = super.onCreateDrawableState(extraSpace + 1) when { isShowingStar() -> { val state = if (_checked) stateChecked else stateUnchecked mergeDrawableStates(drawableState, state) } isShowingReservation() -> { mergeDrawableStates(drawableState, reservationStatus?.state) } } return drawableState } private fun isShowingReservation() = currentDrawable == R.drawable.asld_reservation private fun isShowingStar() = currentDrawable == R.drawable.asld_star_event companion object { private val stateChecked = intArrayOf(android.R.attr.state_checked) private val stateUnchecked = intArrayOf(-android.R.attr.state_checked) } }" +"class ReserveButton(context: Context, attrs: AttributeSet) : AppCompatImageButton(context, attrs) { var status = ReservationViewState.RESERVATION_DISABLED set(value) { if (value == field) return field = value contentDescription = context.getString(value.contentDescription) refreshDrawableState() } init { // Drawable defining drawables for each reservation state setImageResource(R.drawable.ic_reservation) status = ReservationViewState.RESERVABLE } override fun onCreateDrawableState(extraSpace: Int): IntArray { @Suppress(""SENSELESS_COMPARISON"") // Status is null during super init if (status == null) return super.onCreateDrawableState(extraSpace) val drawableState = super.onCreateDrawableState(extraSpace + 1) mergeDrawableStates(drawableState, status.state) return drawableState } }" "An [AppCompatImageButton] extension supporting multiple custom states, representing the status of a user's reservation for an event." +"enum class ReservationViewState( val state: IntArray, @StringRes val text: Int, @StringRes val contentDescription: Int ) { RESERVABLE( intArrayOf(R.attr.state_reservable), R.string.reservation_reservable, R.string.a11y_reservation_available ), WAIT_LIST_AVAILABLE( intArrayOf(R.attr.state_wait_list_available), R.string.reservation_waitlist_available, R.string.a11y_reservation_wait_list_available ), WAIT_LISTED( intArrayOf(R.attr.state_wait_listed), R.string.reservation_waitlisted, R.string.a11y_reservation_wait_listed ), RESERVED( intArrayOf(R.attr.state_reserved), R.string.reservation_reserved, R.string.a11y_reservation_reserved ), RESERVATION_PENDING( intArrayOf(R.attr.state_reservation_pending), R.string.reservation_pending, R.string.a11y_reservation_pending ), RESERVATION_DISABLED( intArrayOf(R.attr.state_reservation_disabled), R.string.reservation_disabled, R.string.a11y_reservation_disabled );" Models the different states of a reservation and a corresponding content description. +"class ReservationTextView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = android.R.attr.textViewStyle ) : AppCompatTextView(context, attrs, defStyleAttr) { var status = ReservationViewState.RESERVABLE set(value) { if (value == field) return field = value setText(value.text) refreshDrawableState() } init { setText(ReservationViewState.RESERVABLE.text) val drawable = context.getDrawable(R.drawable.asld_reservation) setCompoundDrawablesRelativeWithIntrinsicBounds(drawable, null, null, null) } override fun onCreateDrawableState(extraSpace: Int): IntArray { @Suppress(""SENSELESS_COMPARISON"") // Status is null during super init if (status == null) return super.onCreateDrawableState(extraSpace) val drawableState = super.onCreateDrawableState(extraSpace + 1) mergeDrawableStates(drawableState, status.state) return drawableState } } Footer" "An [AppCompatTextView] extension supporting multiple custom states, representing the status of a user's reservation for an event." +"fun indexSessionHeaders(sessions: List, zoneId: ZoneId): List> { return sessions .mapIndexed { index, session -> index to TimeUtils.zonedTime(session.startTime, zoneId) } .distinctBy { it.second.truncatedTo(ChronoUnit.MINUTES) } }" Find the first session at each start time (rounded down to nearest minute) and return pairs of index to start time. Assumes that [sessions] are sorted by ascending start time. +"@HiltViewModel class ScheduleViewModel @Inject constructor( private val loadScheduleUserSessionsUseCase: LoadScheduleUserSessionsUseCase, signInViewModelDelegate: SignInViewModelDelegate, scheduleUiHintsShownUseCase: ScheduleUiHintsShownUseCase, topicSubscriber: TopicSubscriber, private val snackbarMessageManager: SnackbarMessageManager, getTimeZoneUseCase: GetTimeZoneUseCase, private val refreshConferenceDataUseCase: RefreshConferenceDataUseCase, observeConferenceDataUseCase: ObserveConferenceDataUseCase ) : ViewModel(), SignInViewModelDelegate by signInViewModelDelegate { val timeZoneId = flow { if (getTimeZoneUseCase(Unit).successOr(true)) { emit(TimeUtils.CONFERENCE_TIMEZONE) } else { emit(ZoneId.systemDefault()) } }.stateIn(viewModelScope, Lazily, TimeUtils.CONFERENCE_TIMEZONE) val isConferenceTimeZone: StateFlow = timeZoneId.mapLatest { zoneId -> TimeUtils.isConferenceTimeZone(zoneId) }.stateIn(viewModelScope, Lazily, true) private lateinit var dayIndexer: ConferenceDayIndexer private val refreshSignal = MutableSharedFlow() private val loadDataSignal: Flow = flow { emit(Unit) emitAll(refreshSignal) }" "Loads data and exposes it to the view. By annotating the constructor with [@Inject], Dagger will use that constructor when needing to create the object, so defining a [@Provides] method for this class won't be needed." +"override fun onDrawOver(c: Canvas, parent: RecyclerView, state: State) { if (timeSlots.isEmpty() || parent.isEmpty()) return val isRtl = parent.isRtl() if (isRtl) { c.save() c.translate((parent.width - width).toFloat(), 0f) } val parentPadding = parent.paddingTop var earliestPosition = Int.MAX_VALUE var previousHeaderPosition = -1 var previousHasHeader = false var earliestChild: View? = null for (i in parent.childCount - 1 downTo 0) { val child = parent.getChildAt(i) if (child == null) { Timber.w( """"""View is null. Index: $i, childCount: ${parent.childCount}, |RecyclerView.State: $state"""""".trimMargin() ) continue } if (child.y > parent.height || (child.y + child.height) < 0) { continue } val position = parent.getChildAdapterPosition(child) if (position < 0) { continue } if (position < earliestPosition) { earliestPosition = position earliestChild = child } val header = timeSlots[position] if (header != null) { drawHeader(c, child, parentPadding, header, child.alpha, previousHasHeader) previousHeaderPosition = position previousHasHeader = true } else { previousHasHeader = false } } if (earliestChild != null && earliestPosition != previousHeaderPosition) { findHeaderBeforePosition(earliestPosition)?.let { stickyHeader -> previousHasHeader = previousHeaderPosition - earliestPosition == 1 drawHeader(c, earliestChild, parentPadding, stickyHeader, 1f, previousHasHeader) } } if (isRtl) { c.restore() } }" Loop over each child and draw any corresponding headers i.e. items who's position is a key in [timeSlots]. We also look back to see if there are any headers _before_ the first header we found i.e. which needs to be sticky. +"@InstallIn(FragmentComponent::class) @Module internal class SessionViewPoolModule { @FragmentScoped @Provides @Named(""sessionViewPool"") fun providesSessionViewPool(): RecyclerView.RecycledViewPool = RecyclerView.RecycledViewPool() @FragmentScoped @Provides @Named(""tagViewPool"") fun providesTagViewPool(): RecyclerView.RecycledViewPool = RecyclerView.RecycledViewPool() }" Provides [RecyclerView.RecycledViewPool]s to share views between [RecyclerView]s. E.g. Between different days of the schedule. +@InternalStreamChatApi public const val GIPHY_INFO_DEFAULT_WIDTH_DP: Int = 200 Default width used for Giphy Images if no width metadata is available. +@InternalStreamChatApi public const val GIPHY_INFO_DEFAULT_HEIGHT_DP: Int = 200 Default height used for Giphy Images if no width metadata is available. +"public fun Attachment.giphyInfo(field: GiphyInfoType): GiphyInfo? { val giphyInfoMap =(extraData[ModelType.attach_giphy] as? Map?)?.get(field.value) as? Map? return giphyInfoMap?.let { map -> GiphyInfo( url = map[""url""] ?: """", width = getGiphySize(map, ""width"", Utils.dpToPx(GIPHY_INFO_DEFAULT_WIDTH_DP)), height = getGiphySize(map, ""height"", Utils.dpToPx(GIPHY_INFO_DEFAULT_HEIGHT_DP)) ) } }" Returns an object containing extra information about the Giphy image based on its type. +"private fun getGiphySize(map: Map, size: String, defaultValue: Int): Int { return if (!map[size].isNullOrBlank()) map[size]?.toInt() ?: defaultValue else defaultValue }" Returns specified size for the giphy. +"public data class GiphyInfo( val url: String, @Px val width: Int, @Px val height: Int, )" Contains extra information about Giphy attachments. +"@OptIn(ExperimentalCoroutinesApi::class) @InternalStreamChatApi @Suppress(""TooManyFunctions"") public class MessageComposerController( private val channelId: String, private val chatClient: ChatClient = ChatClient.instance(), private val maxAttachmentCount: Int = AttachmentConstants.MAX_ATTACHMENTS_COUNT,private val maxAttachmentSize: Long = AttachmentConstants.MAX_UPLOAD_FILE_SIZE, ) { }" "Controller responsible for handling the composing and sending of messages. It acts as a central place for both the core business logic and state required to create and send messages, handle attachments, message actions and more. If you require more state and business logic, compose this Controller with your code and apply the necessary changes." +private val scope = CoroutineScope(DispatcherProvider.Immediate) Creates a [CoroutineScope] that allows us to cancel the ongoing work when the parent  ViewModel is disposed. +"public var typingUpdatesBuffer: TypingUpdatesBuffer = DefaultTypingUpdatesBuffer( onTypingStarted = ::sendKeystrokeEvent, onTypingStopped = ::sendStopTypingEvent, coroutineScope = scope )" Buffers typing updates. +"public val channelState: Flow = chatClient.watchChannelAsState( cid = channelId, messageLimit = DefaultMessageLimit, coroutineScope = scope ).filterNotNull()" Holds information about the current state of the [Channel]. +"public val ownCapabilities: StateFlow> = channelState.flatMapLatest { it.channelData } .map { it.ownCapabilities } .stateIn( scope = scope, started = SharingStarted.Eagerly, initialValue = setOf() )" Holds information about the abilities the current user is able to exercise in the given channel. +"private val canSendTypingUpdates = ownCapabilities.map { it.contains(ChannelCapabilities.SEND_TYPING_EVENTS) } .stateIn( scope = scope, started = SharingStarted.Eagerly, initialValue = false )" Signals if the user's typing will send a typing update in the given channel. +"private val canSendLinks = ownCapabilities.map { it.contains(ChannelCapabilities.SEND_LINKS) }.stateIn(scope = scope,started = SharingStarted.Eagerly,initialValue = false)" Signals if the user is allowed to send links. +"private val isSlowModeActive = ownCapabilities.map { it.contains(ChannelCapabilities.SLOW_MODE) } .stateIn( scope = scope, started = SharingStarted.Eagerly, initialValue = false )" Signals if the user needs to wait before sending the next message. +public val state: MutableStateFlow = MutableStateFlow(MessageComposerState()) Full message composer state holding all the required information. +"public val input: MutableStateFlow = MutableStateFlow("""")" UI state of the current composer input. +public val alsoSendToChannel: MutableStateFlow = MutableStateFlow(false) If the message will be shown in the channel after it is sent. +public val cooldownTimer: MutableStateFlow = MutableStateFlow(0) Represents the remaining time until the user is allowed to send the next message. +public val selectedAttachments: MutableStateFlow> = MutableStateFlow(emptyList()) "Represents the currently selected attachments, that are shown within the composer UI." +public val validationErrors: MutableStateFlow> = MutableStateFlow(emptyList()) Represents the list of validation errors for the current text input and the currently selected attachments. +public val mentionSuggestions: MutableStateFlow> = MutableStateFlow(emptyList()) Represents the list of users that can be used to autocomplete the current mention input. +public val commandSuggestions: MutableStateFlow> = MutableStateFlow(emptyList()) Represents the list of commands that can be executed for the channel. +private var users: List = emptyList() Represents the list of users in the channel. +private var commands: List = emptyList() Represents the list of available commands in the channel. +private var maxMessageLength: Int = DefaultMaxMessageLength Represents the maximum allowed message length in the message input. +private var cooldownTimerJob: Job? = null Represents the coroutine [Job] used to update the countdown +private var cooldownInterval: Int = 0 Represents the cooldown interval in seconds. +public val messageMode: MutableStateFlow = MutableStateFlow(MessageMode.Normal) "Current message mode, either [MessageMode.Normal] or [MessageMode.MessageThread]. Used to determine if we're sending a thread reply or a regular message." +public val messageActions: MutableStateFlow> = MutableStateFlow(mutableSetOf()) "Set of currently active message actions. These are used to display different UI in the composer, as well as help us decorate the message with information, such as the quoted message id." +public val lastActiveAction: Flow get() = messageActions.map { actions -> actions.lastOrNull { it is Edit || it is Reply } } "Represents a Flow that holds the last active [MessageAction] that is either the [Edit], [Reply]." +private val activeAction: MessageAction? get() = messageActions.value.lastOrNull { it is Edit || it is Reply } "Gets the active [Edit] or [Reply] action, whichever is last, to show on the UI." +private val isInEditMode: Boolean get() = activeAction is Edit "Gives us information if the active action is Edit, for business logic purposes." +private val parentMessageId: String? get() = (messageMode.value as? MessageMode.MessageThread)?.parentMessage?.id "Gets the parent message id if we are in thread mode, or null otherwise." +private val messageText: String get() = input.value Gets the current text input in the message composer.  +private val isInThread: Boolean get() = messageMode.value is MessageMode.MessageThread "Gives us information if the composer is in the ""thread"" mode." +private val selectedMentions: MutableSet = mutableSetOf() Represents the selected mentions based on the message suggestion list. +init { channelState.flatMapLatest { it.channelConfig }.onEach { maxMessageLength = it.maxMessageLength commands = it.commands state.value = state.value.copy(hasCommands = commands.isNotEmpty()) }.launchIn(scope)  channelState.flatMapLatest { it.members }.onEach { members -> users = members.map { it.user } }.launchIn(scope)  channelState.flatMapLatest { it.channelData }.onEach { cooldownInterval = it.cooldown }.launchIn(scope)  setupComposerState() } Sets up the data loading operations such as observing the maximum allowed message length. +private fun setupComposerState() { input.onEach { input -> state.value = state.value.copy(inputValue = input) }.launchIn(scope)  selectedAttachments.onEach { selectedAttachments -> state.value = state.value.copy(attachments = selectedAttachments) }.launchIn(scope)  lastActiveAction.onEach { activeAction -> state.value = state.value.copy(action = activeAction) }.launchIn(scope)  validationErrors.onEach { validationErrors -> state.value = state.value.copy(validationErrors = validationErrors) }.launchIn(scope)  mentionSuggestions.onEach { mentionSuggestions -> state.value = state.value.copy(mentionSuggestions = mentionSuggestions) }.launchIn(scope)  commandSuggestions.onEach { commandSuggestions -> state.value = state.value.copy(commandSuggestions = commandSuggestions) }.launchIn(scope)  cooldownTimer.onEach { cooldownTimer -> state.value = state.value.copy(coolDownTime = cooldownTimer) }.launchIn(scope)  messageMode.onEach { messageMode -> state.value = state.value.copy(messageMode = messageMode) }.launchIn(scope)  alsoSendToChannel.onEach { alsoSendToChannel -> state.value = state.value.copy(alsoSendToChannel = alsoSendToChannel) }.launchIn(scope)  ownCapabilities.onEach { ownCapabilities -> state.value = state.value.copy(ownCapabilities = ownCapabilities) }.launchIn(scope) } Sets up the observing operations for various composer states. +public fun setMessageInput(value: String) { this.input.value = value  if (canSendTypingUpdates.value) { typingUpdatesBuffer.onKeystroke() } handleMentionSuggestions() handleCommandSuggestions() handleValidationErrors() } Called when the input changes and the internal state needs to be updated. +public fun setMessageMode(messageMode: MessageMode) { this.messageMode.value = messageMode } Called when the message mode changes and the internal state needs to be updated. +public fun setAlsoSendToChannel(alsoSendToChannel: Boolean) { this.alsoSendToChannel.value = alsoSendToChannel } "Called when the ""Also send as a direct message"" checkbox is checked or unchecked." +"public fun performMessageAction(messageAction: MessageAction) { when (messageAction) { is ThreadReply -> { setMessageMode(MessageMode.MessageThread(messageAction.message)) } is Reply -> { messageActions.value = messageActions.value + messageAction } is Edit -> { input.value = messageAction.message.text selectedAttachments.value = messageAction.message.attachments messageActions.value = messageActions.value + messageAction } else -> { // no op, custom user action } } }" Handles selected [messageAction]. We only have three actions we can react to in the composer: +"public fun dismissMessageActions() { if (isInEditMode) { setMessageInput("""") this.selectedAttachments.value = emptyList(  }) this.messageActions.value = emptySet() }" Dismisses all message actions from the UI and clears the input if [isInEditMode] is true. +public fun addSelectedAttachments(attachments: List) { val newAttachments = (selectedAttachments.value + attachments).distinctBy { if (it.name != null) { it.name } else { it } } selectedAttachments.value = newAttachments  handleValidationErrors() } "Stores the selected attachments from the attachment picker. These will be shown in the UI, within the composer component. We upload and send these attachments once the user taps on the send button." +public fun removeSelectedAttachment(attachment: Attachment) { selectedAttachments.value = selectedAttachments.value - attachment  handleValidationErrors() } "Removes a selected attachment from the list, when the user taps on the cancel/delete button." +"public fun clearData() { input.value = """" selectedAttachments.value = emptyList() validationErrors.value = emptyList() alsoSendToChannel.value = false }" Clears all the data from the input - both the current [input] value and the [selectedAttachments]. +"public fun sendMessage(message: Message) { val activeMessage = activeAction?.message ?: message val sendMessageCall = if (isInEditMode && !activeMessage.isModerationFailed(chatClient)) { getEditMessageCall(message) } else { message.showInChannel = isInThread && alsoSendToChannel.value val (channelType, channelId) = message.cid.cidToTypeAndId() if (activeMessage.isModerationFailed(chatClient)) { chatClient.deleteMessage(activeMessage.id, true).enqueue() }  chatClient.sendMessage(channelType, channelId, message) }  dismissMessageActions() clearData()  sendMessageCall.enqueueAndHandleSlowMode() }" "Sends a given message using our Stream API. Based on [isInEditMode], we either edit an existing message, or we send a new message, using [ChatClient]. In case the message is a moderated message the old one is deleted before the replacing one is sent." +"public fun buildNewMessage( message: String, attachments: List = emptyList(), ): Message { val activeAction = activeAction  val trimmedMessage = message.trim() val activeMessage = activeAction?.message ?: Message() val replyMessageId = (activeAction as? Reply)?.message?.id val mentions = filterMentions(selectedMentions, trimmedMessage)  return if (isInEditMode && !activeMessage.isModerationFailed(chatClient)) { activeMessage.copy( text = trimmedMessage, attachments = attachments.toMutableList(), mentionedUsersIds = mentions ) } else { Message( cid = channelId, text = trimmedMessage, parentId = parentMessageId, replyMessageId = replyMessageId, attachments = attachments.toMutableList(), mentionedUsersIds = mentions ) } }" "Builds a new [Message] to send to our API. If [isInEditMode] is true, we use the current action's message and apply the given changes." +"private fun filterMentions(selectedMentions: Set, message: String): MutableList {val text = message.lowercase()val remainingMentions =selectedMentions.filter {text.contains(""@${it.name.lowercase()}"")}.map { it.id }this.selectedMentions.clear()return remainingMentions.toMutableList()}" Filters the current input and the mentions the user selected from the suggestion list. Removes any mentions which are selected but no longer present in the input. +public fun leaveThread() {setMessageMode(MessageMode.Normal)dismissMessageActions() } "Updates the UI state when leaving the thread, to switch back to the [MessageMode.Normal], by calling [setMessageMode]." +public fun onCleared() {typingUpdatesBuffer.clear()scope.cancel()} Cancels any pending work when the parent ViewModel is about to be destroyed. +"private fun handleValidationErrors() {validationErrors.value = mutableListOf().apply {val message = input.valueval messageLength = message.length if (messageLength > maxMessageLength) {add( ValidationError.MessageLengthExceeded(messageLength = messageLength,maxMessageLength = maxMessageLength))} val attachmentCount = selectedAttachments.value.size if (attachmentCount > maxAttachmentCount) { add( ValidationError.AttachmentCountExceeded( attachmentCount = attachmentCount, maxAttachmentCount = maxAttachmentCount ) ) }  val attachments: List = selectedAttachments.value .filter { it.fileSize > maxAttachmentSize } if (attachments.isNotEmpty()) { add( ValidationError.AttachmentSizeExceeded( attachments = attachments, maxAttachmentSize = maxAttachmentSize ) ) } if (!canSendLinks.value && message.containsLinks()) { add( ValidationError.ContainsLinksWhenNotAllowed ) } } }" Checks the current input for validation errors. +"public fun selectMention(user: User) { val augmentedMessageText = ""${messageText.substringBeforeLast(""@"")}@${user.name} ""  setMessageInput(augmentedMessageText) selectedMentions += user }" Autocompletes the current text input with the mention from the selected user. +"public fun selectCommand(command: Command) { setMessageInput(""/${command.name} "") }" Switches the message composer to the command input mode. +public fun toggleCommandsVisibility() { val isHidden = commandSuggestions.value.isEmpty()  commandSuggestions.value = if (isHidden) commands else emptyList() } Toggles the visibility of the command suggestion list popup. +public fun dismissSuggestionsPopup() { mentionSuggestions.value = emptyList() commandSuggestions.value = emptyList() } Dismisses the suggestions popup above the message composer. +"private fun handleMentionSuggestions() { val containsMention = MentionPattern.matcher(messageText).find()  mentionSuggestions.value = if (containsMention) { users.filter { it.name.contains(messageText.substringAfterLast(""@""), true) } } else { emptyList() } }" Shows the mention suggestion list popup if necessary. +"private fun handleCommandSuggestions() { val containsCommand = CommandPattern.matcher(messageText).find()  commandSuggestions.value = if (containsCommand && selectedAttachments.value.isEmpty()) { val commandPattern = messageText.removePrefix(""/"") commands.filter { it.name.startsWith(commandPattern) } } else { emptyList() } }" Shows the command suggestion list popup if necessary. +private fun Call.enqueueAndHandleSlowMode() { if (cooldownInterval > 0 && isSlowModeActive.value && !isInEditMode) { cooldownTimerJob?.cancel()  cooldownTimer.value = cooldownInterval enqueue { if (it.isSuccess || !chatClient.clientState.isNetworkAvailable) { cooldownTimerJob = scope.launch { for (timeRemaining in cooldownInterval downTo 0) { cooldownTimer.value = timeRemaining delay(OneSecond) } } } else { cooldownTimer.value = 0 } } } else { enqueue() } } Executes the message Call and shows cooldown countdown timer instead of send button when slow mode is enabled.  +private fun getEditMessageCall(message: Message): Call { return chatClient.updateMessage(message) } Gets the edit message call using [ChatClient]. +"private fun sendKeystrokeEvent() { val (type, id) = channelId.cidToTypeAndId()  chatClient.keystroke(type, id, parentMessageId).enqueue() }" Makes an API call signaling that a typing event has occurred. +"private fun sendStopTypingEvent() { val (type, id) = channelId.cidToTypeAndId()  chatClient.stopTyping(type, id, parentMessageId).enqueue() }" Makes an API call signaling that a stop typing event has occurred. +public sealed class ModeratedMessageOption(public val text: Int) Represents possible options user can take upon moderating a message. +public object SendAnyway : ModeratedMessageOption(R.string.stream_ui_moderation_dialog_send) Prompts the user to send the message anyway if the message was flagged by moderation. +public object EditMessage : ModeratedMessageOption(R.string.stream_ui_moderation_dialog_edit) Prompts the user to edit the message if the message was flagged by moderation. +public object DeleteMessage : ModeratedMessageOption(R.string.stream_ui_moderation_dialog_delete) Prompts the user to delete the message if the message was flagged by moderation. +"public class CustomModerationOption( text: Int, public val extraData: Map = emptyMap(), ) : ModeratedMessageOption(text)" Custom actions that you can define for moderated messages. +"@InternalStreamChatApi public fun defaultMessageModerationOptions(): List = listOf( SendAnyway, EditMessage, DeleteMessage )" return A list of [ModeratedMessageOption] to show to the user. +"@StreamHandsOff( reason = ""This class shouldn't be renamed without verifying it works correctly on Chat Client Artifacts because "" + ""we are using it by reflection"" ) public class StreamCoilUserIconBuilder(private val context: Context) : UserIconBuilder { override suspend fun buildIcon(user: User): IconCompat? = StreamImageLoader .instance() .loadAsBitmap(context, user.image, StreamImageLoader.ImageTransformation.Circle) ?.let(IconCompat::createWithBitmap) }" "Produces an [IconCompat] using Coil, which downloads and caches the user image." +public class CoilDisposable(private val disposable: coil.request.Disposable) : Disposable {override val isDisposed: Boolean get() = disposable.isDisposed Wrapper around the Coil Disposable. +override fun dispose() { disposable.dispose() } } Dispose all the source. Use it when the resource is already used or the result is no longer needed. +"private fun setPassword(value:String) { _uiState.value = uiState.value.copy(password = InputWrapper(value = value)) viewModelScope.launch(Dispatchers.IO) { when(val error = getPasswordFieldErrors()) {null -> { _uiState.value = uiState.value.copy( passErrorState = PasswordErrorState( length = false, lowerUpper = false, containsNumber = false, containsSpecial = false ) ) } else -> { _uiState.value = uiState.value.copy( passErrorState = PasswordErrorState( length = error.validLength, lowerUpper = error.validLowerUpper, containsNumber = error.validNumber, containsSpecial = error.validSpecial ) ) } } } }" Function to save the user entered password in the UI state Also handles the error state for the password requirements +"private fun setCompanyName(companyName: String) { _uiState.value = uiState.value.copy(companyName = InputWrapper(value = companyName, errorId = null) ) }" This method save company name entered in the UI form +"private fun setAddress( address1: String? = null, address2: String? = null, address3: String? = null, city: String? = null, zipcode: String? = null ) { if (address1 != null) { _uiState.value = uiState.value.copy( addressFields = _uiState.value.addressFields.copy( address1 = InputWrapper(value = address1, errorId = null) ) ) } if (address2 != null) { _uiState.value = uiState.value.copy( addressFields = _uiState.value.addressFields.copy( address2 = InputWrapper(value = address2, errorId = null) ) ) } if (address3 != null) { _uiState.value = uiState.value.copy( addressFields = _uiState.value.addressFields.copy( address3 = InputWrapper(value = address3, errorId = null) ) ) } if (city != null) { _uiState.value = uiState.value.copy( addressFields = _uiState.value.addressFields.copy( city = InputWrapper(value = city, errorId = null) ) ) } if (zipcode != null) { _uiState.value = uiState.value.copy( addressFields = _uiState.value.addressFields.copy( zipcode = InputWrapper(value = zipcode, errorId = null) ) ) } }" This method save the address fields in the UI form +private fun setConfirmPassword(value: String) { _uiState.value = uiState.value.copy(confirmPassword = InputWrapper(value = value)) } Function to save the user entered confirm password in the UI state +private fun userNameChanged(userName: String) { _uiState.value = uiState.value.copy(userName = InputWrapper(value = userName)) } Function to change the username +"private fun useEmailAsUserName(value: Boolean) { _uiState.value = uiState.value.copy( emailAsUser = value, userName = uiState.value.email ) }" Function to change the state of the checkbox for user email as username +private fun matchResultSelected(result: MatchResult) {_uiState.value = uiState.value.copy( selectedMatchResult = result ) } Saves the selected Matched result from the DuplicateCheck Screen in the UI State this will be useful in further userflow of Contact Admin +private fun yourNameUpdated(name: String) { _uiState.value = uiState.value.copy( yourName = InputWrapper(value = name) ) } This function save and updated the UIState with the user provided input for UserName +private fun userPhoneUpdated(number: String) { _uiState.value = uiState.value.copy( userPhone = InputWrapper(value = number) ) } This function saves and updates the UIState with the user provided input for Phone number +private fun userMessageUpdated(message: String) { _uiState.value = uiState.value.copy( userMessage = InputWrapper(value = message) ) } This function updates the custom user message entered +"private fun sendEmailClicked() { ReCaptchaService.validateWithEnterpriseReCaptchaService( null, ReCaptchaEventEnum.CONTACT_ADMIN) }" This function trigger the user flow further to process the send email request +private fun setFirstName(name: String) { _uiState.value = uiState.value.copy( firstName = InputWrapper(value = name) ) } Saves the first name entered on the userinformation screen +private fun setLastName(last: String) { _uiState.value = uiState.value.copy( lastName = InputWrapper(value = last) ) } This functions saves the Last name entered on the user information screen +private fun setBusinessRole(business: String) { _uiState.value = uiState.value.copy( selectedBusinessRole = business ) } This functions saves the business role entered on the user information screen +private fun setOtherBusinessRole(role: String) { _uiState.value = uiState.value.copy( selectedOtherBusinessRole = role ) } This function saves the other business role entered by the user +"fun handleRegistrationScreenEvent(registrationScreenEvent: RegistrationScreenEvent) { when(registrationScreenEvent) { is RegistrationScreenEvent.TouClicked -> { _uiState.value = uiState.value.copy( isTouChecked = registrationScreenEvent.checked, displayTouError = false ) } is RegistrationScreenEvent.PrivacyStatementClicked -> { _uiState.value = uiState.value.copy( isPrivacyStatementChecked = registrationScreenEvent.checked, displayPrivacyStatementError = false ) } is RegistrationScreenEvent.NextClicked -> { navigateToNextScreen(registrationScreenEvent.registrationScreenType) } is RegistrationScreenEvent.SignInClicked -> {  } is RegistrationScreenEvent.ShowError -> { val pError = uiState.value.privacyStatementVisible && !uiState.value.isPrivacyStatementChecked val tError = uiState.value.touVisible && !uiState.value.isTouChecked _uiState.value = uiState.value.copy( displayPrivacyStatementError = pError, displayTouError = tError ) } is RegistrationScreenEvent.CompanyNameUpdated -> { setCompanyName(registrationScreenEvent.name) } is RegistrationScreenEvent.AddressFieldsUpdated -> { setAddress( address1 = registrationScreenEvent.address1, address2 = registrationScreenEvent.address2, address3 = registrationScreenEvent.address3, city = registrationScreenEvent.city, zipcode = registrationScreenEvent.zipCode ) } is RegistrationScreenEvent.CountrySelected -> { updateCountryList(registrationScreenEvent.index) } is RegistrationScreenEvent.StateSelected -> { saveSelectedState(registrationScreenEvent.index) } is RegistrationScreenEvent.RecommendationSelected -> { _uiState.value = uiState.value.copy( isRecommendedSelected = registrationScreenEvent.isSelected ) } is RegistrationScreenEvent.RecommendationConfirmed -> { _uiState.value = uiState.value.copy( recommendedScreenSeen = true ) navigateToNextScreen(RegistrationScreenType.CompanyInformationScreen()) } is RegistrationScreenEvent.EmailChanged -> { setEmail(registrationScreenEvent.emailAddress) } is RegistrationScreenEvent.PasswordChanged -> { setPassword(registrationScreenEvent.password) } is RegistrationScreenEvent.ConfirmPasswordChanged -> { setConfirmPassword(registrationScreenEvent.confirmPassword) } is RegistrationScreenEvent.UserEmailAsUsername -> { useEmailAsUserName(registrationScreenEvent.checked) } is RegistrationScreenEvent.UserNameChanged -> { userNameChanged(registrationScreenEvent.userName) } is RegistrationScreenEvent.SelectedMatchedResult -> { matchResultSelected(registrationScreenEvent.result) } is RegistrationScreenEvent.ContinueNewAccountClicked -> { navigateToNextScreen(RegistrationScreenType.UserInformationScreen()) } is RegistrationScreenEvent.UserNameUpdated -> { yourNameUpdated(registrationScreenEvent.name) } is RegistrationScreenEvent.UserPhoneUpdated -> { userPhoneUpdated(registrationScreenEvent.number) } is RegistrationScreenEvent.SendEmailClicked -> { sendEmailClicked() } is RegistrationScreenEvent.UserMessageUpdated -> { userMessageUpdated(registrationScreenEvent.message) } is RegistrationScreenEvent.DifferentAccount -> { viewModelScope.launch(Dispatchers.Main) { navigationEvent.emit(RegistrationNavigationEvent.OpenAccountReviewScreen) } } is RegistrationScreenEvent.ContinueNewAccount -> { viewModelScope.launch(Dispatchers.Main) { navigationEvent.emit(RegistrationNavigationEvent.OpenAccountInformationScreen) } } is RegistrationScreenEvent.FirstNameUpdated -> { setFirstName(registrationScreenEvent.firstName) } is RegistrationScreenEvent.LastNameUpdated -> { setLastName(registrationScreenEvent.lastName) } is RegistrationScreenEvent.BusinessRoleUpdated -> { setBusinessRole(registrationScreenEvent.businessRole) } is RegistrationScreenEvent.OtherBusinessRoleUpdated -> { setOtherBusinessRole(registrationScreenEvent.otherBusinessRole) } } }" @param registrationScreenEvent - [RegistrationScreenEvent] is a class which holds multiple Events types from UI to ViewModel This method helps in communicating the UI events from Registration Screen and ViewModel. Any future Event that is added needs to be added in the as well. +"private fun navigateToNextScreen(screenType: RegistrationScreenType) { when(screenType) { is RegistrationScreenType.CompanyInformationScreen -> { viewModelScope.launch(Dispatchers.Main) { navigationEvent.emit(RegistrationNavigationEvent.OpenCompanyInformationScreen) } _uiState.value = uiState.value.copy( dotPagerList = listOf( Dot(completed = true),Dot(),Dot(),Dot()),isLoading = true)getCountryData() getCountryStateData() } is RegistrationScreenType.AgreementsScreen -> {  } is RegistrationScreenType.AccountInformationScreen -> { _uiState.value = uiState.value.copy( signInProcessing = true ) //Starting DQM string checking API call, if error t val parameters = JsonObject() parameters.addProperty(""name"",uiState.value.companyName.value) dqmStringCheckerForCompanyName(parameters) getAddressFieldErrorsOrNull() } is RegistrationScreenType.RecommendationScreen -> { viewModelScope.launch(Dispatchers.Main) { navigationEvent.emit(RegistrationNavigationEvent.OpenRecommendationScreen) } } is RegistrationScreenType.AccountReviewScreen -> { _uiState.value = uiState.value.copy( signInProcessing = true, dotPagerList = listOf( Dot(completed = true), Dot(completed = true), Dot(completed = true), Dot() ) ) when(val validationResult = validateAccountInformationScreen()) { null -> { goToUniqueUserNameCheck() } else -> { displayAccountInformationErrors(validationResult) } } } is RegistrationScreenType.UserInformationScreen -> { viewModelScope.launch(Dispatchers.Main) { _uiState.value = uiState.value.copy( signInProcessing = true ) navigationEvent.emit(RegistrationNavigationEvent.OpenUserInformationScreen) getBusinessRoles() } } is RegistrationScreenType.SignUpEmailConfirmationScreen -> { when(val validationResult = validateUserInformationScreen()) { null -> { _uiState.value = uiState.value.copy( signInProcessing = true ) dqmStringCheckForFirstName() } else  > { displayUserInformationErrors(validationResult) } } } } }" This method navigates the registration flow to the next appropriate screen for the registration +"private fun getCountryData() {viewModelScope.launch(Dispatchers.IO) {inputStreamForCountriesJSONObject = CountriesRegistrationFormat.instance.getCountriesRegistrationFormat() selectedCountriesJSONObject = inputStreamForCountriesJSONObject!!.optJSONArray(LocaleUtils.instance.localeCountry) for (i in 0 until selectedCountriesJSONObject!!.length()) { val selectedCountryAttributes = selectedCountriesJSONObject!!.optJSONObject(i) val keyAttribute = selectedCountryAttributes!!.optString(""name"") val keyAttributeRequired = selectedCountryAttributes.optBoolean(""required"") when (keyAttribute) { ""PROVINCE"" -> { } ""STATE"" -> { _uiState.value = uiState.value.copy( addressFields = _uiState.value.addressFields.copy( selectedState = _uiState.value.addressFields.selectedState.copy( isRequired = keyAttributeRequired ) ) ) } ""POSTAL_CODE"" -> { } ""ZIP_CODE"" -> { _uiState.value = uiState.value.copy( addressFields = uiState.value.addressFields.copy( zipcode = uiState.value.addressFields.zipcode.copy( isRequired = keyAttributeRequired ) ) ) } ""STREET1"" -> { _uiState.value = uiState.value.copy( addressFields = uiState.value.addressFields.copy( address1 = uiState.value.addressFields.address1.copy( isRequired = keyAttributeRequired ) ) ) } ""STREET2"" -> { _uiState.value = uiState.value.copy( addressFields = uiState.value.addressFields.copy( address2 = uiState.value.addressFields.address2.copy( isRequired = keyAttributeRequired ) ) ) } ""STREET3"" -> { _uiState.value = uiState.value.copy( addressFields = _uiState.value.addressFields.copy( address3 = _uiState.value.addressFields.address3.copy( isRequired = keyAttributeRequired ) ) ) } ""STREET4"" -> { } ""MUNICIPALITY"" -> { //Ying confirmed no Latin for Municipality in AN and API call } ""CITY"" -> { _uiState.value = uiState.value.copy( addressFields = _uiState.value.addressFields.copy( city = _uiState.value.addressFields.city.copy( isRequired = keyAttributeRequired ) ) ) } ""STATE_TEXT"" -> { } ""COUNTRY"" -> { _uiState.value = uiState.value.copy( addressFields = _uiState.value.addressFields.copy( selectedCountry = _uiState.value.addressFields.selectedCountry.copy( isRequired = keyAttributeRequired ) ) ) } } } } }" implementation for taking the fields required for the Company information Form +"private fun getCountryStateData() { viewModelScope.launch(Dispatchers.IO) { when(val result = getCountryDataUseCase.getCountryState( fullUrl = NetworkingService.instance.getOnboardingAPIURL(""onboarding/countries-states""), headers = NetworkingService.instance.anAccessTokenHeadersForSignUp )) { is RemoteResponse.Success -> { _uiState.value = uiState.value.copy( countryOptions = result.value.countries, isLoading = false ) } is RemoteResponse.Failure -> {  } } } }" This method gets the list of all the countries and states for all of the countries in the world +"private fun updateCountryList(countrySelected: Int) { _uiState.value = uiState.value.copy( addressFields = uiState.value.addressFields.copy( selectedCountry = uiState.value.addressFields.selectedCountry.copy( value = uiState.value.countryOptions[countrySelected].name ), selectedIso2Code = uiState.value.countryOptions[countrySelected].isoA2Code, selectedIso3Code = uiState.value.countryOptions[countrySelected].isoA3Code ), stateList = uiState.value.countryOptions[countrySelected].states?: listOf() ) if (uiState.value.countryOptions[countrySelected].isoA2Code.equals(""US"",ignoreCase = true)) { _uiState.value = uiState.value.copy( isZipCodeVerificationRequired = true ) } else { _uiState.value = uiState.value.copy( isZipCodeVerificationRequired = false ) } }" This method saves the selected country in the view-state and also updates the state list to be shown in the State dropdown menu +private fun saveSelectedState(stateSelected: Int) { _uiState.value = uiState.value.copy( addressFields = uiState.value.addressFields.copy( selectedState = uiState.value.addressFields.selectedState.copy( value = uiState.value.stateList[stateSelected].name ) ) ) _uiState.value = uiState.value.copy( selectedStateAbb = uiState.value.stateList[stateSelected].regionCode ) } This method saves the selected state in the View-state +"private fun dqmStringCheckForFirstName() { val parameters = JsonObject() parameters.addProperty(""userFirstName"", uiState.value.firstName.value) viewModelScope.launch(Dispatchers.IO) { when(val result = getCountryDataUseCase.checkDqmStringChecker( body = parameters )) { is RemoteResponse.Success -> { result.value.results.forEach { if (it.fieldName == ""CP_FIRSTNAME"" && it.severity == ""E"") { when (val value = validateUserInformationScreen(errorTypeForFirst = ErrorType.Error)) { null -> {  } else -> { displayUserInformationErrors(value) } } } else if (it.fieldName == ""CP_FIRSTNAME"" && it.severity == ""W"") { when (val value = validateUserInformationScreen(errorTypeForFirst = ErrorType.Warning)) { null -> {  } else -> { displayUserInformationErrors(value) } } } else if (it.fieldName == ""CP_FIRSTNAME"" && it.valid) { dqmStringCheckForLastName() } } } is RemoteResponse.Failure -> {  } } } }" This function runs the dqm checker API for the first name +"private fun dqmStringCheckForLastName() { val userParams = JsonObject() userParams.addProperty(""userLastName"", uiState.value.lastName.value) viewModelScope.launch(Dispatchers.IO) { when(val result = getCountryDataUseCase.checkDqmStringChecker( body = userParams )) { is RemoteResponse.Success -> { result.value.results.forEach { if(it.fieldName == ""CP_LASTNAME"" && it.severity == ""E"") { when(val value = validateUserInformationScreen(errorTypeForLast = ErrorType.Error)) { null -> { } else -> { displayUserInformationErrors(value) } } } else if(it.fieldName == ""CP_LASTNAME"" && it.severity == ""W"") { when(val value = validateUserInformationScreen(errorTypeForLast = ErrorType.Warning)) { null -> { } else -> { displayUserInformationErrors(value) } } } else if (it.fieldName == ""CP_LASTNAME"" && it.valid) { ReCaptchaService.validateWithEnterpriseReCaptchaService( null, ReCaptchaEventEnum.CREATE_ACCOUNT ) } } } is RemoteResponse.Failure -> { } } } }" This function runs the dqm checker API for the last name +"private fun dqmStringCheckerForCompanyName(parameters: JsonObject) { viewModelScope.launch(Dispatchers.IO) { when(val result = getCountryDataUseCase.checkDqmStringChecker( body = parameters )) { is RemoteResponse.Success -> { result.value.results.forEach { // Check if the company name has errors if (it.fieldName == ""ACCOUNT_NAME"" && it.severity == ""E"" && !it.valid) { when(val value = getCompanyNameErrorsOrNull(ErrorType.Error)) { // if there are no errors then proce null -> { } //if error are there display errors else -> displayCompanyInfoErrors(value) } } else if(it.fieldName == ""ACCOUNT_NAME"" && it.severity == ""W"") { when(val value = getCompanyNameErrorsOrNull(ErrorType.Warning)) { null -> { when(val addressValidation = getAddressFieldErrorsOrNull()) { null -> { } else -> { displayCompanyInfoErrors(addressValidation) } } } else -> displayCompanyInfoErrors(value) } } else { when (val addressValidation = getAddressFieldErrorsOrNull()) { null -> { if (uiState.value.isZipCodeVerificationRequired == true) { checkZipCode() } else { } } else -> { displayCompanyInfoErrors(addressValidation) } } } } } is RemoteResponse.Failure -> { } } } }" Post DQM string checker API call is made to check the error in the registration form +"private fun proceedToAccountCreationApiCall(): JSONObject { val userParams = JSONObject() val createParams = JSONObject() val supplierParams = JSONObject() val addressParams = JSONObject() val touArr = JSONArray() userParams.putOpt(""userId"", uiState.value.userName.value) userParams.putOpt(""password"", uiState.value.password.value) userParams.putOpt(""firstName"",uiState.value.firstName.value) userParams.putOpt(""lastName"",uiState.value.lastName.value) userParams.putOpt(""language"",Resources.getSystem().configuration.locale.language) userParams.putOpt(""email"",uiState.value.email.value) userParams.putOpt(""businessRole"", uiState.value.selectedBusinessRole) if (uiState.value.selectedBusinessRole == ""OTHER"") { userParams.putOpt(""businessRoleOtherValue"", uiState.value.selectedOtherBusinessRole) } createParams.putOpt(""user"", userParams) addressParams.putOpt(""street1"", uiState.value.addressFields.address1.value?:"""") addressParams.putOpt(""street2"", uiState.value.addressFields.address2.value?:"""") addressParams.putOpt(""street3"", uiState.value.addressFields.address3.value?:"""") addressParams.putOpt(""city"", uiState.value.addressFields.city.value?:"""") addressParams.putOpt(""state"", uiState.value.addressFields.address1.value?:"""") addressParams.putOpt(""isoStateCode"", uiState.value.selectedStateAbb?:"""") addressParams.putOpt(""postalCode"", uiState.value.addressFields.zipcode.value?:"""") addressParams.putOpt(""isoCountryCode"",uiState.value.addressFields.selectedIso2Code?:"""") supplierParams.putOpt(""name"", uiState.value.companyName.value) supplierParams.putOpt(""accountType"", ""LIGHT"") supplierParams.putOpt(""routingEmail"", uiState.value.email.value) supplierParams.putOpt(""address"", addressParams) createParams.putOpt(""supplier"", supplierParams) createParams.putOpt(""source"", ""MOBILE"") touArr.put(""TOU_UNIFIED"") touArr.put(""SYSTEM_PRIVACY_STATEMENT"") createParams.putOpt(""documentTypes"", touArr) return createParams } private fun proceedToContactAdminEmailConfirmationScreen() { viewModelScope.launch(Dispatchers.IO) { navigationEvent.emit(RegistrationNavigationEvent.OpenContactAdminEmailConfirmationScreen) } }" This function creates the param required for account creation and makes the api call for the account creation. Based on the response received from the API call it navigates the UI flow further. +"private suspend fun goToDuplicateCheck(isContactAdmin: Boolean = false) { val userParams = JsonObject() userParams.addProperty(""companyName"", uiState.value.companyName.value) userParams.addProperty(""city"", uiState.value.addressFields.city.value) userParams.addProperty(""email"", uiState.value.email.value) userParams.addProperty(""username"", uiState.value.userName.value) userParams.addProperty(""country"", uiState.value.addressFields.selectedIso3Code) when (val dupResult = getAccountInformationUseCase.getDuplicateResult( url = NetworkingService.instance.getOnboardingAPIURL(""onboarding/dupcheck""), headers = if (isContactAdmin) { NetworkingService.instance.anAccessTokenHeadersForGoogleRecaptchaForContactAdmin } else { NetworkingService.instance.anAccessTokenHeadersForGoogleRecaptcha }, body = userParams )) { is RemoteResponse.Success -> { if (dupResult.value.matchResults.isEmpty()) { _uiState.value = uiState.value.copy( signInProcessing = false ) //TODO go to next step in sign up } else { _uiState.value = uiState.value.copy( signInProcessing = false, matchedResult = dupResult.value.matchResults ) navigationEvent.emit(RegistrationNavigationEvent.OpenAccountReviewScreen) } } is RemoteResponse.Failure -> { } } }" Function to make the api call for the Duplicate check of the account and provide the recommendation +"private fun getCompanyNameErrorsOrNull(errorType: ErrorType): InputErrors? { val companyNameError = InputValidator.getDqmErrorIdOrNull(errorType) return if (companyNameError == null) { null } else { InputErrors(companyNameError,null, null,null,null,null,null,null,null) } }" Util function for checking if the company name field has any error or not +"private fun getAddressFieldErrorsOrNull(): InputErrors? { val address1 = InputValidator.checkIfFieldRequired(uiState.value.addressFields.address1.value?:"""", uiState.value.addressFields.address1.isRequired) val address2 = InputValidator.checkIfFieldRequired(uiState.value.addressFields.address2.value?:"""", uiState.value.addressFields.address2.isRequired) val address3 = InputValidator.checkIfFieldRequired(uiState.value.addressFields.address3.value?:"""", uiState.value.addressFields.address3.isRequired) val city = InputValidator.checkIfFieldRequired(uiState.value.addressFields.city.value?:"""", uiState.value.addressFields.city.isRequired) val state = InputValidator.checkIfFieldRequired(uiState.value.addressFields.selectedState.value?:"""", uiState.value.addressFields.selectedState.isRequired) val zipCode = InputValidator.checkIfFieldRequired(uiState.value.addressFields.zipcode.value?:"""", uiState.value.addressFields.zipcode.isRequired) val country = InputValidator.checkIfFieldRequired(uiState.value.addressFields.selectedCountry.value?:"""", uiState.value.addressFields.selectedCountry.isRequired) return if (address1 == null && address2 == null && address3 == null && city == null && state == null && zipCode == null && country == null) { null } else { InputErrors( companyNameErrorId = null, companyNameWarningId = null, address1 = address1, address2 = address2, address3 = address3, city = city, state = state, zipCode = zipCode, country = country ) } }" Util function is for Address fields in Compnay Information Screen This functions check for validation requirement for all the fields and returns error if any of them does not match any requirement for validation +"private fun getPasswordFieldErrors(): PasswordInputErrors? { val validLength = InputValidator.validPasswordLength(uiState.value.password.value?:"""") val validLowerUpper = InputValidator.validUpperAndLowerCase(uiState.value.password.value?:"""") val validNumber = InputValidator.containsNumber(uiState.value.password.value?:"""") val validSpecial = InputValidator.containSpecialCharacter(uiState.value.password.value?:"""") return if (!validLength && !validLowerUpper && !validNumber && !validSpecial ) { null } else { PasswordInputErrors( validLength = validLength, validLowerUpper = validLowerUpper, validNumber = validNumber, validSpecial = validSpecial ) } }" Util function for Password field in the AccountInformation Screen This functions check for validation requirement for the password and returns error if password does not match any requirement +"private fun validateAccountInformationScreen(): AccountInformationErrors? { val emailValid = InputValidator.checkIfFieldRequired(uiState.value.email.value?:"""", true) val userNameValid = InputValidator.checkIfFieldRequired(uiState.value.userName.value?:"""", true) val passwordValid = InputValidator.checkIfFieldRequired(uiState.value.password.value?:"""", true) val confirmPasswordValid = InputValidator.checkIfFieldRequired(uiState.value.confirmPassword.value?:"""", true) return if (emailValid == null && userNameValid == null && passwordValid == null && confirmPasswordValid == null) { null } else { AccountInformationErrors( emailNameErrorId = emailValid, userNameErrorId = userNameValid, passwordErrorId = passwordValid, verifyPasswordErrorId = confirmPasswordValid ) } }" "This function validates the information on the Account Information screen. If input validation fails for any of the fields, this functions assigns the error strings to be shown by the UI" +"private fun validateUserInformationScreen( errorTypeForFirst: ErrorType? = null, errorTypeForLast: ErrorType? = null ): UserInformationErrors? { val firstNameValid = if (errorTypeForFirst == null) { InputValidator.checkIfFieldRequired(uiState.value.firstName.value ?: """", true) } else { InputValidator.getDqmErrorIdOrNull(errorTypeForFirst) } val lastNameValid = if (errorTypeForLast == null) { InputValidator.checkIfFieldRequired(uiState.value.lastName.value ?: """", true) } else { InputValidator.getDqmErrorIdOrNull(errorTypeForLast) } return if (firstNameValid == null && lastNameValid == null) { null } else { UserInformationErrors( firstNameErrorId = firstNameValid, lastNameErrorId = lastNameValid ) } }" "This function validates the information on the UserInformationScreen. If input validates fails for any of the fields, this functions assigns the error strings to be shown by the UI" +"private fun checkZipCode() { val parameters = HashMap() parameters[""zipCode""] = uiState.value.addressFields.zipcode.value!! parameters[""isoCountryCode""] = ""US"" viewModelScope.launch(Dispatchers.IO) { when(val result = getCountryDataUseCase.verifyZipCodeForUS( fullUrl = NetworkingService.instance.getOnboardingAPIURL(""onboarding/states/"") + (uiState.value.selectedStateAbb?.split(""-"".toRegex())?.toTypedArray() ?.get(1) ?: """"), queryMap = parameters )) { is RemoteResponse.Success -> { if (result.value.abbreviation.isNullOrEmpty()) { val zipCode = InputValidator.validZipCode(true) displayCompanyInfoErrors( InputErrors( companyNameErrorId = null, companyNameWarningId = null, address1 = null, address2 = null, address3 = null, city = null, state = null, zipCode = zipCode, country = null ) ) } else { // [displayInputErrors] is not required as there are no errors, but still implemented to keep the code in proper structure val zipCode = InputValidator.validZipCode(false) displayCompanyInfoErrors( InputErrors( companyNameErrorId = null, companyNameWarningId = null, address1 = null, address2 = null, address3 = null, city = null, state = null, zipCode = zipCode, country = null ), signInProcessing = true ) if (uiState.value.recommendedScreenSeen) { _uiState.value = uiState.value.copy( dotPagerList = listOf( Dot(completed = true), Dot(completed = true), Dot(), Dot() ), signInProcessing = false ) viewModelScope.launch(Dispatchers.Main) { navigationEvent.emit(RegistrationNavigationEvent.OpenAccountInformationScreen) } } else { getTokenForRecommendationApi() } } } is RemoteResponse.Failure -> { } } } }" "This Api call method which validates the Zipcode enters by the user, this only runs if the input country is US" +"private fun getTokenForRecommendationApi() { viewModelScope.launch(Dispatchers.IO) { val tokenHeaders = HashMap() tokenHeaders[""Authorization""] = ""Basic "" + SecurityService.instance.getString(SecurityService.Keys.saphcpToken) when(val result = getCountryDataUseCase.addressCleanser( fullUrl = NetworkingService.getAddressCorrectionTokenURL(), headers = tokenHeaders )) { is RemoteResponse.Success -> { getRecommendationDetails(result.value) } is RemoteResponse.Failure -> { } } } }" Function to get the Recommendation token details for the address entered by the user +"private fun getRecommendationDetails(token: AddressCleanser) { val headers = HashMap() headers[""Authorization""] = ""Bearer "" + token.accessToken val parameters = JsonObject() parameters.add(""outputFields"", addressCleanseOutputFields()) parameters.add(""addressInput"", addressCleanseInputFields()) viewModelScope.launch(Dispatchers.IO) { when(val result = getCountryDataUseCase.getRecommendationDetails( headers = headers, body = parameters )) { is RemoteResponse.Success -> { if (result.value.stdAddrAddressDelivery.isEmpty() || result.value.stdAddrLocalityFull.isEmpty() || result.value.stdAddrRegionCode.isEmpty() ) { _uiState.value = uiState.value.copy( dotPagerList = listOf( Dot(completed = true), Dot(completed = true), Dot(), Dot() ), signInProcessing = false ) viewModelScope.launch(Dispatchers.Main) { navigationEvent.emit(RegistrationNavigationEvent.OpenAccountInformationScreen) } } else { _uiState.value = uiState.value.copy( recommendedAddress = RegistrationAddressFields( address1 = InputWrapper(value = result.value.stdAddrAddressDelivery), city = InputWrapper(value = result.value.stdAddrLocalityFull), zipcode = InputWrapper( value = result.value.stdAddrPostcodeFull.split( ""-"".toRegex() ).map { it.trim() }[0] ), selectedState = InputWrapper(value = result.value.stdAddrRegionFull), selectedCountry = InputWrapper(value = result.value.stdAddrCountry2char) ), signInProcessing = false ) navigateToNextScreen(RegistrationScreenType.RecommendationScreen()) } } is RemoteResponse.Failure -> { } } } }" Function to get the Recommendation details for the address entered by the user +"private suspend fun getBusinessRoles() { when(val roles = getBusinessRoleUseCase.getBusinessRole( fullUrl = NetworkingService.instance.getOnboardingAPIURL(""onboarding/business-roles""), headers = NetworkingService.instance.anAccessTokenHeadersForSignUp as HashMap /* = java.util.HashMap */, )) { is RemoteResponse.Success -> { _uiState.value = uiState.value.copy( signInProcessing = false, businessRole = roles.value.results ) } is RemoteResponse.Failure -> { } } } private fun createAccount() { NetworkingService.instance.anNewStackAPIsGoogleRecaptchaPost( ""onboarding/accounts"", proceedToAccountCreationApiCall(), isContactAdmin = false, object : JSONObjectRequestListener { override fun onResponse(response: JSONObject) { _uiState.value = uiState.value.copy( signInProcessing = false ) viewModelScope.launch(Dispatchers.Main) { navigationEvent.emit(RegistrationNavigationEvent.OpenSignUpConfirmationScreen) } } override fun onError(ANError: ANError) { } }, false, false, ) }" This functions gets the business role list fro the API call +"private fun displayCompanyInfoErrors(inputErrors: InputErrors, signInProcessing: Boolean = false) { _uiState.value = uiState.value.copy( companyName = uiState.value.companyName.copy( errorId = inputErrors.companyNameErrorId ), addressFields = uiState.value.addressFields.copy( address1 = uiState.value.addressFields.address1.copy( errorId = inputErrors.address1 ), address2 = uiState.value.addressFields.address2.copy( errorId = inputErrors.address2 ), address3 = uiState.value.addressFields.address3.copy( errorId = inputErrors.address3 ), city = uiState.value.addressFields.city.copy( errorId = inputErrors.city ), zipcode = uiState.value.addressFields.zipcode.copy( errorId = inputErrors.zipCode ), selectedState = uiState.value.addressFields.selectedState.copy( errorId = inputErrors.state ), selectedCountry = uiState.value.addressFields.selectedCountry.copy( errorId = inputErrors.country ) ), signInProcessing = signInProcessing ) }" Displaying errors on the fields in the CompanyInfo screen +"private fun displayAccountInformationErrors(inputErrors: AccountInformationErrors) { _uiState.value = uiState.value.copy( email = uiState.value.email.copy( errorId = inputErrors.emailNameErrorId ), userName = uiState.value.userName.copy( errorId = inputErrors.userNameErrorId ), password = uiState.value.password.copy( errorId = inputErrors.passwordErrorId ), confirmPassword = uiState.value.confirmPassword.copy( errorId = inputErrors.verifyPasswordErrorId ), signInProcessing = false ) }" This function display the errors on the AccountInformationScreen +"private fun displayUserInformationErrors(inputErrors: UserInformationErrors) { _uiState.value = uiState.value.copy( firstName = uiState.value.firstName.copy( errorId = inputErrors.firstNameErrorId ), lastName = uiState.value.lastName.copy( errorId = inputErrors.lastNameErrorId ), signInProcessing = false ) }" This function displays the error on the User Information Screen +"object UnsplashSizingInterceptor : Interceptor { override suspend fun intercept(chain: Interceptor.Chain): ImageResult { val data = chain.request.data val widthPx = chain.size.width.pxOrElse { -1 } val heightPx = chain.size.height.pxOrElse { -1 } if (widthPx > 0 && heightPx > 0 && data is String && data.startsWith(""https://images.unsplash.com/photo-"") ) { val url = data.toHttpUrl() .newBuilder() .addQueryParameter(""w"", widthPx.toString()) .addQueryParameter(""h"", heightPx.toString()) .build() val request = chain.request.newBuilder().data(url).build() return chain.proceed(request) } return chain.proceed(chain.request) } }" A Coil [Interceptor] which appends query params to Unsplash urls to request sized images. +fun YearMonth.getNumberWeeks(weekFields: WeekFields = CALENDAR_STARTS_ON): Int { val firstWeekNumber = this.atDay(1)[weekFields.weekOfMonth()] val lastWeekNumber = this.atEndOfMonth()[weekFields.weekOfMonth()] return lastWeekNumber - firstWeekNumber + 1 // Both weeks inclusive } This function get the number of weeks in the month +"public fun produceRequestedResources( resourceResults: R, requestParams: RequestBuilders.ResourcesRequest, ): Resources" Produce resources for the given request. The implementation should read [androidx.wear.tiles.RequestBuilders.ResourcesRequest.getResourceIds] and if not empty only return the requested resources. +"public class ThemePreviewTileRenderer(context: Context, private val thisTheme: Colors) : SingleTileLayoutRenderer(context) { override fun createTheme(): Colors = thisTheme override fun renderTile( state: Unit, deviceParameters: DeviceParameters ): LayoutElement { return Box.Builder() .setWidth(ExpandedDimensionProp.Builder().build()) .setHeight(ExpandedDimensionProp.Builder().build()) .setHorizontalAlignment(HORIZONTAL_ALIGN_CENTER) .setVerticalAlignment(VERTICAL_ALIGN_CENTER) .addContent( Column.Builder() .addContent(title()) .addContent(primaryIconButton()) .addContent(primaryChip(deviceParameters)) .addContent(secondaryCompactChip(deviceParameters)) .addContent(secondaryIconButton()) .build() ) .build() } internal fun title() = Text.Builder(context, ""Title"") .setTypography(Typography.TYPOGRAPHY_CAPTION1) .setColor(ColorBuilders.argb(theme.onSurface)) .build() internal fun primaryChip( deviceParameters: DeviceParameters ) = Chip.Builder(context, NoOpClickable, deviceParameters) .setPrimaryLabelContent(""Primary Chip"") .setIconContent(Icon) .setChipColors(ChipColors.primaryChipColors(theme)) .build() internal fun secondaryCompactChip( deviceParameters: DeviceParameters ) = CompactChip.Builder(context, ""Secondary Chip"", NoOpClickable, deviceParameters) .setChipColors(ChipColors.secondaryChipColors(theme)) .build() internal fun primaryIconButton() = Button.Builder(context, NoOpClickable) .setIconContent(Icon) .setButtonColors(ButtonColors.primaryButtonColors(theme)) .build() internal fun secondaryIconButton() = Button.Builder(context, NoOpClickable) .setIconContent(Icon) .setButtonColors(ButtonColors.secondaryButtonColors(theme)) .build() override fun ResourceBuilders.Resources.Builder.produceRequestedResources( resourceResults: Unit, deviceParameters: DeviceParameters, resourceIds: MutableList ) { addIdToImageMapping(Icon, drawableResToImageResource(R.drawable.ic_nordic)) } private companion object { private const val Icon = ""icon"" } }" Tile that renders components with typical layouts and a theme colour. +public fun drawableResToImageResource(@DrawableRes id: Int): ImageResource = ImageResource.Builder() .setAndroidResourceByResId( AndroidImageResourceByResId.Builder() .setResourceId(id) .build() ) .build() Load a resource from the res/drawable* directories. +"public suspend fun ImageLoader.loadImage( context: Context, data: Any?, configurer: ImageRequest.Builder.() -> Unit = {} ): Bitmap? { val request = ImageRequest.Builder(context) .data(data) .apply(configurer) .allowRgb565(true) .allowHardware(false) .build() val response = execute(request) return (response.drawable as? BitmapDrawable)?.bitmap }" Load a Bitmap from a CoilImage loader. +"public suspend fun ImageLoader.loadImageResource( context: Context, data: Any?, configurer: ImageRequest.Builder.() -> Unit = {} ): ImageResource? = loadImage(context, data, configurer)?.toImageResource()" Load an ImageResource from a CoilImage loader. +"public fun Bitmap.toImageResource(): ImageResource { val rgb565Bitmap = if (config == Bitmap.Config.RGB_565) { this } else { copy(Bitmap.Config.RGB_565, false) } val byteBuffer = ByteBuffer.allocate(rgb565Bitmap.byteCount) rgb565Bitmap.copyPixelsToBuffer(byteBuffer) val bytes: ByteArray = byteBuffer.array() return ImageResource.Builder().setInlineResource( ResourceBuilders.InlineImageResource.Builder() .setData(bytes) .setWidthPx(rgb565Bitmap.width) .setHeightPx(rgb565Bitmap.height) .setFormat(ResourceBuilders.IMAGE_FORMAT_RGB_565) .build() ) .build() }" Convert a bitmap to a ImageResource. +"public val NoOpClickable: ModifiersBuilders.Clickable = ModifiersBuilders.Clickable.Builder() .setId(""noop"") .build()" Simple NoOp clickable for preview use. +"public abstract class DataComplicationService> : SuspendingComplicationDataSourceService() { public abstract val renderer: R public abstract suspend fun data(request: ComplicationRequest): D public abstract fun previewData(type: ComplicationType): D override suspend fun onComplicationRequest(request: ComplicationRequest): ComplicationData { val data: D = data(request) return render(request.complicationType, data) } override fun getPreviewData(type: ComplicationType): ComplicationData? { val data: D = previewData(type) return render(type, data) } public fun render(type: ComplicationType, data: D): ComplicationData { return renderer.render(type, data) } }" "A complication service based on a [ComplicationTemplate]. The implementation is effectively two parts, first creating some simple data model using a suspending [data] function. Then a render phase." +"public fun drawToBitmap( bitmap: Bitmap, density: Density, size: Size, onDraw: DrawScope.() -> Unit ) { val androidCanvas = AndroidCanvas(bitmap) val composeCanvas = ComposeCanvas(androidCanvas) val canvasDrawScope = CanvasDrawScope() canvasDrawScope.draw(density, LayoutDirection.Ltr, composeCanvas, size) { onDraw() } }" Render an element normally drawn within a Compose Canvas into a Bitmap. This allows shared elements between the app and tiles. +Render an element normally drawn within a Compose Canvas into a Bitmap and then convert to a Tiles ImageResource. "@RequiresApi(VERSION_CODES.O) public fun canvasToImageResource( size: Size, density: Density, onDraw: DrawScope.() -> Unit ): ImageResource { return Bitmap.createBitmap( size.width.toInt(), size.height.toInt(), Bitmap.Config.RGB_565, false ).apply { drawToBitmap(bitmap = this, density = density, size = size, onDraw = onDraw) }.toImageResource() }" +public interface NetworkingRules { public fun isHighBandwidthRequest(requestType: RequestType): Boolean} Implementation of app rules for network usage. A way to implement logic such as +"public fun checkValidRequest( requestType: RequestType, currentNetworkType: NetworkType ): RequestCheck" Checks whether this request is allowed on the current network type. +Returns the preferred network for a request. Null means no suitable network. "public fun getPreferredNetwork( networks: Networks, requestType: RequestType ): NetworkStatus?" +"public object Lenient : NetworkingRules { override fun isHighBandwidthRequest(requestType: RequestType): Boolean { return requestType is RequestType.MediaRequest } override fun checkValidRequest( requestType: RequestType, currentNetworkType: NetworkType ): RequestCheck { return Allow } override fun getPreferredNetwork( networks: Networks, requestType: RequestType ): NetworkStatus? { return networks.networks.firstOrNull { it.type is NetworkType.Wifi } } }" +"public object Conservative : NetworkingRules { override fun isHighBandwidthRequest(requestType: RequestType): Boolean { return requestType is RequestType.MediaRequest } override fun checkValidRequest( requestType: RequestType, currentNetworkType: NetworkType ): RequestCheck { if (requestType is RequestType.MediaRequest) { return if (requestType.type == RequestType.MediaRequest.MediaRequestType.Download) { if (currentNetworkType is NetworkType.Wifi || currentNetworkType is NetworkType.Cellular) { Allow } else { Fail(""downloads only possible over Wifi/LTE"") } } else { Fail(""streaming disabled"") } } return Allow } override fun getPreferredNetwork( networks: Networks, requestType: RequestType ): NetworkStatus? { val cell = networks.networks.firstOrNull { it.type is NetworkType.Cellular } val ble = networks.networks.firstOrNull { it.type is NetworkType.Bluetooth } return networks.networks.firstOrNull { it.type is NetworkType.Wifi } ?: if (requestType is RequestType.MediaRequest) { cell } else { ble } } } }" "Conservative rules don't allow Streaming, and only allow Downloads over high bandwidth networks." +"public class NetworkingRulesEngine( internal val networkRepository: NetworkRepository, internal val logger: NetworkStatusLogger = NetworkStatusLogger.Logging, private val networkingRules: NetworkingRules = NetworkingRules.Conservative ) { public fun preferredNetwork(requestType: RequestType): NetworkStatus? { val networks = networkRepository.networkStatus.value return networkingRules.getPreferredNetwork(networks, requestType) } public fun checkValidRequest( requestType: RequestType, currentNetworkType: NetworkType? ): RequestCheck { return networkingRules.checkValidRequest(requestType, currentNetworkType ?: NetworkType.Unknown(""unknown"")) } public fun isHighBandwidthRequest(requestType: RequestType): Boolean { return networkingRules.isHighBandwidthRequest(requestType) } @Suppress(""UNUSED_PARAMETER"") public fun reportConnectionFailure(inetSocketAddress: InetSocketAddress, networkType: NetworkType?) { // TODO check for no internet on BLE and other scenarios } }" "Networking Rules that bridges between app specific rules and specific network actions, like opening a network socket." +"@ExperimentalHorologistMediaUiApi @Composable public fun ShowPlaylistChip( artworkUri: Any?, name: String?, onClick: () -> Unit, modifier: Modifier = Modifier, placeholder: Painter? = null, ) { val appIcon: (@Composable BoxScope.() -> Unit)? = artworkUri?.let { { MediaArtwork( modifier = Modifier.size(ChipDefaults.LargeIconSize), contentDescription = name, artworkUri = artworkUri, placeholder = placeholder, ) } } Chip( modifier = modifier.fillMaxWidth(), colors = ChipDefaults.secondaryChipColors(), icon = appIcon, label = { Text( text = name.orEmpty(), overflow = TextOverflow.Ellipsis ) }, onClick = onClick ) }" [Chip] to show all items in the selected category. +"class ServiceWorkerSupportFeature( private val homeActivity: HomeActivity, ) : ServiceWorkerDelegate, DefaultLifecycleObserver { override fun onDestroy(owner: LifecycleOwner) { homeActivity.components.core.engine.unregisterServiceWorkerDelegate() } override fun onCreate(owner: LifecycleOwner) { homeActivity.components.core.engine.registerServiceWorkerDelegate(this) } override fun addNewTab(engineSession: EngineSession): Boolean { with(homeActivity) { openToBrowser(BrowserDirection.FromHome) components.useCases.tabsUseCases.addTab( flags = LoadUrlFlags.external(), engineSession = engineSession, source = SessionState.Source.Internal.None, ) } return true } }" Fenix own version of the `ServiceWorkerSupportFeature` from Android-Components which adds the ability to navigate to the browser before opening a new tab. Will automatically register callbacks for service workers requests and cleanup when [homeActivity] is destroyed. +"enum class BrowserDirection(@IdRes val fragmentId: Int) { FromGlobal(0), FromHome(R.id.homeFragment), FromWallpaper(R.id.wallpaperSettingsFragment), FromSearchDialog(R.id.searchDialogFragment), FromSettings(R.id.settingsFragment), FromBookmarks(R.id.bookmarkFragment), FromBookmarkSearchDialog(R.id.bookmarkSearchDialogFragment), FromHistory(R.id.historyFragment), FromHistorySearchDialog(R.id.historySearchDialogFragment), FromHistoryMetadataGroup(R.id.historyMetadataGroupFragment), FromTrackingProtectionExceptions(R.id.trackingProtectionExceptionsFragment), FromAbout(R.id.aboutFragment), FromTrackingProtection(R.id.trackingProtectionFragment), FromHttpsOnlyMode(R.id.httpsOnlyFragment), FromCookieBanner(R.id.cookieBannerFragment), FromTrackingProtectionDialog(R.id.trackingProtectionPanelDialogFragment), FromSavedLoginsFragment(R.id.savedLoginsFragment), FromAddNewDeviceFragment(R.id.addNewDeviceFragment), FromAddSearchEngineFragment(R.id.addSearchEngineFragment), FromEditCustomSearchEngineFragment(R.id.editCustomSearchEngineFragment), FromAddonDetailsFragment(R.id.addonDetailsFragment), FromStudiesFragment(R.id.studiesFragment), FromAddonPermissionsDetailsFragment(R.id.addonPermissionsDetailFragment), FromLoginDetailFragment(R.id.loginDetailFragment), FromTabsTray(R.id.tabsTrayFragment), FromRecentlyClosed(R.id.recentlyClosedFragment), }" Used with [HomeActivity.openToBrowser] to indicate which fragment the browser is being opened from. +"class FenixLogSink(private val logsDebug: Boolean = true) : LogSink { private val androidLogSink = AndroidLogSink() override fun log( priority: Log.Priority, tag: String?, throwable: Throwable?, message: String?, ) { if (priority == Log.Priority.DEBUG && !logsDebug) { return } androidLogSink.log(priority, tag, throwable, message) } }" "Fenix [LogSink] implementation that writes to Android's log, depending on settings." +"enum class GlobalDirections(val navDirections: NavDirections, val destinationId: Int) { Home(NavGraphDirections.actionGlobalHome(), R.id.homeFragment), Bookmarks( NavGraphDirections.actionGlobalBookmarkFragment(BookmarkRoot.Root.id), R.id.bookmarkFragment, ), History( NavGraphDirections.actionGlobalHistoryFragment(), R.id.historyFragment, ), Settings( NavGraphDirections.actionGlobalSettingsFragment(), R.id.settingsFragment, ), Sync( NavGraphDirections.actionGlobalTurnOnSync(), R.id.turnOnSyncFragment, ), SearchEngine( NavGraphDirections.actionGlobalSearchEngineFragment(), R.id.searchEngineFragment, ), Accessibility( NavGraphDirections.actionGlobalAccessibilityFragment(), R.id.accessibilityFragment, ), DeleteData( NavGraphDirections.actionGlobalDeleteBrowsingDataFragment(), R.id.deleteBrowsingDataFragment, ), SettingsAddonManager( NavGraphDirections.actionGlobalAddonsManagementFragment(), R.id.addonsManagementFragment, ), SettingsLogins( NavGraphDirections.actionGlobalSavedLoginsAuthFragment(), R.id.saveLoginSettingFragment, ), SettingsTrackingProtection( NavGraphDirections.actionGlobalTrackingProtectionFragment(), R.id.trackingProtectionFragment, ), WallpaperSettings( NavGraphDirections.actionGlobalWallpaperSettingsFragment(), R.id.wallpaperSettingsFragment, ), }" Used with [HomeActivity] global navigation to indicate which fragment is being opened. +open class SecureFragment(@LayoutRes contentLayoutId: Int) : Fragment(contentLayoutId) { constructor() : this(0) { Fragment() } override fun onCreate(savedInstanceState: Bundle?) { this.secure() super.onCreate(savedInstanceState) } override fun onDestroy() { this.removeSecure() super.onDestroy() } } A [Fragment] implementation that can be used to secure screens displaying sensitive information by not allowing taking screenshots of their content. Fragments displaying such screens should extend [SecureFragment] instead of [Fragment] class. +class WifiConnectionMonitor(app: Application) { @VisibleForTesting internal val callbacks = mutableListOf<(Boolean) -> Unit>() @VisibleForTesting internal var connectivityManager = app.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager @VisibleForTesting internal var lastKnownStateWasAvailable: Boolean? = null @VisibleForTesting internal var isRegistered = false @Synchronized set @VisibleForTesting internal val frameworkListener = object : ConnectivityManager.NetworkCallback() { override fun onLost(network: Network) { notifyListeners(false) lastKnownStateWasAvailable = false } override fun onAvailable(network: Network) { notifyListeners(true) lastKnownStateWasAvailable = true } } internal fun notifyListeners(value: Boolean) { val items = ArrayList(callbacks) items.forEach { it(value) } } Attaches itself to the [Application] and listens for WIFI available/not available events. This allows the calling code to set simpler listeners. +"fun start() { // Framework code throws if a listener is registered twice without unregistering. if (isRegistered) return val request = NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) .build() // AFAICT, the framework does not send an event when a new NetworkCallback is registered // while the WIFI is not connected, so we push this manually. If the WIFI is on, it will send // a follow up event shortly val noCallbacksReceivedYet = lastKnownStateWasAvailable == null if (noCallbacksReceivedYet) { lastKnownStateWasAvailable = false notifyListeners(false) } connectivityManager.registerNetworkCallback(request, frameworkListener) isRegistered = true }" "Attaches the [WifiConnectionMonitor] to the application. After this has been called, callbacks added via [addOnWifiConnectedChangedListener] will be called until either the app exits, or [stop] is called." +fun stop() { // Framework code will throw if an unregistered listener attempts to unregister. if (!isRegistered) return connectivityManager.unregisterNetworkCallback(frameworkListener) isRegistered = false lastKnownStateWasAvailable = null callbacks.clear() } Detatches the [WifiConnectionMonitor] from the app. No callbacks added via [addOnWifiConnectedChangedListener] will be called after this has been called. +fun addOnWifiConnectedChangedListener(onWifiChanged: (Boolean) -> Unit) { val lastKnownState = lastKnownStateWasAvailable if (callbacks.add(onWifiChanged) && lastKnownState != null) { onWifiChanged(lastKnownState) } } Adds [onWifiChanged] to a list of listeners that will be called whenever WIFI connects or disconnects. +fun removeOnWifiConnectedChangedListener(onWifiChanged: (Boolean) -> Unit) { callbacks.remove(onWifiChanged) } } Removes [onWifiChanged] from the list of listeners to be called whenever WIFI connects or disconnects. +"enum class ImageFileState { Unavailable, Downloading, Downloaded, Error, }" Defines the download state of wallpaper asset. +fun lowercase(): String = this.name.lowercase() } Get a lowercase string representation of the [ImageType.name] for use in path segments. +"enum class ImageType { Portrait, Landscape, Thumbnail, ;" Defines various image asset types that can be downloaded for each wallpaper. +"fun nameIsDefault(name: String): Boolean = name.isEmpty() || name == defaultName || name.lowercase() == ""none"" }" "Check if a wallpaper name matches the default. Considers empty strings to be default since that likely means a wallpaper has never been set. The ""none"" case here is to deal with a legacy case where the default wallpaper used to be Wallpaper.NONE. See commit 7a44412, Wallpaper.NONE and Settings.currentWallpaper (legacy name) for context." +"@Suppress(""ComplexCondition"") fun getCurrentWallpaperFromSettings(settings: Settings): Wallpaper? { val name = settings.currentWallpaperName val textColor = settings.currentWallpaperTextColor val cardColorLight = settings.currentWallpaperCardColorLight val cardColorDark = settings.currentWallpaperCardColorDark return if (name.isNotEmpty() && textColor != 0L && cardColorLight != 0L && cardColorDark != 0L) { Wallpaper( name = name, textColor = textColor, cardColorLight = cardColorLight, cardColorDark = cardColorDark, collection = DefaultCollection, thumbnailFileState = ImageFileState.Downloaded, assetsFileState = ImageFileState.Downloaded, ) } else { null } }" Generate a wallpaper from metadata cached in Settings. +"fun getLocalPath(name: String, type: ImageType) = ""wallpapers/$name/${type.lowercase()}.png""" Defines the standard path at which a wallpaper resource is kept on disk. +"fun legacyGetLocalPath(orientation: String, theme: String, name: String): String = ""wallpapers/$orientation/$theme/$name.png""" Defines the standard path at which a wallpaper resource is kept on disk. +"const val classicFirefoxCollectionName = ""classic-firefox"" val ClassicFirefoxCollection = Collection( name = classicFirefoxCollectionName, heading = null, description = null, learnMoreUrl = null, availableLocales = null, startDate = null, endDate = null, ) val DefaultCollection = Collection( name = defaultName, heading = null, description = null, learnMoreUrl = null, availableLocales = null, startDate = null, endDate = null, ) val Default = Wallpaper( name = defaultName, collection = DefaultCollection, textColor = null, cardColorLight = null, cardColorDark = null, thumbnailFileState = ImageFileState.Downloaded, assetsFileState = ImageFileState.Downloaded, )" "Note: this collection could get out of sync with the version of it generated when fetching remote metadata. It is included mostly for convenience, but use with utmost care until we find a better way of handling the edge cases around this collection. It is generally safer to do comparison directly with the collection name" +"data class Collection( val name: String, val heading: String?, val description: String?, val learnMoreUrl: String?, val availableLocales: List?, val startDate: Date?, val endDate: Date?, )  companion object { const val amethystName = ""amethyst"" const val ceruleanName = ""cerulean"" const val sunriseName = ""sunrise"" const val twilightHillsName = ""twilight-hills"" const val beachVibeName = ""beach-vibe"" const val firefoxCollectionName = ""firefox"" const val defaultName = ""default""" "Type that represents a collection that a [Wallpaper] belongs to. @property name The name of the collection the wallpaper belongs to. @property learnMoreUrl The URL that can be visited to learn more about a collection, if any. @property availableLocales The locales that this wallpaper is restricted to. If null, the wallpaper is not restricted. @property startDate The date the wallpaper becomes available in a promotion. If null, it is available from any date. @property endDate The date the wallpaper stops being available in a promotion. If null, the wallpaper will be available to any date." +"data class Wallpaper( val name: String, val collection: Collection, val textColor: Long?, val cardColorLight: Long?, val cardColorDark: Long?, val thumbnailFileState: ImageFileState, val assetsFileState: ImageFileState, ) {" Type that represents wallpapers. @property name The name of the wallpaper. @property collection The name of the collection the wallpaper belongs to. is not restricted. @property textColor The 8 digit hex code color that should be used for text overlaying the wallpaper. @property cardColorLight The 8 digit hex code color that should be used for cards overlaying the wallpaper when the user's theme is set to Light. @property cardColorDark The 8 digit hex code color that should be used for cards overlaying the wallpaper when the user's theme is set to Dark. +"suspend fun downloadThumbnail(wallpaper: Wallpaper): Wallpaper.ImageFileState = withContext(dispatcher) { downloadAsset(wallpaper, Wallpaper.ImageType.Thumbnail)" Downloads a thumbnail for a wallpaper from the network. This is expected to be found remotely at: ///thumbnail.png and stored locally at: wallpapers//thumbnail.png +"suspend fun downloadWallpaper(wallpaper: Wallpaper): Wallpaper.ImageFileState = withContext(dispatcher) { val portraitResult = downloadAsset(wallpaper, Wallpaper.ImageType.Portrait) val landscapeResult = downloadAsset(wallpaper, Wallpaper.ImageType.Landscape) return@withContext if (portraitResult == Wallpaper.ImageFileState.Downloaded && landscapeResult == Wallpaper.ImageFileState.Downloaded ) { Wallpaper.ImageFileState.Downloaded } else { Wallpaper.ImageFileState.Error } }" Downloads a wallpaper from the network. Will try to fetch 2 versions of each wallpaper: portrait and landscape. These are expected to be found at a remote path in the form: ///.png and will be stored in the local path: wallpapers//.png +"class WallpaperDownloader( private val storageRootDirectory: File, private val client: Client, private val dispatcher: CoroutineDispatcher = Dispatchers.IO, ) { private val remoteHost = BuildConfig.WALLPAPER_URL" Can download wallpapers from a remote host. +suspend fun wallpaperImagesExist(wallpaper: Wallpaper): Boolean = withContext(coroutineDispatcher) { allAssetsExist(wallpaper.name) } Checks whether all the assets for a wallpaper exist on the file system. +"fun clean(currentWallpaper: Wallpaper, availableWallpapers: List) { CoroutineScope(coroutineDispatcher).launch { val wallpapersToKeep = (listOf(currentWallpaper) + availableWallpapers).map { it.name } wallpapersDirectory.listFiles()?.forEach { file -> if (file.isDirectory && !wallpapersToKeep.contains(file.name)) { file.deleteRecursively() } } } }" Remove all wallpapers that are not the [currentWallpaper] or in [availableWallpapers]. +"suspend fun lookupExpiredWallpaper(settings: Settings): Wallpaper? = withContext(coroutineDispatcher) { val name = settings.currentWallpaperName if (allAssetsExist(name)) { Wallpaper( name = name, collection = Wallpaper.DefaultCollection, textColor = settings.currentWallpaperTextColor, cardColorLight = settings.currentWallpaperCardColorLight, cardColorDark = settings.currentWallpaperCardColorDark, thumbnailFileState = Wallpaper.ImageFileState.Downloaded, assetsFileState = Wallpaper.ImageFileState.Downloaded, ) } else { null } }  private fun allAssetsExist(name: String): Boolean = Wallpaper.ImageType.values().all { type -> File(storageRootDirectory, getLocalPath(name, type)).exists() }" Lookup all the files for a wallpaper name. This lookup will fail if there are not files for each of a portrait and landscape orientation as well as a thumbnail. +"fun runIfWallpaperCardColorsAreAvailable( run: (cardColorLight: Int, cardColorDark: Int) -> Unit, ) { if (currentWallpaper.cardColorLight != null && currentWallpaper.cardColorDark != null) { run(currentWallpaper.cardColorLight.toInt(), currentWallpaper.cardColorDark.toInt()) } } }" Run the [run] block only if the current wallpaper's card colors are available. +"@Composable fun composeRunIfWallpaperCardColorsAreAvailable( run: @Composable (cardColorLight: Color, cardColorDark: Color) -> Unit, ) { if (currentWallpaper.cardColorLight != null && currentWallpaper.cardColorDark != null) { run(Color(currentWallpaper.cardColorLight), Color(currentWallpaper.cardColorDark)) } }" Run the Composable [run] block only if the current wallpaper's card colors are available. +val wallpaperCardColor: Color @Composable get() = when { currentWallpaper.cardColorLight != null && currentWallpaper.cardColorDark != null -> { if (isSystemInDarkTheme()) { Color(currentWallpaper.cardColorDark) } else { Color(currentWallpaper.cardColorLight) } } else -> FirefoxTheme.colors.layer2 } Helper property used to obtain the [Color] to fill-in cards in front of a wallpaper. +"data class WallpaperState( val currentWallpaper: Wallpaper, val availableWallpapers: List, ) { companion object { val default = WallpaperState( currentWallpaper = Wallpaper.Default, availableWallpapers = listOf(), ) }" Represents all state related to the Wallpapers feature. +"@JvmStatic fun userViewedWhatsNew(context: Context) { userViewedWhatsNew( SharedPreferenceWhatsNewStorage( context, ), ) }} }" Convenience function to run from the context. +@JvmStatic private fun userViewedWhatsNew(storage: WhatsNewStorage) { wasUpdatedRecently = false storage.setWhatsNewHasBeenCleared(true) } "Reset the ""updated"" state and continue as if the app was not updated recently." +"fun shouldHighlightWhatsNew(context: Context): Boolean { return shouldHighlightWhatsNew( ContextWhatsNewVersion(context), context.components.strictMode.resetAfter(StrictMode.allowThreadDiskReads()) { SharedPreferenceWhatsNewStorage(context) }, ) }" Convenience function to run from the context. +"@JvmStatic fun shouldHighlightWhatsNew(currentVersion: WhatsNewVersion, storage: WhatsNewStorage): Boolean { // Cache the value for the lifetime of this process (or until userViewedWhatsNew() is called) if (wasUpdatedRecently == null) { val whatsNew = WhatsNew(storage) wasUpdatedRecently = whatsNew.hasBeenUpdatedRecently(currentVersion) } return wasUpdatedRecently!! }" "Should we highlight the ""What's new"" menu item because this app been updated recently? This method returns true either if this is the first start of the application since it was updated or this is a later start but still recent enough to consider the app to be updated recently." +class WhatsNew private constructor(private val storage: WhatsNewStorage) { private fun hasBeenUpdatedRecently(currentVersion: WhatsNewVersion): Boolean { val lastKnownAppVersion = storage.getVersion() // Update the version and date if *just* updated if (lastKnownAppVersion == null || currentVersion.majorVersionNumber > lastKnownAppVersion.majorVersionNumber ) { storage.setVersion(currentVersion) storage.setDateOfUpdate(System.currentTimeMillis()) return true } return (!storage.getWhatsNewHasBeenCleared() && storage.getDaysSinceUpdate() < DAYS_PER_UPDATE) } } "Helper class tracking whether the application was recently updated in order to show ""What's new"" menu items and indicators in the application UI. The application is considered updated when the application's version name changes (versionName in the manifest). The applications version code would be a good candidates too, but it might  change more often (RC builds) without the application actually changing from the user's point of view. Whenever the application was updated we still consider the application to be ""recently updated for the next few days." +"class AccessibilityGridLayoutManager( context: Context, spanCount: Int, ) : GridLayoutManager( context, spanCount, ) { override fun getColumnCountForAccessibility( recycler: RecyclerView.Recycler, state: RecyclerView.State, ): Int { return if (itemCount < spanCount) { itemCount } else { super.getColumnCountForAccessibility(recycler, state) } } }" A GridLayoutManager that can be used to override methods in Android implementation to improve ayy1 or fix a11y issues. +private fun MotionEvent.endDrawableTouched() = (layoutDirection == LAYOUT_DIRECTION_LTR && rawX >= (right - compoundPaddingRight)) || (layoutDirection == LAYOUT_DIRECTION_RTL && rawX <= (left + compoundPaddingLeft)) } Returns true if the location of the [MotionEvent] is on top of the end drawable. +private fun shouldShowClearButton(length: Int) = length > 0 && error == null Checks if the clear button should be displayed. +"override fun onTextChanged(text: CharSequence?, start: Int, lengthBefore: Int, lengthAfter: Int) { onTextChanged(text) } fun onTextChanged(text: CharSequence?) { // lengthAfter has inconsistent behaviour when there are spaces in the entered text, so we'll use text.length. val textLength = text?.length ?: 0 val drawable = if (shouldShowClearButton(textLength)) { AppCompatResources.getDrawable(context, R.drawable.mozac_ic_clear)?.apply { colorFilter = createBlendModeColorFilterCompat(context.getColorFromAttr(R.attr.textPrimary), SRC_IN) } } else { null } putCompoundDrawablesRelativeWithIntrinsicBounds(end = drawable) }" Displays a clear icon if text has been entered. +"@SuppressLint(""ClickableViewAccessibility"") override fun onTouchEvent(event: MotionEvent): Boolean { if (shouldShowClearButton(length()) && event.action == ACTION_UP && event.endDrawableTouched()) { setText("""") return true } return super.onTouchEvent(event) }" "Clears the text when the clear icon is touched. Since the icon is just a compound drawable, we check the tap location to see if the X position of the tap is where the drawable is located." +"class ClearableEditText @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.editTextStyle, ) : AppCompatEditText(context, attrs, defStyleAttr) {" An [AppCompatEditText] that shows a clear button to the user. +fun getHttpsOnlyMode(): HttpsOnlyMode { return if (!shouldUseHttpsOnly) { HttpsOnlyMode.DISABLED } else if (shouldUseHttpsOnlyInPrivateTabsOnly) { HttpsOnlyMode.ENABLED_PRIVATE_ONLY } else { HttpsOnlyMode.ENABLED } } Get the current mode for how https-only is enabled. +fun getCookieBannerHandling(): CookieBannerHandlingMode { return when (shouldUseCookieBanner) { true -> CookieBannerHandlingMode.REJECT_ALL false -> if (shouldShowCookieBannerUI && !userOptOutOfReEngageCookieBannerDialog) { CookieBannerHandlingMode.DETECT_ONLY } else { CookieBannerHandlingMode.DISABLED } } } Get the current mode for cookie banner handling +"var showSyncCFR by lazyFeatureFlagPreference(appContext.getPreferenceKey(R.string.pref_key_should_show_sync_cfr), featureFlag = true, default = { mr2022Sections[Mr2022Section.SYNC_CFR] == true }, )" Indicates if sync onboarding CFR should be shown. +"var showHomeOnboardingDialog by lazyFeatureFlagPreference(appContext.getPreferenceKey(R.string.pref_key_should_show_home_onboarding_dialog), featureFlag = true, default = { mr2022Sections[Mr2022Section.HOME_ONBOARDING_DIALOG_EXISTING_USERS] == true }, )" Indicates if home onboarding dialog should be shown. +"var showRecentTabsFeature by lazyFeatureFlagPreference( appContext.getPreferenceKey(R.string.pref_key_recent_tabs), featureFlag = true, default = { homescreenSections[HomeScreenSection.JUMP_BACK_IN] == true }, )" Indicates if the recent tabs functionality should be visible. +"var showRecentBookmarksFeature by lazyFeatureFlagPreference( appContext.getPreferenceKey(R.string.pref_key_recent_bookmarks), default = { homescreenSections[HomeScreenSection.RECENTLY_SAVED] == true }, featureFlag = true, )" Indicates if the recent saved bookmarks functionality should be visible. +"var openNextTabInDesktopMode by booleanPreference( appContext.getPreferenceKey(R.string.pref_key_open_next_tab_desktop_mode), default = false, )" "Storing desktop item checkbox value in the home screen menu.If set to true, next opened tab from home screen will be opened in desktop mode." +"var shouldAutofillCreditCardDetails by booleanPreference( appContext.getPreferenceKey(R.string.pref_key_credit_cards_save_and_autofill_cards), default = true, )" "Storing the user choice from the ""Credit cards"" settings for whether save and autofill cards should be enabled or not. If set to `true` when the user focuses on credit card fields in the webpage an Android prompt letting her select the card details to be automatically filled will appear." +"var shouldAutofillAddressDetails by booleanPreference( appContext.getPreferenceKey(R.string.pref_key_addresses_save_and_autofill_addresses), default = true, )" "Stores the user choice from the ""Autofill Addresses"" settings for whether save and autofill addresses should be enabled or not. If set to `true` when the user focuses on address fields in a webpage an Android prompt is shown, allowing the selection of an address details to be automatically filled in the webpage fields." +"var showPocketRecommendationsFeature by lazyFeatureFlagPreference( appContext.getPreferenceKey(R.string.pref_key_pocket_homescreen_recommendations), featureFlag = FeatureFlags.isPocketRecommendationsFeatureEnabled(appContext), default = { homescreenSections[HomeScreenSection.POCKET] == true }, )" Indicates if the Pocket recommended stories homescreen section should be shown. +"val showPocketSponsoredStories by lazyFeatureFlagPreference( key = appContext.getPreferenceKey(R.string.pref_key_pocket_sponsored_stories), default = { homescreenSections[HomeScreenSection.POCKET_SPONSORED_STORIES] == true }, featureFlag = FeatureFlags.isPocketSponsoredStoriesFeatureEnabled(appContext), )" Indicates if the Pocket recommendations homescreen section should also show sponsored stories. +"val pocketSponsoredStoriesProfileId by stringPreference( appContext.getPreferenceKey(R.string.pref_key_pocket_sponsored_stories_profile), default = UUID.randomUUID().toString(), persistDefaultIfNotExists = true, )" Get the profile id to use in the sponsored stories communications with the Pocket endpoint. +"var showContileFeature by booleanPreference( key = appContext.getPreferenceKey(R.string.pref_key_enable_contile), default = true, )" Indicates if the Contile functionality should be visible. +"var enableTaskContinuityEnhancements by booleanPreference( key = appContext.getPreferenceKey(R.string.pref_key_enable_task_continuity), default = true, )" Indicates if the Task Continuity enhancements are enabled. +"var showUnifiedSearchFeature by lazyFeatureFlagPreference( key = appContext.getPreferenceKey(R.string.pref_key_show_unified_search), default = { FxNimbus.features.unifiedSearch.value(appContext).enabled }, featureFlag = FeatureFlags.unifiedSearchFeature, )" Indicates if the Unified Search feature should be visible. +"var homescreenBlocklist by stringSetPreference( appContext.getPreferenceKey(R.string.pref_key_home_blocklist), default = setOf(), )" Blocklist used to filter items from the home screen that have previously been removed. +"var notificationPrePermissionPromptEnabled by lazyFeatureFlagPreference( key = appContext.getPreferenceKey(R.string.pref_key_notification_pre_permission_prompt_enabled), default = { FxNimbus.features.prePermissionNotificationPrompt.value(appContext).enabled }, featureFlag = FeatureFlags.notificationPrePermissionPromptEnabled, )" Indicates if notification pre permission prompt feature is enabled. +"var isNotificationPrePermissionShown by booleanPreference( key = appContext.getPreferenceKey(R.string.pref_key_is_notification_pre_permission_prompt_shown), default = false, )" Indicates if notification permission prompt has been shown to the user. +"var installedAddonsCount by intPreference( appContext.getPreferenceKey(R.string.pref_key_installed_addons_count), 0, )" Storing number of installed add-ons for telemetry purposes +"var installedAddonsList by stringPreference( appContext.getPreferenceKey(R.string.pref_key_installed_addons_list), default = """", )" Storing the list of installed add-ons for telemetry purposes +"val frecencyFilterQuery by stringPreference( appContext.getPreferenceKey(R.string.pref_key_frecency_filter_query), default = ""mfadid=adm"", // Parameter provided by adM )" URLs from the user's history that contain this search param will be hidden. +"var enabledAddonsCount by intPreference( appContext.getPreferenceKey(R.string.pref_key_enabled_addons_count), 0, )" Storing number of enabled add-ons for telemetry purposes +"var enabledAddonsList by stringPreference( appContext.getPreferenceKey(R.string.pref_key_enabled_addons_list), default = """", )" Storing the list of enabled add-ons for telemetry purposes +"var hasInactiveTabsAutoCloseDialogBeenDismissed by booleanPreference( appContext.getPreferenceKey(R.string.pref_key_has_inactive_tabs_auto_close_dialog_dismissed), default = false, )" Indicates if the auto-close dialog for inactive tabs has been dismissed before. +fun shouldShowInactiveTabsAutoCloseDialog(numbersOfTabs: Int): Boolean { return !hasInactiveTabsAutoCloseDialogBeenDismissed && numbersOfTabs >= INACTIVE_TAB_MINIMUM_TO_SHOW_AUTO_CLOSE_DIALOG && !closeTabsAfterOneMonth } "Indicates if the auto-close dialog should be visible based on if the user has dismissed it before [hasInactiveTabsAutoCloseDialogBeenDismissed], if the minimum number of tabs has been accumulated [numbersOfTabs] and if the auto-close setting is already set to [closeTabsAfterOneMonth]." +"var shouldShowJumpBackInCFR by lazyFeatureFlagPreference( appContext.getPreferenceKey(R.string.pref_key_should_show_jump_back_in_tabs_popup), featureFlag = true, default = { mr2022Sections[Mr2022Section.JUMP_BACK_IN_CFR] == true }, )" Indicates if the jump back in CRF should be shown. +"fun getSitePermissionsPhoneFeatureAction( feature: PhoneFeature, default: Action = Action.ASK_TO_ALLOW, ) = preferences.getInt(feature.getPreferenceKey(appContext), default.toInt()).toAction()" Returns a sitePermissions action for the provided [feature]. +"fun setAutoplayUserSetting( autoplaySetting: Int,) { preferences.edit().putInt(AUTOPLAY_USER_SETTING, autoplaySetting).apply() }" Saves the user selected autoplay setting. +"fun getAutoplayUserSetting() = preferences.getInt(AUTOPLAY_USER_SETTING, AUTOPLAY_BLOCK_AUDIBLE) private fun getSitePermissionsPhoneFeatureAutoplayAction( feature: PhoneFeature, default: AutoplayAction = AutoplayAction.BLOCKED, ) = preferences.getInt(feature.getPreferenceKey(appContext), default.toInt()).toAutoplayAction()" Gets the user selected autoplay setting. +"fun setSitePermissionsPhoneFeatureAction( feature: PhoneFeature, value: Action, ) { preferences.edit().putInt(feature.getPreferenceKey(appContext), value.toInt()).apply() }" Sets a sitePermissions action for the provided [feature]. +fun shouldSetReEngagementNotification(): Boolean { return numberOfAppLaunches <= 1 && !reEngagementNotificationShown } Check if we should set the re-engagement notification +fun shouldShowReEngagementNotification(): Boolean { return !reEngagementNotificationShown && !isDefaultBrowserBlocking() } Check if we should show the re-engagement notification. +"var reEngagementNotificationEnabled by lazyFeatureFlagPreference( key = appContext.getPreferenceKey(R.string.pref_key_re_engagement_notification_enabled), default = { FxNimbus.features.reEngagementNotification.value(appContext).enabled }, featureFlag = true, )" Indicates if the re-engagement notification feature is enabled +@VisibleForTesting internal val timerForCookieBannerDialog: Long get() = 60 * 60 * 1000L * (cookieBannersSection[CookieBannersSection.DIALOG_RE_ENGAGE_TIME] ?: 4) Indicates after how many hours a cookie banner dialog should be shown again +fun shouldCookieBannerReEngagementDialog(): Boolean { val shouldShowDialog = shouldShowCookieBannerUI && !userOptOutOfReEngageCookieBannerDialog && !shouldUseCookieBanner return if (!shouldShowTotalCookieProtectionCFR && shouldShowDialog) { !cookieBannerDetectedPreviously || timeNowInMillis() - lastInteractionWithReEngageCookieBannerDialogInMs >= timerForCookieBannerDialog } else { false } } Indicates if we should should show the cookie banner dialog that invites the user to turn-on the setting. +"fun checkIfFenixIsDefaultBrowserOnAppResume(): Boolean { val prefKey = appContext.getPreferenceKey(R.string.pref_key_default_browser) val isDefaultBrowserNow = isDefaultBrowserBlocking() val wasDefaultBrowserOnLastResume = this.preferences.getBoolean(prefKey, isDefaultBrowserNow) this.preferences.edit().putBoolean(prefKey, isDefaultBrowserNow).apply() return isDefaultBrowserNow && !wasDefaultBrowserOnLastResume }" "Declared as a function for performance purposes. This could be declared as a variable using booleanPreference like other members of this class. However, doing so will make it so it will be initialized once Settings.kt is first called, which in turn will call `isDefaultBrowserBlocking()`. This will lead to a performance regression since that function can be expensive to call." +fun isDefaultBrowserBlocking(): Boolean { val browsers = BrowsersCache.all(appContext) return browsers.isDefaultBrowser } "This function is ""blocking"" since calling this can take approx. 30-40ms (timing taken on a G5+)." +"var lastBrowseActivity by longPreference( appContext.getPreferenceKey(R.string.pref_key_last_browse_activity_time), default = 0L, )" "Indicates the last time when the user was interacting with the [BrowserFragment], This is useful to determine if the user has to start on the [HomeFragment] or it should go directly to the [BrowserFragment]." +"var openHomepageAfterFourHoursOfInactivity by booleanPreference( appContext.getPreferenceKey(R.string.pref_key_start_on_home_after_four_hours), default = true, )" Indicates if the user has selected the option to start on the home screen after four hours of inactivity. +"var alwaysOpenTheHomepageWhenOpeningTheApp by booleanPreference( appContext.getPreferenceKey(R.string.pref_key_start_on_home_always), default = false, )" Indicates if the user has selected the option to always start on the home screen. +"var alwaysOpenTheLastTabWhenOpeningTheApp by booleanPreference( appContext.getPreferenceKey(R.string.pref_key_start_on_home_never), default = false, )" Indicates if the user has selected the option to never start on the home screen and have their last tab opened. +fun shouldStartOnHome(): Boolean { return when { openHomepageAfterFourHoursOfInactivity -> timeNowInMillis() - lastBrowseActivity >= FOUR_HOURS_MS alwaysOpenTheHomepageWhenOpeningTheApp -> true alwaysOpenTheLastTabWhenOpeningTheApp -> false else -> false } } "Indicates if the user should start on the home screen, based on the user's preferences." +"var inactiveTabsAreEnabled by booleanPreference( appContext.getPreferenceKey(R.string.pref_key_inactive_tabs), default = true, )" Indicates if the user has enabled the inactive tabs feature. +fun updateIfNeeded(newTrackers: List) { if (newTrackers != trackers) { trackers = newTrackers buckets = putTrackersInBuckets(newTrackers) } } "If [newTrackers] has changed since the last call, update [buckets] based on the new tracker log list." +fun blockedIsEmpty() = buckets.blockedBucketMap.isEmpty() Returns true if there are no trackers being blocked. +fun loadedIsEmpty() = buckets.loadedBucketMap.isEmpty() Returns true if there are no trackers loaded. +"fun get(key: TrackingProtectionCategory, blocked: Boolean) = if (blocked) buckets.blockedBucketMap[key].orEmpty() else buckets.loadedBucketMap[key].orEmpty() companion object { private fun putTrackersInBuckets( list: List, ): BucketedTrackerLog { val blockedMap = createMap() val loadedMap = createMap() for (item in list) { if (item.cookiesHasBeenBlocked) { blockedMap.addTrackerHost(CROSS_SITE_TRACKING_COOKIES, item) } // Blocked categories for (category in item.blockedCategories) { blockedMap.addTrackerHost(category, item) } // Loaded categories for (category in item.loadedCategories) { loadedMap.addTrackerHost(category, item) } } return BucketedTrackerLog(blockedMap, loadedMap) }" Gets the tracker URLs for a given category. +"private fun createMap() = EnumMap>(TrackingProtectionCategory::class.java)" Create an empty mutable map of [TrackingProtectionCategory] to hostnames. +"private fun MutableMap>.addTrackerHost( category: TrackingCategory, tracker: TrackerLog, ) { val key = when (category) { TrackingCategory.CRYPTOMINING -> CRYPTOMINERS TrackingCategory.FINGERPRINTING -> FINGERPRINTERS TrackingCategory.MOZILLA_SOCIAL -> SOCIAL_MEDIA_TRACKERS TrackingCategory.SCRIPTS_AND_SUB_RESOURCES -> TRACKING_CONTENT else -> return } addTrackerHost(key, tracker) }" "Add the hostname of the [TrackerLog.url] into the map for the given category from Android Components. The category is transformed into a corresponding Fenix bucket, and the item is discarded if the category doesn't have a match." +"private fun MutableMap>.addTrackerHost( key: TrackingProtectionCategory, tracker: TrackerLog, ) { getOrPut(key) { mutableListOf() }.add(tracker) } }" Add the hostname of the [TrackerLog] into the map for the given [TrackingProtectionCategory]. +"class ProtectionsStore(initialState: ProtectionsState) : Store( initialState, ::protectionsStateReducer, )" The [Store] for holding the [ProtectionsState] and applying [ProtectionsAction]s. +sealed class ProtectionsAction : Action { } Actions to dispatch through the `TrackingProtectionStore` to modify `ProtectionsState` through the reducer. +"data class Change( val url: String, val isTrackingProtectionEnabled: Boolean, val isCookieBannerHandlingEnabled: Boolean, val listTrackers: List, val mode: ProtectionsState.Mode, ) : ProtectionsAction()"  The values of the tracking protection view has been changed. +data class ToggleCookieBannerHandlingProtectionEnabled(val isEnabled: Boolean) : ProtectionsAction() Toggles the enabled state of cookie banner handling protection. +data class UrlChange(val url: String) : ProtectionsAction() Indicates the url has changed. +data class TrackerLogChange(val listTrackers: List) : ProtectionsAction() Indicates the url has the list of trackers has been updated. +object ExitDetailsMode : ProtectionsAction() Indicates the user is leaving the detailed view. +"data class EnterDetailsMode( val category: TrackingProtectionCategory, val categoryBlocked: Boolean, ) : ProtectionsAction() }" Holds the data to show a detailed tracking protection view. +"data class ProtectionsState( val tab: SessionState?, val url: String, val isTrackingProtectionEnabled: Boolean, val isCookieBannerHandlingEnabled: Boolean, val listTrackers: List, val mode: Mode, val lastAccessedCategory: String,)  : State { }" The state for the Protections Panel +sealed class Mode { } Indicates the modes in which a tracking protection view could be in. +object Normal : Mode() Indicates that tracking protection view should not be in detail mode. +"data class Details(val selectedCategory: TrackingProtectionCategory,val categoryBlocked: Boolean,) : Mode()}" Indicates that tracking protection view in detailed mode. +"enum class TrackingProtectionCategory( @StringRes val title: Int, @StringRes val description: Int, ) { SOCIAL_MEDIA_TRACKERS( R.string.etp_social_media_trackers_title, R.string.etp_social_media_trackers_description, ), CROSS_SITE_TRACKING_COOKIES( R.string.etp_cookies_title, R.string.etp_cookies_description, ), CRYPTOMINERS( R.string.etp_cryptominers_title, R.string.etp_cryptominers_description, ), FINGERPRINTERS( R.string.etp_fingerprinters_title, R.string.etp_fingerprinters_description, ), TRACKING_CONTENT( R.string.etp_tracking_content_title, R.string.etp_tracking_content_description, ), REDIRECT_TRACKERS( R.string.etp_redirect_trackers_title, R.string.etp_redirect_trackers_description, ), }" The 5 categories of Tracking Protection to display +"fun protectionsStateReducer( state: ProtectionsState, action: ProtectionsAction, ): ProtectionsState { return when (action) { is ProtectionsAction.Change -> state.copy( url = action.url, isTrackingProtectionEnabled = action.isTrackingProtectionEnabled, isCookieBannerHandlingEnabled = action.isCookieBannerHandlingEnabled, listTrackers = action.listTrackers, mode = action.mode, ) is ProtectionsAction.UrlChange -> state.copy( url = action.url, ) is ProtectionsAction.TrackerLogChange -> state.copy(listTrackers = action.listTrackers) ProtectionsAction.ExitDetailsMode -> state.copy( mode = ProtectionsState.Mode.Normal, ) is ProtectionsAction.EnterDetailsMode -> state.copy( mode = ProtectionsState.Mode.Details( action.category, action.categoryBlocked, ), lastAccessedCategory = action.category.name, ) is ProtectionsAction.ToggleCookieBannerHandlingProtectionEnabled -> state.copy( isCookieBannerHandlingEnabled = action.isEnabled, ) }" The [ProtectionsState] reducer. +"class TabsTrayStore( initialState: TabsTrayState = TabsTrayState(), middlewares: List> = emptyList(), ) : Store( initialState, TabsTrayReducer::reduce, middlewares, )" A [Store] that holds the [TabsTrayState] for the tabs tray and reduces [TabsTrayAction]sdispatched to the store. +"internal object TabsTrayReducer { fun reduce(state: TabsTrayState, action: TabsTrayAction): TabsTrayState { return when (action) { is TabsTrayAction.EnterSelectMode -> state.copy(mode = TabsTrayState.Mode.Select(emptySet())) is TabsTrayAction.ExitSelectMode -> state.copy(mode = TabsTrayState.Mode.Normal) is TabsTrayAction.AddSelectTab -> state.copy(mode = TabsTrayState.Mode.Select(state.mode.selectedTabs + action.tab)) is TabsTrayAction.RemoveSelectTab -> { val selected = state.mode.selectedTabs.filter { it.id != action.tab.id }.toSet() state.copy( mode = if (selected.isEmpty()) { TabsTrayState.Mode.Normal } else { TabsTrayState.Mode.Select(selected) }, ) } is TabsTrayAction.PageSelected -> state.copy(selectedPage = action.page) is TabsTrayAction.SyncNow -> state.copy(syncing = true) is TabsTrayAction.SyncCompleted -> state.copy(syncing = false) is TabsTrayAction.UpdateInactiveTabs -> state.copy(inactiveTabs = action.tabs) is TabsTrayAction.UpdateNormalTabs -> state.copy(normalTabs = action.tabs) is TabsTrayAction.UpdatePrivateTabs -> state.copy(privateTabs = action.tabs) is TabsTrayAction.UpdateSyncedTabs -> state.copy(syncedTabs = action.tabs) } } }" Reducer for [TabsTrayStore]. +data class UpdateSyncedTabs(val tabs: List) : TabsTrayAction()} Updates the list of synced tabs in [TabsTrayState.syncedTabs]. +data class UpdatePrivateTabs(val tabs: List) : TabsTrayAction() Updates the list of tabs in [TabsTrayState.privateTabs]. +data class UpdateNormalTabs(val tabs: List) : TabsTrayAction() Updates the list of tabs in [TabsTrayState.normalTabs]. +data class UpdateInactiveTabs(val tabs: List) : TabsTrayAction() Updates the list of tabs in [TabsTrayState.inactiveTabs]. +object SyncCompleted : TabsTrayAction() "When a ""sync"" action has completed; this can be triggered immediately after [SyncNow] if no sync action was able to be performed." +object SyncNow : TabsTrayAction() "A request to perform a ""sync"" action." +data class PageSelected(val page: Page) : TabsTrayAction() the active page in the tray that is now in focus. +data class RemoveSelectTab(val tab: TabSessionState) : TabsTrayAction() Removed a [TabSessionState] from the selection set. +data class AddSelectTab(val tab: TabSessionState) : TabsTrayAction() Added a new [TabSessionState] to the selection set. +object ExitSelectMode : TabsTrayAction() Exited multi-select mode. +object EnterSelectMode : TabsTrayAction() Entered multi-select mode. +sealed class TabsTrayAction : Action {} [Action] implementation related to [TabsTrayStore]. +data class Select(override val selectedTabs: Set) : Mode({} The multi-select mode that the tabs list is in containing the set of currently selected tabs. +object Normal : Mode() The default mode the tabs list is in. +open val selectedTabs = emptySet() A set of selected tabs which we would want to perform an action on. +sealed class Mode { } The current mode that the tabs list is in. +"data class TabsTrayState( val selectedPage: Page = Page.NormalTabs, val mode: Mode = Mode.Normal, val inactiveTabs: List = emptyList(), val normalTabs: List = emptyList(), val privateTabs: List = emptyList(), val syncedTabs: List = emptyList(), val syncing: Boolean = false, ) : State { }" Value type that represents the state of the tabs tray. +"abstract class AbstractPageViewHolder constructor( val containerView: View, ) : RecyclerView.ViewHolder(containerView) { }" An abstract [RecyclerView.ViewHolder] for [TrayPagerAdapter] items. +"abstract fun bind( adapter: RecyclerView.Adapter, )" Invoked when the nested [RecyclerView.Adapter] is bound to the [RecyclerView.ViewHolder]. +abstract fun attachedToWindow() Invoked when the [RecyclerView.ViewHolder] is attached from the window. This could have previously been bound and is now attached again. +abstract fun detachedFromWindow() } Invoked when the [RecyclerView.ViewHolder] is detached from the window. +"override fun attachedToWindow() { adapterRef?.let { adapter -> adapterObserver = object : RecyclerView.AdapterDataObserver() { override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { updateTrayVisibility(showTrayList(adapter)) }  override fun onItemRangeRemoved(positionstart: Int, itemcount: Int) { updateTrayVisibility(showTrayList(adapter)) } } adapterObserver?.let { adapter.registerAdapterDataObserver(it) } } }" When the [RecyclerView.Adapter] is attached to the window we register a data observer to always check whether to call [updateTrayVisibility]. +override fun detachedFromWindow() { adapterObserver?.let { adapterRef?.unregisterAdapterDataObserver(it) adapterObserver = null } } "[RecyclerView.AdapterDataObserver]s are responsible to be unregistered when they are done, so we do that here when our [TrayPagerAdapter] page is detached from the window." +open fun showTrayList(adapter: RecyclerView.Adapter): Boolean = adapter.itemCount > 0 A way for an implementor of [AbstractBrowserPageViewHolder] to define their own behavior of when to show/hide the tray list and empty list UI. +fun updateTrayVisibility(showTrayList: Boolean) { trayList.isVisible = showTrayList emptyList.isVisible = !showTrayList } Helper function used to toggle the visibility of the tabs tray lists and the empty list message. +"fun BrowserMenu.showWithTheme(view: View) { show(view).also { popupMenu -> (popupMenu.contentView as? CardView)?.setCardBackgroundColor( ContextCompat.getColor( view.context, R.color.fx_mobile_layer_color_2, ), ) } }" Invokes [BrowserMenu.show] and applies the default theme color background. +"@OptIn(ExperimentalCoroutinesApi::class) class SyncButtonBinding( tabsTrayStore: TabsTrayStore, private val onSyncNow: () -> Unit, ) : AbstractBinding(tabsTrayStore) { override suspend fun onState(flow: Flow) { flow.map { it.syncing } .ifChanged() .collect { syncingNow -> if (syncingNow) { onSyncNow() } } } }" An [AbstractBinding] that invokes the [onSyncNow] callback when the [TabsTrayState.syncing] is set. +fun TabSessionState.hasSearchTerm(): Boolean { return content.searchTerms.isNotEmpty() || !historyMetadata?.searchTerm.isNullOrBlank() } Returns true if the [TabSessionState] has a search term. +internal fun TabSessionState.isNormalTabActive(maxActiveTime: Long): Boolean { return isActive(maxActiveTime) && !content.private } Returns true if the [TabSessionState] is considered active based on the [maxActiveTime]. +internal fun TabSessionState.isNormalTabActiveWithSearchTerm(maxActiveTime: Long): Boolean { return isNormalTabActive(maxActiveTime) && hasSearchTerm() } Returns true if the [TabSessionState] have a search term. +internal fun TabSessionState.isNormalTabWithSearchTerm(): Boolean { return hasSearchTerm() && !content.private } Returns true if the [TabSessionState] has a search term but may or may not be active. +internal fun TabSessionState.isNormalTabInactive(maxActiveTime: Long): Boolean { return !isActive(maxActiveTime) && !content.private } Returns true if the [TabSessionState] is considered active based on the [maxActiveTime]. +internal fun TabSessionState.isNormalTab(): Boolean { return !content.private } Returns true if the [TabSessionState] is not private.  +fun TabSessionState.toDisplayTitle(): String = content.title.ifEmpty { content.url.trimmed() } Returns a [String] for displaying a [TabSessionState]'s title or its url when a title is not available. +"fun BrowserState.getNormalTrayTabs( inactiveTabsEnabled: Boolean, ): List { return normalTabs.run { if (inactiveTabsEnabled) { filter { it.isNormalTabActive(maxActiveTime) } } else { this } } }" The list of normal tabs in the tabs tray filtered appropriately based on feature flags. +fun BrowserState.findPrivateTab(tabId: String): TabSessionState? { return privateTabs.firstOrNull { it.id == tabId } } Finds and returns the private tab with the given id. Returns null if no matching tab could be found. +val BrowserState.selectedPrivateTab: TabSessionState? get() = selectedTabId?.let { id -> findPrivateTab(id) } The currently selected tab if there's one that is private. +"fun SyncedTabsView.ErrorType.toSyncedTabsListItem(context: Context, navController: NavController) = when (this) { SyncedTabsView.ErrorType.MULTIPLE_DEVICES_UNAVAILABLE -> SyncedTabsListItem.Error(errorText = context.getString(R.string.synced_tabs_connect_another_device)) SyncedTabsView.ErrorType.SYNC_ENGINE_UNAVAILABLE -> SyncedTabsListItem.Error(errorText = context.getString(R.string.synced_tabs_enable_tab_syncing)) SyncedTabsView.ErrorType.SYNC_NEEDS_REAUTHENTICATION -> SyncedTabsListItem.Error(errorText = context.getString(R.string.synced_tabs_reauth)) SyncedTabsView.ErrorType.NO_TABS_AVAILABLE -> SyncedTabsListItem.Error( errorText = context.getString(R.string.synced_tabs_no_tabs), ) SyncedTabsView.ErrorType.SYNC_UNAVAILABLE -> SyncedTabsListItem.Error( errorText = context.getString(R.string.synced_tabs_sign_in_message), errorButton = SyncedTabsListItem.ErrorButton( buttonText = context.getString(R.string.synced_tabs_sign_in_button), ) { navController.navigate(NavGraphDirections.actionGlobalTurnOnSync()) }, ) }" Converts [SyncedTabsView.ErrorType] to [SyncedTabsListItem.Error] with a lambda for ONLY [SyncedTabsView.ErrorType.SYNC_UNAVAILABLE] +"fun List.toComposeList( taskContinuityEnabled: Boolean, ): List = asSequence().flatMap { (device, tabs) -> if (taskContinuityEnabled) { val deviceTabs = if (tabs.isEmpty()) { emptyList() } else { tabs.map { val url = it.active().url val titleText = it.active().title.ifEmpty { url.trimmed() } SyncedTabsListItem.Tab(titleText, url, it) } } sequenceOf(SyncedTabsListItem.DeviceSection(device.displayName, deviceTabs)) } else { val deviceTabs = if (tabs.isEmpty()) { sequenceOf(SyncedTabsListItem.NoTabs) } else { tabs.asSequence().map { val url = it.active().url val titleText = it.active().title.ifEmpty { url.trimmed() } SyncedTabsListItem.Tab(titleText, url, it) } } sequenceOf(SyncedTabsListItem.Device(device.displayName)) + deviceTabs } }.toList()" Converts a list of [SyncedDeviceTabs] into a list of [SyncedTabsListItem]. +"fun RecyclerView.Adapter.observeFirstInsert(block: () -> Unit) { val observer = object : RecyclerView.AdapterDataObserver() { override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { block.invoke() unregisterAdapterDataObserver(this) } } registerAdapterDataObserver(observer) }" Observes the adapter and invokes the callback [block] only when data is first inserted to the adapter. +internal val Context.defaultBrowserLayoutColumns: Int get() { return if (components.settings.gridTabView) { numberOfGridColumns } else { 1 } } Returns the default number of columns a browser tray list should display based on user preferences. +internal val Context.numberOfGridColumns: Int get() { val displayMetrics = resources.displayMetrics val screenWidthDp = displayMetrics.widthPixels / displayMetrics.density return (screenWidthDp / MIN_COLUMN_WIDTH_DP).toInt().coerceAtLeast(2) } Returns the number of grid columns we can fit on the screen in the tabs tray. +internal val ConcatAdapter.browserAdapter get() = adapters.find { it is BrowserTabsAdapter } as BrowserTabsAdapter A convenience binding for retrieving the [BrowserTabsAdapter] from the [ConcatAdapter]. +internal val ConcatAdapter.inactiveTabsAdapter get() = adapters.find { it is InactiveTabsAdapter } as InactiveTabsAdapter A convenience binding for retrieving the [InactiveTabsAdapter] from the [ConcatAdapter]. +fun BrowserStore.getTabSessionState(tabs: Collection): List { return tabs.mapNotNull { state.findTab(it.id) } } Find and extract a list [TabSessionState] from the [BrowserStore] using the IDs from [tabs]. +Opens the provided inactive tab. fun handleInactiveTabClicked(tab: TabSessionState) +fun handleCloseInactiveTabClicked(tab: TabSessionState) Closes the provided inactive tab. +fun handleInactiveTabsHeaderClicked(expanded: Boolean) Expands or collapses the inactive tabs section. +fun handleInactiveTabsAutoCloseDialogDismiss() Dismisses the inactive tabs auto-close dialog. +fun handleEnableInactiveTabsAutoCloseClicked() Enables the inactive tabs auto-close feature with a default time period. +fun handleDeleteAllInactiveTabsClicked() Deletes all inactive tabs. +"fun open(tab: TabSessionState, source: String? = null)" Open a tab. +"fun close(tab: TabSessionState, source: String? = null)" Close the tab. +fun onFabClicked(isPrivate: Boolean) TabTray's Floating Action Button clicked. +fun onRecentlyClosedClicked() Recently Closed item is clicked. +fun onMediaClicked(tab: TabSessionState) Indicates Play/Pause item is clicked. +"fun onMultiSelectClicked( tab: TabSessionState, holder: SelectionHolder, source: String?, )" Handles clicks when multi-selection is enabled. +"fun onLongClicked( tab: TabSessionState, holder: SelectionHolder, ): Boolean" Handles long click events when tab item is clicked. +"private fun updateSyncPreferenceNeedsReauth() { syncPreference.apply { isSwitchWidgetVisible = false title = loggedOffTitle setOnPreferenceChangeListener { _, _ -> onReconnectClicked() false } } }" Displays the logged off title to prompt the user to to re-authenticate their sync account. +"private fun updateSyncPreferenceNeedsLogin() { syncPreference.apply { isSwitchWidgetVisible = false title = loggedOffTitle setOnPreferenceChangeListener { _, _ -> onSyncSignInClicked() false } } }" Display that the user can sync across devices when the user is logged off. +"private fun updateSyncPreferenceStatus() { syncPreference.apply { isSwitchWidgetVisible = true val syncEnginesStatus = SyncEnginesStorage(context).getStatus() val syncStatus = syncEnginesStatus.getOrElse(syncEngine) { false } title = loggedInTitle isChecked = syncStatus setOnPreferenceChangeListener { _, newValue -> SyncEnginesStorage(context).setStatus(syncEngine, newValue as Boolean) setSwitchCheckedState(newValue) true } } }" Shows a switch toggle for the sync preference when the user is logged in. +"fun getSumoURLForTopic( context: Context, topic: SumoTopic, locale: Locale = Locale.getDefault(), ): String { val escapedTopic = getEncodedTopicUTF8(topic.topicStr) // Remove the whitespace so a search is not triggered: val appVersion = context.appVersionName.replace("" "", """") val osTarget = ""Android"" val langTag = getLanguageTag(locale) return ""https://support.mozilla.org/1/mobile/$appVersion/$osTarget/$langTag/$escapedTopic"" }" Gets a support page URL for the corresponding topic. +"fun getGenericSumoURLForTopic(topic: SumoTopic, locale: Locale = Locale.getDefault()): String { val escapedTopic = getEncodedTopicUTF8(topic.topicStr) val langTag = getLanguageTag(locale) return ""https://support.mozilla.org/$langTag/kb/$escapedTopic"" }" Gets a support page URL for the corresponding topic.Used when the app version and os are not part of the URL. +"open class StringSharedPreferenceUpdater : Preference.OnPreferenceChangeListener { override fun onPreferenceChange(preference: Preference, newValue: Any?): Boolean { val newStringValue = newValue as? String ?: return false preference.context.settings().preferences.edit { putString(preference.key, newStringValue) } return true } }" Updates the corresponding [android.content.SharedPreferences] when the String [Preference] is changed. The preference key is used as the shared preference key. +"open class SharedPreferenceUpdater : Preference.OnPreferenceChangeListener { override fun onPreferenceChange(preference: Preference, newValue: Any?): Boolean { val newBooleanValue = newValue as? Boolean ?: return false preference.context.settings().preferences.edit { putBoolean(preference.key, newBooleanValue) } return true } }" Updates the corresponding [android.content.SharedPreferences] when the boolean [Preference] is changed. The preference key is used as the shared preference key. +open fun getDescription(): String? = null Returns the description to be used the UI. +abstract fun getLearnMoreUrl(): String Returns the URL that should be used when the learn more link is clicked. +abstract fun getSwitchValue(): Boolean Indicates the value which the switch widget should show. +"fun RadioButton.setStartCheckedIndicator() { val attr = context.theme.resolveAttribute(android.R.attr.listChoiceIndicatorSingle) val buttonDrawable = AppCompatResources.getDrawable(context, attr) buttonDrawable?.apply { setBounds(0, 0, intrinsicWidth, intrinsicHeight) } putCompoundDrawablesRelative(start = buttonDrawable) }" "In devices with Android 6, when we use android:button=""@null"" android:drawableStart doesn't work via xml as a result we have to apply it programmatically. More info about this issue https://github.com/mozilla-mobile/fenix/issues/1414" +"inline fun Preference.setOnPreferenceChangeListener( crossinline onPreferenceChangeListener: (Preference, T) -> Boolean, ) { setOnPreferenceChangeListener { preference: Preference, newValue: Any -> (newValue as? T)?.let { onPreferenceChangeListener(preference, it) } ?: false } }" Sets the callback to be invoked when this preference is changed by the user (but before the internal state has been updated). Allows the type of the preference to be specified. If the new value doesn't match the preference type the listener isn't called. +fun PreferenceFragmentCompat.requirePreference(@StringRes preferenceId: Int) = requireNotNull(findPreference(getPreferenceKey(preferenceId))) Find a preference with the corresponding key and throw if it does not exist. +"class AuthIntentReceiverActivity : Activity() { @VisibleForTesting override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) MainScope().launch { // The intent property is nullable, but the rest of the code below // assumes it is not. If it's null, then we make a new one and open // the HomeActivity. val intent = intent?.let { Intent(intent) } ?: Intent() if (settings().lastKnownMode.isPrivate) { components.intentProcessors.privateCustomTabIntentProcessor.process(intent) } else { components.intentProcessors.customTabIntentProcessor.process(intent) } intent.setClassName(applicationContext, AuthCustomTabActivity::class.java.name) intent.putExtra(HomeActivity.OPEN_TO_BROWSER, true) startActivity(intent) finish() } } }" Processes incoming intents and sends them to the corresponding activity. +"fun updateAccountUIState(context: Context, profile: Profile?) { val account = accountManager.authenticatedAccount() updateFxAAllowDomesticChinaServerMenu() // Signed-in, no problems. if (account != null && !accountManager.accountNeedsReauth()) { preferenceSignIn.isVisible = false avatarJob?.cancel() val avatarUrl = profile?.avatar?.url if (avatarUrl != null) { avatarJob = scope.launch { val roundedAvatarDrawable = toRoundedDrawable(avatarUrl, context) preferenceFirefoxAccount.icon = roundedAvatarDrawable ?: genericAvatar(context) } } else { avatarJob = null preferenceFirefoxAccount.icon = genericAvatar(context) } preferenceSignIn.onPreferenceClickListener = null preferenceFirefoxAccountAuthError.isVisible = false preferenceFirefoxAccount.isVisible = true accountPreferenceCategory.isVisible = true preferenceFirefoxAccount.displayName = profile?.displayName preferenceFirefoxAccount.email = profile?.email // Signed-in, need to re-authenticate. } else if (account != null && accountManager.accountNeedsReauth()) { preferenceFirefoxAccount.isVisible = false preferenceFirefoxAccountAuthError.isVisible = true accountPreferenceCategory.isVisible = true preferenceSignIn.isVisible = false preferenceSignIn.onPreferenceClickListener = null preferenceFirefoxAccountAuthError.email = profile?.email // Signed-out. } else { preferenceSignIn.isVisible = true preferenceFirefoxAccount.isVisible = false preferenceFirefoxAccountAuthError.isVisible = false accountPreferenceCategory.isVisible = false } }" "Updates the UI to reflect current account state. Possible conditions are logged-in without problems, logged-out, and logged-in but needs to re-authenticate." +fun cancel() { scope.cancel() } Cancel any running coroutine jobs for loading account images. +"private fun genericAvatar(context: Context) = AppCompatResources.getDrawable(context, R.drawable.ic_account)" Returns generic avatar for accounts. +"private suspend fun toRoundedDrawable( url: String, context: Context, ) = httpClient.bitmapForUrl(url)?.let { bitmap -> RoundedBitmapDrawableFactory.create(context.resources, bitmap).apply { isCircular = true setAntiAlias(true) } }" "Gets a rounded drawable from a URL if possible, else null." +"fun verifyCredentialsOrShowSetupWarning(context: Context, prefList: List) { // Use the BiometricPrompt if available if (BiometricPromptFeature.canUseFeature(context)) { togglePrefsEnabled(prefList, false) biometricPromptFeature.get()?.requestAuthentication(unlockMessage()) return } // Fallback to prompting for password with the KeyguardManager val manager = context.getSystemService() if (manager?.isKeyguardSecure == true) { showPinVerification(manager) } else { // Warn that the device has not been secured if (context.settings().shouldShowSecurityPinWarning) { showPinDialogWarning(context) } else { navigateOnSuccess() } } }" Use [BiometricPromptFeature] or [KeyguardManager] to confirm device security. +"fun setBiometricPrompt(view: View, prefList: List) { biometricPromptFeature.set( feature = BiometricPromptFeature( context = requireContext(), fragment = this, onAuthFailure = { togglePrefsEnabled(prefList, true) }, onAuthSuccess = ::navigateOnSuccess, ), owner = this, view = view, ) }" Sets the biometric prompt feature. +"@Suppress(""Deprecation"") abstract fun showPinVerification(manager: KeyguardManager)" Creates a prompt to verify the device's pin/password and start activity based on the result. This is only used when BiometricPrompt is unavailable on the device. +"fun togglePrefsEnabled(prefList: List, enabled: Boolean) { for (preference in prefList) { requirePreference(preference).isEnabled = enabled } }" Toggle preferences to enable or disable navigation during authentication flows. +abstract fun showPinDialogWarning(context: Context) Shows a dialog warning to set up a pin/password when the device is not secured. This is only used when BiometricPrompt is unavailable on the device. +abstract fun navigateOnSuccess() Navigate when authentication is successful. +abstract fun unlockMessage(): String Gets the string to be used for [BiometricPromptFeature.requestAuthentication] prompting to unlock the device. +fun BiometricManager.isEnrolled(): Boolean { val status = canAuthenticate(BIOMETRIC_WEAK) return status == BIOMETRIC_SUCCESS } Checks if the user can use the [BiometricManager] and is therefore enrolled. +fun BiometricManager.isHardwareAvailable(): Boolean { val status = canAuthenticate(BIOMETRIC_WEAK) return status != BIOMETRIC_ERROR_NO_HARDWARE && status != BIOMETRIC_ERROR_HW_UNAVAILABLE } Checks if the hardware requirements are met for using the [BiometricManager]. +"private fun autofillFragmentStateReducer( state: AutofillFragmentState, action: AutofillAction, ): AutofillFragmentState { return when (action) { is AutofillAction.UpdateAddresses -> { state.copy( addresses = action.addresses, isLoading = false, ) } is AutofillAction.UpdateCreditCards -> { state.copy( creditCards = action.creditCards, isLoading = false, ) } } }" Reduces the autofill state from the current state with the provided [action] to be performed. +"fun LocaleManager.getSelectedLocale( context: Context, localeList: List = getSupportedLocales(), ): Locale { val selectedLocale = getCurrentLocale(context)?.toLanguageTag() val defaultLocale = getSystemDefault() return if (selectedLocale == null) { defaultLocale } else { val supportedMatch = localeList .firstOrNull { it.toLanguageTag() == selectedLocale } supportedMatch ?: defaultLocale } }" "Returns the locale that corresponds to the language stored locally by us. If no suitable one is found, return default." +"fun LocaleManager.getSupportedLocales(): List { val resultLocaleList: MutableList = ArrayList() resultLocaleList.add(0, getSystemDefault()) resultLocaleList.addAll( BuildConfig.SUPPORTED_LOCALE_ARRAY .toList() .map { it.toLocale() }.sortedWith( compareBy( { it.displayLanguage }, { it.displayCountry }, ), ), ) return resultLocaleList }" "Returns a list of currently supported locales, with the system default set as the first one" +"private fun localeSettingsStateReducer( state: LocaleSettingsState, action: LocaleSettingsAction, ): LocaleSettingsState { return when (action) { is LocaleSettingsAction.Select -> { state.copy(selectedLocale = action.selectedItem, searchedLocaleList = state.localeList) } is LocaleSettingsAction.Search -> { val searchedItems = state.localeList.filter { it.getDisplayLanguage(it).startsWith(action.query, ignoreCase = true) || it.displayLanguage.startsWith(action.query, ignoreCase = true) || it === state.localeList[0] } state.copy(searchedLocaleList = searchedItems) } } }" Reduces the locale state from the current state and an action performed on it. +sealed class LocaleSettingsAction : Action { data class Select(val selectedItem: Locale) : LocaleSettingsAction() data class Search(val query: String) : LocaleSettingsAction() } Actions to dispatch through the `LocaleSettingsStore` to modify `LocaleSettingsState` through the reducer. +"data class LocaleSettingsState( val localeList: List, val searchedLocaleList: List, val selectedLocale: Locale, ) : State fun createInitialLocaleSettingsState(context: Context): LocaleSettingsState { val supportedLocales = LocaleManager.getSupportedLocales() return LocaleSettingsState( supportedLocales, supportedLocales, selectedLocale = LocaleManager.getSelectedLocale(context), ) }" The state of the language selection page +"private fun Locale.getProperDisplayName(): String { val displayName = this.displayName.capitalize(Locale.getDefault()) if (displayName.equals(this.toString(), ignoreCase = true)) { return LocaleViewHolder.LOCALE_TO_DISPLAY_ENGLISH_NAME_MAP[this.toString()] ?: displayName } return displayName }" "Returns the locale in the selected language, with fallback to English name" +"private fun String.capitalize(locale: Locale): String { return substring(0, 1).uppercase(locale) + substring(1) }" "Similar to Kotlin's capitalize with locale parameter, but that method is currently experimental" +"fun Address.getAddressLabel(): String = listOf( streetAddress.toOneLineAddress(), addressLevel3, addressLevel2, organization, addressLevel1, country, postalCode, tel, email, ).filter { it.isNotEmpty() }.joinToString("", "")" Generate a description item text for an [Address].  +"fun Address.getFullName(): String = listOf(givenName, additionalName, familyName) .filter { it.isNotEmpty() } .joinToString("" "")" Generate a label item text for an [Address] +private fun loadAddresses() { lifecycleScope.launch { val addresses = requireContext().components.core.autofillStorage.getAllAddresses() lifecycleScope.launch(Dispatchers.Main) { store.dispatch(AutofillAction.UpdateAddresses(addresses)) } } } Fetches all the addresses from the autofill storage and updates the [AutofillFragmentStore] with the list of addresses. +"@Composable fun AddressList( addresses: List
, onAddressClick: (Address) -> Unit, onAddAddressButtonClick: () -> Unit, ) { LazyColumn { items(addresses) { address -> TextListItem( label = address.getFullName(), modifier = Modifier.padding(start = 56.dp), description = address.getAddressLabel(), maxDescriptionLines = 2, onClick = { onAddressClick(address) }, ) } item { IconListItem( label = stringResource(R.string.preferences_addresses_add_address), beforeIconPainter = painterResource(R.drawable.ic_new), onClick = onAddAddressButtonClick, ) } } }" A list of addresses. +"fun onUpdateAddress(guid: String, addressFields: UpdatableAddressFields)" "Updates the provided address in the autofill storage. Called when a user taps on the update menu item or ""Update"" button." +fun onDeleteAddress(guid: String) "Deletes the provided address from the autofill storage. Called when a user taps on the save menu item or ""Save"" button." +fun onSaveAddress(addressFields: UpdatableAddressFields) "Saves the provided address field into the autofill storage. Called when a user taps on the save menu item or ""Save"" button." +fun onCancelButtonClicked() "Navigates back to the autofill preference settings. Called when a user taps on the ""Cancel"" button." +"private fun syncDeviceName(newDeviceName: String): Boolean { if (newDeviceName.trim().isEmpty()) { return false } // This may fail, and we'll have a disparity in the UI until `updateDeviceName` is called. viewLifecycleOwner.lifecycleScope.launch(Main) { context?.let { accountManager.authenticatedAccount() ?.deviceConstellation() ?.setDeviceName(newDeviceName, it) } } return true }" Takes a non-empty value and sets the device name. May fail due to authentication. +private fun syncNow() { viewLifecycleOwner.lifecycleScope.launch { SyncAccount.syncNow.record(NoExtras()) // Trigger a sync. requireComponents.backgroundServices.accountManager.syncNow(SyncReason.User) // Poll for device events & update devices. accountManager.authenticatedAccount() ?.deviceConstellation()?.run { refreshDevices() pollForCommands() } } } Manual sync triggered by the user. This also checks account authentication and refreshes the device list. +private fun updateSyncEngineStates() { val syncEnginesStatus = SyncEnginesStorage(requireContext()).getStatus() requirePreference(R.string.pref_key_sync_bookmarks).apply { isEnabled = syncEnginesStatus.containsKey(SyncEngine.Bookmarks) isChecked = syncEnginesStatus.getOrElse(SyncEngine.Bookmarks) { true } } requirePreference(R.string.pref_key_sync_credit_cards).apply { isEnabled = syncEnginesStatus.containsKey(SyncEngine.CreditCards) isChecked = syncEnginesStatus.getOrElse(SyncEngine.CreditCards) { true } } requirePreference(R.string.pref_key_sync_history).apply { isEnabled = syncEnginesStatus.containsKey(SyncEngine.History) isChecked = syncEnginesStatus.getOrElse(SyncEngine.History) { true } } requirePreference(R.string.pref_key_sync_logins).apply { isEnabled = syncEnginesStatus.containsKey(SyncEngine.Passwords) isChecked = syncEnginesStatus.getOrElse(SyncEngine.Passwords) { true } } requirePreference(R.string.pref_key_sync_tabs).apply { isEnabled = syncEnginesStatus.containsKey(SyncEngine.Tabs) isChecked = syncEnginesStatus.getOrElse(SyncEngine.Tabs) { true } } requirePreference(R.string.pref_key_sync_address).apply { isVisible = FeatureFlags.syncAddressesFeature isEnabled = syncEnginesStatus.containsKey(SyncEngine.Addresses) isChecked = syncEnginesStatus.getOrElse(SyncEngine.Addresses) { true } } } Updates the status of all [SyncEngine] states. +"private fun showPinDialogWarning(syncEngine: SyncEngine, newValue: Boolean) { context?.let { AlertDialog.Builder(it).apply { setTitle(getString(R.string.logins_warning_dialog_title)) setMessage( getString(R.string.logins_warning_dialog_message), ) setNegativeButton(getString(R.string.logins_warning_dialog_later)) { _: DialogInterface, _ -> updateSyncEngineState(syncEngine, newValue) } setPositiveButton(getString(R.string.logins_warning_dialog_set_up_now)) { it: DialogInterface, _ -> it.dismiss() val intent = Intent( Settings.ACTION_SECURITY_SETTINGS, ) startActivity(intent) } create() }.show().secure(activity) it.settings().incrementShowLoginsSecureWarningSyncCount() } }" Creates and shows a warning dialog that prompts the user to create a pin/password to secure their device when none is detected. The user has the option to continue with updating their sync preferences (updates the [SyncEngine] state) or navigating to device security settings to create a pin/password. +"private fun updateSyncEngineState(engine: SyncEngine, newValue: Boolean) { SyncEnginesStorage(requireContext()).setStatus(engine, newValue) viewLifecycleOwner.lifecycleScope.launch { requireContext().components.backgroundServices.accountManager.syncNow(SyncReason.EngineChange) } }" Updates the sync engine status with the new state of the preference and triggers a sync event. +"private fun updateSyncEngineStateWithPinWarning( syncEngine: SyncEngine, newValue: Boolean, ) { val manager = activity?.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager if (manager.isKeyguardSecure || !newValue || !requireContext().settings().shouldShowSecurityPinWarningSync ) { updateSyncEngineState(syncEngine, newValue) } else { showPinDialogWarning(syncEngine, newValue) } }" "Prompts the user if they do not have a password/pin set up to secure their device, and updates the state of the sync engine with the new checkbox value." +"private fun accountStateReducer( state: AccountSettingsFragmentState, action: AccountSettingsFragmentAction, ): AccountSettingsFragmentState { return when (action) { is AccountSettingsFragmentAction.SyncFailed -> state.copy(lastSyncedDate = LastSyncTime.Failed(action.time)) is AccountSettingsFragmentAction.SyncEnded -> state.copy(lastSyncedDate = LastSyncTime.Success(action.time)) is AccountSettingsFragmentAction.UpdateDeviceName -> state.copy(deviceName = action.name) } }" The SearchState Reducer. +sealed class AccountSettingsFragmentAction : Action { data class SyncFailed(val time: Long) : AccountSettingsFragmentAction() data class SyncEnded(val time: Long) : AccountSettingsFragmentAction() data class UpdateDeviceName(val name: String) : AccountSettingsFragmentAction() } Actions to dispatch through the `SearchStore` to modify `SearchState` through the reducer. +"data class AccountSettingsFragmentState( val lastSyncedDate: LastSyncTime = LastSyncTime.Never, val deviceName: String = """", ) : State" The state for the Account Settings Screen +fun onCancelButtonClicked() "Navigates back to the credit card preference settings. Called when a user taps on the  ""Cancel"" button." +fun onDeleteCardButtonClicked(guid: String) "Deletes the provided credit card in the credit card storage. Called when a user taps on the delete menu item or ""Delete card"" button." +fun onSaveCreditCard(creditCardFields: NewCreditCardFields) "Saves the provided credit card field into the credit card storage. Called when a user taps on the save menu item or ""Save"" button." +"fun onUpdateCreditCard(guid: String, creditCardFields: UpdatableCreditCardFields) }" "Updates the provided credit card with the new credit card fields. Called when a user taps on the save menu item or ""Save"" button when editing an existing credit card." +"class DefaultCreditCardEditorInteractor( private val controller: CreditCardEditorController, ) : CreditCardEditorInteractor { }" The default implementation of [CreditCardEditorInteractor]. +fun onSelectCreditCard(creditCard: CreditCard) Navigates to the credit card editor to edit the selected credit card. Called when a user taps on a credit card item. +fun onAddCreditCardClick() } Navigates to the credit card editor to add a new credit card. Called when a user taps on 'Add credit card' button. +"class DefaultCreditCardsManagementInteractor(private val controller: CreditCardsManagementController,) : CreditCardsManagementInteractor {override fun onSelectCreditCard(creditCard: CreditCard) { controller.handleCreditCardClicked(creditCard) CreditCards.managementCardTapped.record(NoExtras()) } override fun onAddCreditCardClick() { controller.handleAddCreditCardClicked() CreditCards.managementAddTapped.record(NoExtras()) } }" The default implementation of [CreditCardsManagementInteractor]. +"fun bind(state: CreditCardEditorState) { if (state.isEditing) { binding.deleteButton.apply { visibility = View.VISIBLE setOnClickListener { interactor.onDeleteCardButtonClicked(state.guid) } } } binding.cancelButton.setOnClickListener { interactor.onCancelButtonClicked() } binding.saveButton.setOnClickListener { saveCreditCard(state) } binding.cardNumberInput.text = state.cardNumber.toEditable() binding.nameOnCardInput.text = state.billingName.toEditable() binding.cardNumberLayout.setErrorTextColor( ColorStateList.valueOf( binding.root.context.getColorFromAttr(R.attr.textWarning), ), ) binding.nameOnCardLayout.setErrorTextColor( ColorStateList.valueOf( binding.root.context.getColorFromAttr(R.attr.textWarning), ), ) bindExpiryMonthDropDown(state.expiryMonth) bindExpiryYearDropDown(state.expiryYears) }" Binds the given [CreditCardEditorState] in the [CreditCardEditorFragment]. +"internal fun saveCreditCard(state: CreditCardEditorState) { binding.root.hideKeyboard() if (validateForm()) { val cardNumber = binding.cardNumberInput.text.toString().toCreditCardNumber() if (state.isEditing) { val fields = UpdatableCreditCardFields( billingName = binding.nameOnCardInput.text.toString(), cardNumber = CreditCardNumber.Plaintext(cardNumber), cardNumberLast4 = cardNumber.last4Digits(), expiryMonth = (binding.expiryMonthDropDown.selectedItemPosition + 1).toLong(), expiryYear = binding.expiryYearDropDown.selectedItem.toString().toLong(), cardType = cardNumber.creditCardIIN()?.creditCardIssuerNetwork?.name ?: """", ) interactor.onUpdateCreditCard(state.guid, fields) } else { val fields = NewCreditCardFields( billingName = binding.nameOnCardInput.text.toString(), plaintextCardNumber = CreditCardNumber.Plaintext(cardNumber), cardNumberLast4 = cardNumber.last4Digits(), expiryMonth = (binding.expiryMonthDropDown.selectedItemPosition + 1).toLong(), expiryYear = binding.expiryYearDropDown.selectedItem.toString().toLong(), cardType = cardNumber.creditCardIIN()?.creditCardIssuerNetwork?.name ?: """", ) interactor.onSaveCreditCard(fields) } } }" Saves a new credit card or updates an existing one with data from the user input. +@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) internal fun validateForm(): Boolean { var isValid = true if (binding.cardNumberInput.text.toString().validateCreditCardNumber()) { binding.cardNumberLayout.error = null binding.cardNumberTitle.setTextColor(binding.root.context.getColorFromAttr(R.attr.textPrimary)) } else { isValid = false binding.cardNumberLayout.error = binding.root.context.getString(R.string.credit_cards_number_validation_error_message) binding.cardNumberTitle.setTextColor(binding.root.context.getColorFromAttr(R.attr.textWarning)) } if (binding.nameOnCardInput.text.toString().isNotBlank()) { binding.nameOnCardLayout.error = null binding.nameOnCardTitle.setTextColor(binding.root.context.getColorFromAttr(R.attr.textPrimary)) } else { isValid = false binding.nameOnCardLayout.error = binding.root.context.getString(R.string.credit_cards_name_on_card_validation_error_message) binding.nameOnCardTitle.setTextColor(binding.root.context.getColorFromAttr(R.attr.textWarning)) } return isValid } Validates the credit card information entered by the user. +"private fun bindExpiryMonthDropDown(expiryMonth: Int) { val adapter = ArrayAdapter( binding.root.context, android.R.layout.simple_spinner_dropdown_item, ) val dateFormat = SimpleDateFormat(""MMMM (MM)"", Locale.getDefault()) val calendar = Calendar.getInstance() calendar.set(Calendar.DAY_OF_MONTH, 1) for (month in 0..NUMBER_OF_MONTHS) { calendar.set(Calendar.MONTH, month) adapter.add(dateFormat.format(calendar.time)) } binding.expiryMonthDropDown.adapter = adapter binding.expiryMonthDropDown.setSelection(expiryMonth - 1) }" "Setup the expiry month dropdown by formatting and populating it with the months in a calendar year, and set the selection to the provided expiry month." +"private fun bindExpiryYearDropDown(expiryYears: Pair) { val adapter = ArrayAdapter( binding.root.context, android.R.layout.simple_spinner_dropdown_item, ) val (startYear, endYear) = expiryYears for (year in startYear until endYear) { adapter.add(year.toString()) } binding.expiryYearDropDown.adapter = adapter }" Setup the expiry year dropdown with the range specified by the provided expiryYears +"private fun bindCreditCardExpiryDate( creditCard: CreditCard, binding: CreditCardListItemBinding, ) { val dateFormat = SimpleDateFormat(DATE_PATTERN, Locale.getDefault()) val calendar = Calendar.getInstance() calendar.set(Calendar.DAY_OF_MONTH, 1) // Subtract 1 from the expiry month since Calendar.Month is based on a 0-indexed. calendar.set(Calendar.MONTH, creditCard.expiryMonth.toInt() - 1) calendar.set(Calendar.YEAR, creditCard.expiryYear.toInt()) binding.expiryDate.text = dateFormat.format(calendar.time) }" Set the credit card expiry date formatted according to the locale. +"class CreditCardsAdapter( private val interactor: CreditCardsManagementInteractor, ) : ListAdapter(DiffCallback) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CreditCardItemViewHolder { val view = LayoutInflater.from(parent.context) .inflate(CreditCardItemViewHolder.LAYOUT_ID, parent, false) return CreditCardItemViewHolder(view, interactor) } override fun onBindViewHolder(holder: CreditCardItemViewHolder, position: Int) { holder.bind(getItem(position)) } internal object DiffCallback : DiffUtil.ItemCallback() { override fun areItemsTheSame(oldItem: CreditCard, newItem: CreditCard) = oldItem.guid == newItem.guid override fun areContentsTheSame(oldItem: CreditCard, newItem: CreditCard) = oldItem == newItem } }" Adapter for a list of credit cards to be displayed. +Updates the display of the credit cards based on the given [AutofillFragmentState]. fun update(state: AutofillFragmentState) { binding.progressBar.isVisible = state.isLoading binding.creditCardsList.isVisible = state.creditCards.isNotEmpty() creditCardsAdapter.submitList(state.creditCards) } +"suspend fun CreditCard.toCreditCardEditorState(storage: AutofillCreditCardsAddressesStorage): CreditCardEditorState { val crypto = storage.getCreditCardCrypto() val key = crypto.getOrGenerateKey() val cardNumber = crypto.decrypt(key, encryptedCardNumber)?.number ?: """" val startYear = expiryYear.toInt() val endYear = startYear + NUMBER_OF_YEARS_TO_SHOW return CreditCardEditorState( guid = guid, billingName = billingName, cardNumber = cardNumber, expiryMonth = expiryMonth.toInt(), expiryYears = Pair(startYear, endYear), isEditing = true, ) }" Returns a [CreditCardEditorState] from the given [CreditCard]. +"fun getInitialCreditCardEditorState(): CreditCardEditorState { val calendar = Calendar.getInstance() val startYear = calendar.get(Calendar.YEAR) val endYear = startYear + NUMBER_OF_YEARS_TO_SHOW return CreditCardEditorState( expiryYears = Pair(startYear, endYear), ) }" Returns the initial credit editor state if no credit card is provided. +"override fun onPause() { // Don't redirect if the user is navigating to the credit card editor fragment. redirectToReAuth( listOf(R.id.creditCardEditorFragment), findNavController().currentDestination?.id, R.id.creditCardsManagementFragment, ) super.onPause() }" "When the fragment is paused, navigate back to the settings page to reauthenticate." +private fun loadCreditCards() { lifecycleScope.launch(Dispatchers.IO) { val creditCards = requireContext().components.core.autofillStorage.getAllCreditCards() lifecycleScope.launch(Dispatchers.Main) { store.dispatch(AutofillAction.UpdateCreditCards(creditCards)) } } } Fetches all the credit cards from the autofill storage and updates the [AutofillFragmentStore] with the list of credit cards. +fun String.toCreditCardNumber(): String { return this.filter { it.isDigit() } } Strips characters other than digits from a string. Used to strip a credit card number user input of spaces and separators. +fun String.last4Digits(): String { return this.takeLast(LAST_VISIBLE_DIGITS_COUNT) } Returns the last 4 digits from a formatted credit card number string. +fun String.validateCreditCardNumber(): Boolean { val creditCardNumber = this.toCreditCardNumber() if (creditCardNumber != this || creditCardNumber.creditCardIIN() == null) { return false } return luhnAlgorithmValidation(creditCardNumber) } "Returns true if the provided string is a valid credit card by checking if it has a matching credit card issuer network passes the Luhn Algorithm, and false otherwise." +"@Suppress(""MagicNumber"") @VisibleForTesting internal fun luhnAlgorithmValidation(creditCardNumber: String): Boolean { var checksum = 0 val reversedCardNumber = creditCardNumber.reversed() for (index in reversedCardNumber.indices) { val digit = Character.getNumericValue(reversedCardNumber[index]) checksum += if (index % 2 == 0) digit else (digit * 2).let { (it / 10) + (it % 10) } } return (checksum % 10) == 0 }" Implementation of Luhn Algorithm validation (https://en.wikipedia.org/wiki/Luhn_algorithm) +"fun bind(item: History.Metadata, isPendingDeletion: Boolean) { binding.historyLayout.isVisible = !isPendingDeletion binding.historyLayout.titleView.text = item.title binding.historyLayout.urlView.text = item.url binding.historyLayout.setSelectionInteractor(item, selectionHolder, interactor) binding.historyLayout.changeSelected(item in selectionHolder.selectedItems) if (this.item?.url != item.url) { binding.historyLayout.loadFavicon(item.url) } if (selectionHolder.selectedItems.isEmpty()) { binding.historyLayout.overflowView.showAndEnable() } else { binding.historyLayout.overflowView.hideAndDisable() } this.item = item }" Displays the data of the given history record. +fun onShareMenuItem(items: Set) "Opens the share sheet for a set of history [items]. Called when a user clicks on the ""Share"" menu item." +fun onDeleteAllConfirmed() Called when a user has confirmed the deletion of the group. +fun onDeleteAll() "Called when a user clicks on the ""Delete history"" menu item." +fun onDelete(items: Set) "Deletes the given set of history metadata [items]. Called when a user clicks on the ""Delete"" menu item or the ""x"" button associated with a history metadata item." +fun onBackPressed(items: Set): Boolean Called on backpressed to deselect all the given [items]. +fun handleDeleteAllConfirmed() Deletes history metadata items in this group. +fun handleDeleteAll() Displays a [DeleteAllConfirmationDialogFragment] prompt. +fun handleDelete(items: Set) Deletes the given history metadata [items] from storage. +fun handleShare(items: Set) Opens the share sheet for a set of history [items]. +fun handleBackPressed(items: Set): Boolean Called on backpressed to deselect all the given [items]. +fun handleDeselect(item: History.Metadata) Toggles the given history [item] to be deselected in multi-select mode. +fun handleSelect(item: History.Metadata) Toggles the given history [item] to be selected in multi-select mode. +fun handleOpen(item: History.Metadata) Opens the given history [item] in a new tab. +"private fun nimbusBranchesFragmentStateReducer( state: NimbusBranchesState, action: NimbusBranchesAction, ): NimbusBranchesState { return when (action) { is NimbusBranchesAction.UpdateBranches -> { state.copy( branches = action.branches, selectedBranch = action.selectedBranch, isLoading = false, ) } is NimbusBranchesAction.UpdateSelectedBranch -> { state.copy(selectedBranch = action.selectedBranch) } is NimbusBranchesAction.UpdateUnselectBranch -> { state.copy(selectedBranch = """") } } }" Reduces the Nimbus branches state from the current state with the provided [action] to be performed. +private fun getCFRToShow(): Result { var result: Result = Result.None val count = recyclerView.adapter?.itemCount ?: return result for (index in count downTo 0) { val viewHolder = recyclerView.findViewHolderForAdapterPosition(index) if (context.settings().showSyncCFR && viewHolder is RecentSyncedTabViewHolder) { result = Result.SyncedTab(view = viewHolder.composeView) break } else if (context.settings().shouldShowJumpBackInCFR && viewHolder is RecentTabsHeaderViewHolder ) { result = Result.JumpBackIn(view = viewHolder.composeView) } } return result } Returns a [Result] that indicates the CFR that should be shown on the Home screen if any based on the views available and the preferences. +"@Composable fun NotificationPermissionDialogScreen( onDismiss: () -> Unit, grantNotificationPermission: () -> Unit, ) { NotificationPermissionContent( notificationPermissionPageState = NotificationPageState, onDismiss = { onDismiss() Onboarding.notifPppCloseClick.record(NoExtras()) }, onPrimaryButtonClick = { grantNotificationPermission() Onboarding.notifPppPositiveBtnClick.record(NoExtras()) }, onSecondaryButtonClick = { onDismiss() Onboarding.notifPppNegativeBtnClick.record(NoExtras()) }, ) }" A screen for displaying notification pre permission prompt. +"private data class NotificationPermissionPageState( @DrawableRes val image: Int, @StringRes val title: Int, @StringRes val description: Int, @StringRes val primaryButtonText: Int, @StringRes val secondaryButtonText: Int? = null, val onRecordImpressionEvent: () -> Unit, )" Model containing data for the [NotificationPermissionPage]. +fun onTextChanged(text: String) Called whenever the text inside the [ToolbarView] changes +fun onEditingCanceled() Called when a user removes focus from the [ToolbarView] +"fun onUrlCommitted(url: String, fromHomeScreen: Boolean = false)" Called when a user hits the return key while [ToolbarView] has focus. +fun onSearchEngineSuggestionSelected(searchEngine: SearchEngine) Called whenever search engine suggestion is tapped +fun onSearchShortcutsButtonClicked() Called whenever the Shortcuts button is clicked +fun onExistingSessionSelected(tabId: String) Called whenever an existing session is selected from the sessionSuggestionProvider +fun onClickSearchEngineSettings() "Called whenever the ""Search Engine Settings"" item is tapped" +fun onSearchShortcutEngineSelected(searchEngine: SearchEngine) Called whenever a search engine shortcut is tapped @param searchEngine the searchEngine that was selected +fun onSearchTermsTapped(searchTerms: String) Called whenever a search engine suggestion is tapped +"fun onUrlTapped(url: String, flags: LoadUrlFlags = LoadUrlFlags.none())" Called whenever a suggestion containing a URL is tapped +fun deselect(item: T) Called when a selected item is tapped in selection mode and should no longer be selected. +fun select(item: T) "Called when an item is long pressed and selection mode is started, or when selection mode has already started an an item is tapped." +fun open(item: T) Called when an item is tapped to open it. +fun onAutoplayChanged(value: AutoplayValue) Indicates the user changed the status of a an autoplay permission. +fun onPermissionToggled(permissionState: WebsitePermission) Indicates the user changed the status of a certain website permission. +fun onPermissionsShown() "Indicates there are website permissions allowed / blocked for the current website. which, status which is shown to the user." +fun handleClearSiteDataClicked(baseDomain: String) Clears site data for the current website. Called when a user clicks on the section to clear site data. +fun handleConnectionDetailsClicked() "Navigates to the connection details. Called when a user clicks on the ""Secured or Insecure Connection"" section." +fun handleTrackingProtectionDetailsClicked() Navigates to the tracking protection details panel. +fun handleCookieBannerHandlingDetailsClicked() Navigates to the cookie banners details panel. +fun handleAndroidPermissionGranted(feature: PhoneFeature) Handles a certain set of Android permissions being explicitly granted by the user. +fun handleAutoplayChanged(autoplayValue: AutoplayValue) Handles change a [WebsitePermission.Autoplay]. +fun handlePermissionToggled(permission: WebsitePermission) Handles toggling a [WebsitePermission]. +fun handlePermissionsShown() Handles the case of the [WebsitePermissionsView] needed to be displayed to the user. +"class ConnectionDetailsInteractor( private val controller: ConnectionDetailsController, ) : WebSiteInfoInteractor {  override fun onBackPressed() { controller.handleBackPressed() } }" "[ConnectionPanelDialogFragment] interactor. Implements callbacks for each of [ConnectionPanelDialogFragment]'s Views declared possible user interactions, delegates all such user events to the [ConnectionDetailsController]." +fun onTrackingProtectionDetailsClicked() "Navigates to the tracking protection preferences. Called when a user clicks on the ""Details"" button." +fun onCookieBannerHandlingDetailsClicked() Navigates to the tracking protection details panel. +fun onTrackingProtectionToggled(isEnabled: Boolean) Called whenever the tracking protection toggle for this site is toggled. +"class DefaultCookieBannerDetailsInteractor( private val controller: CookieBannerDetailsController, ) : CookieBannerDetailsInteractor { override fun onBackPressed() { controller.handleBackPressed() } override fun onTogglePressed(vale: Boolean) { controller.handleTogglePressed(vale) } }" "CookieBannerPanelDialogFragment] interactor. Implements callbacks for each of [CookieBannerPanelDialogFragment]'s Views declared possible user interactions, delegates all such user events to the [CookieBannerDetailsController]." +interface CookieBannerDetailsInteractor { Called whenever back is pressed. fun onBackPressed() = Unit Called whenever the user press the toggle widget. fun onTogglePressed(vale: Boolean) = Unit } Contract declaring all possible user interactions with [CookieBannerHandlingDetailsView]. +"data class CookieBannerDialogVariant( val title: String, val message: String, val positiveTextButton: String, ) }" Data class for cookie banner dialog variant +"fun tryToShowReEngagementDialog( settings: Settings, status: CookieBannerHandlingStatus, navController: NavController, ) { if (status == CookieBannerHandlingStatus.DETECTED && settings.shouldCookieBannerReEngagementDialog() ) { settings.lastInteractionWithReEngageCookieBannerDialogInMs = System.currentTimeMillis() settings.cookieBannerDetectedPreviously = true val directions = BrowserFragmentDirections.actionBrowserFragmentToCookieBannerDialogFragment() navController.nav(R.id.browserFragment, directions) } }" "Tries to show the re-engagement cookie banner dialog, when the right conditions are met, o otherwise the dialog won't show." +"fun PhoneFeature.isUserPermissionGranted( sitePermissions: SitePermissions?, settings: Settings, ) = getStatus(sitePermissions, settings) == SitePermissions.Status.ALLOWED" Common [PhoneFeature] extensions used for **quicksettings**. Whether the website permission associated with this [PhoneFeature] was specifically allowed by the user.  To check whether the needed Android permission is also allowed [PhoneFeature#isAndroidPermissionGranted()] can be used. +"fun PhoneFeature.shouldBeEnabled( context: Context, sitePermissions: SitePermissions?, settings: Settings, ) = isAndroidPermissionGranted(context) && isUserPermissionGranted(sitePermissions, settings)" Common [PhoneFeature] extensions used for **quicksettings**. Whether the website permission associated with this [PhoneFeature] should allow user interaction. +"fun PhoneFeature.shouldBeVisible( sitePermissions: SitePermissions?, settings: Settings, ): Boolean { // We have to check if the site have a site permission exception, // if it doesn't the feature shouldn't be visible return if (sitePermissions == null) { false } else { getStatus(sitePermissions, settings) != SitePermissions.Status.NO_DECISION } }" Common [PhoneFeature] extensions used for **quicksettings**. Whether the website permission associated with this [PhoneFeature] should be shown to the user. +fun onPermissionsShown() "Indicates there are website permissions allowed / blocked for the current website. which, status which is shown to the user." +fun handleClearSiteDataClicked(baseDomain: String) Clears site data for the current website. Called when a user clicks on the section to clear site data. +fun handleConnectionDetailsClicked() "Navigates to the connection details. Called when a user clicks on the ""Secured or Insecure Connection"" section." +fun handleTrackingProtectionDetailsClicked() Navigates to the tracking protection details panel. +fun handleCookieBannerHandlingDetailsClicked() Navigates to the cookie banners details panel. +fun handleAndroidPermissionGranted(feature: PhoneFeature) Handles a certain set of Android permissions being explicitly granted by the user. +fun handleAutoplayChanged(autoplayValue: AutoplayValue) Handles change a [WebsitePermission.Autoplay]. +fun handlePermissionToggled(permission: WebsitePermission) Handles toggling a [WebsitePermission]. +fun handlePermissionsShown() Handles the case of the [WebsitePermissionsView] needed to be displayed to the user. +"class ConnectionDetailsInteractor( private val controller: ConnectionDetailsController, ) : WebSiteInfoInteractor {  override fun onBackPressed() { controller.handleBackPressed() } }" "[ConnectionPanelDialogFragment] interactor. Implements callbacks for each of [ConnectionPanelDialogFragment]'s Views declared possible user interactions, delegates all such user events to the [ConnectionDetailsController]." +fun onTrackingProtectionDetailsClicked() "Navigates to the tracking protection preferences. Called when a user clicks on the ""Details"" button." +fun onCookieBannerHandlingDetailsClicked() Navigates to the tracking protection details panel. +fun onTrackingProtectionToggled(isEnabled: Boolean) Called whenever the tracking protection toggle for this site is toggled. +"class DefaultCookieBannerDetailsInteractor( private val controller: CookieBannerDetailsController, ) : CookieBannerDetailsInteractor { override fun onBackPressed() { controller.handleBackPressed() } override fun onTogglePressed(vale: Boolean) { controller.handleTogglePressed(vale) } }" "CookieBannerPanelDialogFragment] interactor. Implements callbacks for each of [CookieBannerPanelDialogFragment]'s Views declared possible user interactions, delegates all such user events to the [CookieBannerDetailsController]." +interface CookieBannerDetailsInteractor { Called whenever back is pressed. fun onBackPressed() = Unit Called whenever the user press the toggle widget. fun onTogglePressed(vale: Boolean) = Unit } Contract declaring all possible user interactions with [CookieBannerHandlingDetailsView]. +"data class CookieBannerDialogVariant( val title: String, val message: String, val positiveTextButton: String, ) }" Data class for cookie banner dialog variant +"fun tryToShowReEngagementDialog( settings: Settings, status: CookieBannerHandlingStatus, navController: NavController, ) { if (status == CookieBannerHandlingStatus.DETECTED && settings.shouldCookieBannerReEngagementDialog() ) { settings.lastInteractionWithReEngageCookieBannerDialogInMs = System.currentTimeMillis() settings.cookieBannerDetectedPreviously = true val directions = BrowserFragmentDirections.actionBrowserFragmentToCookieBannerDialogFragment() navController.nav(R.id.browserFragment, directions) } }" "Tries to show the re-engagement cookie banner dialog, when the right conditions are met, o otherwise the dialog won't show." +"fun PhoneFeature.isUserPermissionGranted( sitePermissions: SitePermissions?, settings: Settings, ) = getStatus(sitePermissions, settings) == SitePermissions.Status.ALLOWED" Common [PhoneFeature] extensions used for **quicksettings**. Whether the website permission associated with this [PhoneFeature] was specifically allowed by the user.  To check whether the needed Android permission is also allowed [PhoneFeature#isAndroidPermissionGranted()] can be used. +"fun PhoneFeature.shouldBeEnabled( context: Context, sitePermissions: SitePermissions?, settings: Settings, ) = isAndroidPermissionGranted(context) && isUserPermissionGranted(sitePermissions, settings)" Common [PhoneFeature] extensions used for **quicksettings**. Whether the website permission associated with this [PhoneFeature] should allow user interaction. +"fun PhoneFeature.shouldBeVisible( sitePermissions: SitePermissions?, settings: Settings, ): Boolean { // We have to check if the site have a site permission exception, // if it doesn't the feature shouldn't be visible return if (sitePermissions == null) { false } else { getStatus(sitePermissions, settings) != SitePermissions.Status.NO_DECISION } }" Common [PhoneFeature] extensions used for **quicksettings**. Whether the website permission associated with this [PhoneFeature] should be shown to the user. +"private fun filterItems( searchedForText: String?, sortingStrategy: SortingStrategy, state: LoginsListState, ): LoginsListState { return if (searchedForText.isNullOrBlank()) { state.copy( isLoading = false, sortingStrategy = sortingStrategy, highlightedItem = sortingStrategyToMenuItem(sortingStrategy), searchedForText = searchedForText, filteredItems = sortingStrategy(state.loginList), ) } else { state.copy( isLoading = false, sortingStrategy = sortingStrategy, highlightedItem = sortingStrategyToMenuItem(sortingStrategy), searchedForText = searchedForText, filteredItems = sortingStrategy(state.loginList).filter { it.origin.contains( searchedForText, ) }, ) } }"  [LoginsListState] containing a new [LoginsListState.filteredItems] with filtered [LoginsListState.items] +"private fun savedLoginsStateReducer( state: LoginsListState, action: LoginsAction, ): LoginsListState { return when (action) { is LoginsAction.LoginsListUpToDate -> { state.copy(isLoading = false) } is LoginsAction.UpdateLoginsList -> { state.copy( isLoading = false, loginList = action.list, filteredItems = state.sortingStrategy(action.list), ) } is LoginsAction.FilterLogins -> { filterItems( action.newText, state.sortingStrategy, state, ) } is LoginsAction.UpdateCurrentLogin -> { state.copy( currentItem = action.item, ) } is LoginsAction.SortLogins -> { filterItems( state.searchedForText, action.sortingStrategy, state, ) } is LoginsAction.LoginSelected -> { state.copy( isLoading = true, ) } is LoginsAction.DuplicateLogin -> { state.copy( duplicateLogin = action.dupe, ) } } }" "Handles changes in the saved logins list, including updates and filtering." +"data class LoginsListState( val isLoading: Boolean = false, val loginList: List, val filteredItems: List, val currentItem: SavedLogin? = null, val searchedForText: String?, val sortingStrategy: SortingStrategy, val highlightedItem: SavedLoginsSortingStrategyMenu.Item, val duplicateLogin: SavedLogin? = null, ) : State fun createInitialLoginsListState(settings: Settings) = LoginsListState( isLoading = true, loginList = emptyList(), filteredItems = emptyList(), searchedForText = null, sortingStrategy = settings.savedLoginsSortingStrategy, highlightedItem = settings.savedLoginsMenuHighlightedItem, )" View that contains and configures the Login Details +"class SavedLoginsInteractor( private val loginsListController: LoginsListController, private val savedLoginsStorageController: SavedLoginsStorageController, ) { fun onItemClicked(item: SavedLogin) { loginsListController.handleItemClicked(item) } fun onLearnMoreClicked() { loginsListController.handleLearnMoreClicked() } fun onSortingStrategyChanged(sortingStrategy: SortingStrategy) { loginsListController.handleSort(sortingStrategy) } fun loadAndMapLogins() { savedLoginsStorageController.handleLoadAndMapLogins() } fun onAddLoginClick() { loginsListController.handleAddLoginClicked() } }" Interactor for the saved logins screen +"class LoginDetailInteractor( private val savedLoginsController: SavedLoginsStorageController, ) { fun onFetchLoginList(loginId: String) { savedLoginsController.fetchLoginDetails(loginId) } fun onDeleteLogin(loginId: String) { savedLoginsController.delete(loginId) } }" Interactor for the login detail screen +"class EditLoginInteractor( private val savedLoginsController: SavedLoginsStorageController, ) { fun findDuplicate(loginId: String, usernameText: String, passwordText: String) { savedLoginsController.findDuplicateForSave(loginId, usernameText, passwordText) } fun onSaveLogin(loginId: String, usernameText: String, passwordText: String) { savedLoginsController.save(loginId, usernameText, passwordText) } }" Interactor for the edit login screen +"class AddLoginInteractor( private val savedLoginsController: SavedLoginsStorageController, ) { fun findDuplicate(originText: String, usernameText: String, passwordText: String) { savedLoginsController.findDuplicateForAdd(originText, usernameText, passwordText) } fun onAddLogin(originText: String, usernameText: String, passwordText: String) { savedLoginsController.add(originText, usernameText, passwordText) } }" Interactor for the add login screen +"@Composable private fun PlaceHolderTabIcon(modifier: Modifier) { Box( modifier = modifier.background( color = when (isSystemInDarkTheme()) { true -> PhotonColors.DarkGrey60 false -> PhotonColors.LightGrey30 }, ), ) }" A placeholder for the recent tab icon. +"@Composable private fun RecentTabIcon( url: String, modifier: Modifier = Modifier, contentScale: ContentScale = ContentScale.Fit, alignment: Alignment = Alignment.Center, icon: Bitmap? = null, ) { when { icon != null -> { Image( painter = BitmapPainter(icon.asImageBitmap()), contentDescription = null, modifier = modifier, contentScale = contentScale, alignment = alignment, ) } !inComposePreview -> { components.core.icons.Loader(url) { Placeholder { PlaceHolderTabIcon(modifier) } WithIcon { icon -> Image( painter = icon.painter, contentDescription = null, modifier = modifier, contentScale = contentScale, ) } } } else -> { PlaceHolderTabIcon(modifier) } } }" A recent tab icon. +"@OptIn(ExperimentalComposeUiApi::class) @Composable private fun RecentTabMenu( showMenu: Boolean, menuItems: List, tab: RecentTab.Tab, onDismissRequest: () -> Unit, ) { DisposableEffect(LocalConfiguration.current.orientation) { onDispose { onDismissRequest() } } DropdownMenu( expanded = showMenu, onDismissRequest = { onDismissRequest() }, modifier = Modifier .background(color = FirefoxTheme.colors.layer2) .semantics { testTagsAsResourceId = true testTag = ""recent.tab.menu"" }, ) { for (item in menuItems) { DropdownMenuItem( onClick = { onDismissRequest() item.onClick(tab) }, ) { Text( text = item.title, color = FirefoxTheme.colors.textPrimary, maxLines = 1, modifier = Modifier .fillMaxHeight() .align(Alignment.CenterVertically), ) } } } }" Menu shown for a [RecentTab.Tab]. +"@Composable fun RecentTabImage( tab: RecentTab.Tab, modifier: Modifier = Modifier, contentScale: ContentScale = ContentScale.FillWidth, ) { val previewImageUrl = tab.state.content.previewImageUrl when { !previewImageUrl.isNullOrEmpty() -> { Image( url = previewImageUrl, modifier = modifier, targetSize = 108.dp, contentScale = ContentScale.Crop, ) } else -> ThumbnailCard( url = tab.state.content.url, key = tab.state.id, modifier = modifier, contentScale = contentScale, ) } }" A recent tab image. +"@OptIn( ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class, ) @Composable @Suppress(""LongMethod"") private fun RecentTabItem( tab: RecentTab.Tab, menuItems: List, backgroundColor: Color, onRecentTabClick: (String) -> Unit = {}, ) { var isMenuExpanded by remember { mutableStateOf(false) } Card( modifier = Modifier .fillMaxWidth() .height(112.dp) .combinedClickable( enabled = true, onClick = { onRecentTabClick(tab.state.id) }, onLongClick = { isMenuExpanded = true }, ), shape = RoundedCornerShape(8.dp), backgroundColor = backgroundColor, elevation = 6.dp, ) { Row( modifier = Modifier.padding(16.dp), ) { RecentTabImage( tab = tab, modifier = Modifier .size(108.dp, 80.dp) .clip(RoundedCornerShape(8.dp)), contentScale = ContentScale.Crop, ) Spacer(modifier = Modifier.width(16.dp)) Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.SpaceBetween, ) { Text( text = tab.state.content.title.ifEmpty { tab.state.content.url.trimmed() }, modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""recent.tab.title"" }, color = FirefoxTheme.colors.textPrimary, fontSize = 14.sp, maxLines = 2, overflow = TextOverflow.Ellipsis, ) Row { RecentTabIcon( url = tab.state.content.url, modifier = Modifier .size(18.dp) .clip(RoundedCornerShape(2.dp)), contentScale = ContentScale.Crop, icon = tab.state.content.icon, ) Spacer(modifier = Modifier.width(8.dp)) Text( text = tab.state.content.url.trimmed(), modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""recent.tab.url"" }, color = FirefoxTheme.colors.textSecondary, fontSize = 12.sp, overflow = TextOverflow.Ellipsis, maxLines = 1, ) } } RecentTabMenu( showMenu = isMenuExpanded, menuItems = menuItems, tab = tab, onDismissRequest = { isMenuExpanded = false }, ) } } }" A recent tab item. +"fun TextView.setOnboardingIcon(@DrawableRes id: Int) { val icon = context.getDrawableWithTint(id, context.getColorFromAttr(R.attr.iconActive))?.apply { val size = context.resources.getDimensionPixelSize(R.dimen.onboarding_header_icon_height_width) setBounds(size) } putCompoundDrawablesRelative(start = icon) }" Sets the drawableStart of a header in an onboarding card. +"@VisibleForTesting internal fun restoreSelectedCategories( coroutineScope: CoroutineScope, currentCategories: List, store: Store, selectedPocketCategoriesDataStore: DataStore, ) { coroutineScope.launch { store.dispatch( AppAction.PocketStoriesCategoriesSelectionsChange( currentCategories, selectedPocketCategoriesDataStore.data.first() .valuesList.map { PocketRecommendedStoriesSelectedCategory( name = it.name, selectionTimestamp = it.selectionTimestamp, ) }, ), ) } }" Combines [currentCategories] with the locally persisted data about previously selected categories and emits a new [AppAction.PocketStoriesCategoriesSelectionsChange] to update these in store. +"@VisibleForTesting internal fun persistSelectedCategories( coroutineScope: CoroutineScope, currentCategoriesSelections: List, selectedPocketCategoriesDataStore: DataStore, ) { val selectedCategories = currentCategoriesSelections .map { SelectedPocketStoriesCategory.newBuilder().apply { name = it.name selectionTimestamp = it.selectionTimestamp }.build() } // Irrespective of the current selections or their number overwrite everything we had. coroutineScope.launch { selectedPocketCategoriesDataStore.updateData { data -> data.newBuilderForType().addAllValues(selectedCategories).build() } } }" Persist [currentCategoriesSelections] for making this details available in between app restarts. +"private fun bookmarkSearchStateReducer( state: BookmarkSearchFragmentState, action: BookmarkSearchFragmentAction, ): BookmarkSearchFragmentState { return when (action) { is BookmarkSearchFragmentAction.UpdateQuery -> state.copy(query = action.query) } }" The [BookmarkSearchFragmentState] Reducer. +"suspend fun updateMenu(itemType: BookmarkNodeType, itemId: String) { menuController.submitList(menuItems(itemType, itemId)) }" Update the menu items for the type of bookmark. +private fun differentFromSelectedFolder(arguments: Bundle?): Boolean { return arguments != null && BookmarkFragmentArgs.fromBundle(arguments).currentRoot != viewModel.selectedFolder?.guid } Returns true if the currentRoot listed in the [arguments] is different from the current selected folder. +"override fun onDestinationChanged(controller: NavController, destination: NavDestination, arguments: Bundle?) { if (destination.id != R.id.bookmarkFragment || differentFromSelectedFolder(arguments)) { // TODO this is currently called when opening the bookmark menu. Fix this if possible bookmarkInteractor.onAllBookmarksDeselected() } }" Deselects all items when the user navigates to a different fragment or a different folder. +"private fun downloadStateReducer( state: DownloadFragmentState, action: DownloadFragmentAction, ): DownloadFragmentState { return when (action) { is DownloadFragmentAction.AddItemForRemoval -> state.copy(mode = DownloadFragmentState.Mode.Editing(state.mode.selectedItems + action.item)) is DownloadFragmentAction.RemoveItemForRemoval -> { val selected = state.mode.selectedItems - action.item state.copy( mode = if (selected.isEmpty()) { DownloadFragmentState.Mode.Normal } else { DownloadFragmentState.Mode.Editing(selected) }, ) } is DownloadFragmentAction.ExitEditMode -> state.copy(mode = DownloadFragmentState.Mode.Normal) is DownloadFragmentAction.EnterDeletionMode -> state.copy(isDeletingItems = true) is DownloadFragmentAction.ExitDeletionMode -> state.copy(isDeletingItems = false) is DownloadFragmentAction.AddPendingDeletionSet -> state.copy( pendingDeletionIds = state.pendingDeletionIds + action.itemIds, ) is DownloadFragmentAction.UndoPendingDeletionSet -> state.copy( pendingDeletionIds = state.pendingDeletionIds - action.itemIds, ) } }" The DownloadState Reducer. +"private fun deleteDownloadItems(items: Set) { updatePendingDownloadToDelete(items) MainScope().allowUndo( requireActivity().getRootView()!!, getMultiSelectSnackBarMessage(items), getString(R.string.bookmark_undo_deletion), onCancel = { undoPendingDeletion(items) }, operation = getDeleteDownloadItemsOperation(items), ) }" "Schedules [items] for deletion. Note: When tapping on a download item's ""trash"" button (itemView.overflow_menu) this [items].size() will be 1." +"fun History.toPendingDeletionHistory(): PendingDeletionHistory { return when (this) { is History.Regular -> PendingDeletionHistory.Item(visitedAt = visitedAt, url = url) is History.Group -> PendingDeletionHistory.Group( visitedAt = visitedAt, historyMetadata = items.map { historyMetadata -> PendingDeletionHistory.MetaData( historyMetadata.visitedAt, historyMetadata.historyMetadataKey, ) }, ) is History.Metadata -> PendingDeletionHistory.MetaData(visitedAt, historyMetadataKey) } }" Maps an instance of [History] to an instance of [PendingDeletionHistory]. +fun changeSelected(isSelected: Boolean) { binding.icon.displayedChild = if (isSelected) 1 else 0 } Changes the icon to show a check mark if [isSelected] +fun displayAs(mode: ItemType) { urlView.isVisible = mode == ItemType.SITE } Change visibility of parts of this view based on what type of item is being represented. +"private fun recentlyClosedStateReducer( state: RecentlyClosedFragmentState, action: RecentlyClosedFragmentAction, ): RecentlyClosedFragmentState { return when (action) { is RecentlyClosedFragmentAction.Change -> state.copy(items = action.list) is RecentlyClosedFragmentAction.Select -> { state.copy(selectedTabs = state.selectedTabs + action.tab) } is RecentlyClosedFragmentAction.Deselect -> { state.copy(selectedTabs = state.selectedTabs - action.tab) } RecentlyClosedFragmentAction.DeselectAll -> state.copy(selectedTabs = emptySet()) } }" +"private fun historyStateReducer( state: HistoryMetadataGroupFragmentState, action: HistoryMetadataGroupFragmentAction, ): HistoryMetadataGroupFragmentState { return when (action) { is HistoryMetadataGroupFragmentAction.UpdateHistoryItems -> state.copy(items = action.items) is HistoryMetadataGroupFragmentAction.Select -> state.copy( items = state.items.toMutableList() .map { if (it == action.item) { it.copy(selected = true) } else { it } }, ) is HistoryMetadataGroupFragmentAction.Deselect -> state.copy( items = state.items.toMutableList() .map { if (it == action.item) { it.copy(selected = false) } else { it } }, ) is HistoryMetadataGroupFragmentAction.DeselectAll -> state.copy( items = state.items.toMutableList() .map { it.copy(selected = false) }, ) is HistoryMetadataGroupFragmentAction.Delete -> { val items = state.items.toMutableList() items.remove(action.item) state.copy(items = items) } is HistoryMetadataGroupFragmentAction.DeleteAll -> state.copy(items = emptyList()) is HistoryMetadataGroupFragmentAction.UpdatePendingDeletionItems -> state.copy(pendingDeletionItems = action.pendingDeletionItems) is HistoryMetadataGroupFragmentAction.ChangeEmptyState -> state.copy( isEmpty = action.isEmpty, ) }" The RecentlyClosedFragmentState Reducer. +"private fun historyStateReducer( state: HistoryMetadataGroupFragmentState, action: HistoryMetadataGroupFragmentAction, ): HistoryMetadataGroupFragmentState { return when (action) { is HistoryMetadataGroupFragmentAction.UpdateHistoryItems -> state.copy(items = action.items) is HistoryMetadataGroupFragmentAction.Select -> state.copy( items = state.items.toMutableList() .map { if (it == action.item) { it.copy(selected = true) } else { it } }, ) is HistoryMetadataGroupFragmentAction.Deselect -> state.copy( items = state.items.toMutableList() .map { if (it == action.item) { it.copy(selected = false) } else { it } }, ) is HistoryMetadataGroupFragmentAction.DeselectAll -> state.copy( items = state.items.toMutableList() .map { it.copy(selected = false) }, ) is HistoryMetadataGroupFragmentAction.Delete -> { val items = state.items.toMutableList() items.remove(action.item) state.copy(items = items) } is HistoryMetadataGroupFragmentAction.DeleteAll -> state.copy(items = emptyList()) is HistoryMetadataGroupFragmentAction.UpdatePendingDeletionItems -> state.copy(pendingDeletionItems = action.pendingDeletionItems) is HistoryMetadataGroupFragmentAction.ChangeEmptyState -> state.copy( isEmpty = action.isEmpty, ) }" Reduces the history metadata state from the current state with the provided [action] to be performed. +"override fun handleHistoryShowAllClicked() { navController.navigate( HomeFragmentDirections.actionGlobalHistoryFragment(), ) }" Shows the history fragment. +"override fun handleRecentHistoryGroupClicked(recentHistoryGroup: RecentHistoryGroup) { navController.navigate( HomeFragmentDirections.actionGlobalHistoryMetadataGroup( title = recentHistoryGroup.title, historyMetadataItems = recentHistoryGroup.historyMetadata .mapIndexed { index, item -> item.toHistoryMetadata(index) }.toTypedArray(), ), ) }" Navigates to the history metadata group fragment to display the group. +"override fun handleRemoveRecentHistoryGroup(groupTitle: String) { // We want to update the UI right away in response to user action without waiting for the IO. // First, dispatch actions that will clean up search groups in the two stores that have // metadata-related state. store.dispatch(HistoryMetadataAction.DisbandSearchGroupAction(searchTerm = groupTitle)) appStore.dispatch(AppAction.DisbandSearchGroupAction(searchTerm = groupTitle)) // Then, perform the expensive IO work of removing search groups from storage. scope.launch { storage.deleteHistoryMetadata(groupTitle) } RecentSearches.groupDeleted.record(NoExtras()) }" Removes a [RecentHistoryGroup] with the given title from the homescreen. +override fun handleRecentHistoryHighlightClicked(recentHistoryHighlight: RecentHistoryHighlight) { selectOrAddTabUseCase.invoke(recentHistoryHighlight.url) navController.navigate(R.id.browserFragment) } Switch to an already open tab for [recentHistoryHighlight] if one exists or create a new tab in which to load this item's URL. +override fun handleRemoveRecentHistoryHighlight(highlightUrl: String) { appStore.dispatch(AppAction.RemoveRecentHistoryHighlight(highlightUrl)) scope.launch { storage.deleteHistoryMetadataForUrl(highlightUrl) } } Removes a [RecentHistoryHighlight] with the given title from the homescreen. +"@OptIn(ExperimentalComposeUiApi::class) @Composable fun RecentlyVisited( recentVisits: List, menuItems: List, backgroundColor: Color = FirefoxTheme.colors.layer2, onRecentVisitClick: (RecentlyVisitedItem, Int) -> Unit = { _, _ -> }, ) { Card( modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(8.dp), backgroundColor = backgroundColor, elevation = 6.dp, ) { val listState = rememberLazyListState() val flingBehavior = EagerFlingBehavior(lazyRowState = listState) LazyRow( modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""recent.visits"" }, state = listState, contentPadding = PaddingValues(16.dp), horizontalArrangement = Arrangement.spacedBy(32.dp), flingBehavior = flingBehavior, ) { val itemsList = recentVisits.chunked(VISITS_PER_COLUMN) itemsIndexed(itemsList) { pageIndex, items -> Column( modifier = Modifier.fillMaxWidth(), ) { items.forEachIndexed { index, recentVisit -> when (recentVisit) { is RecentHistoryHighlight -> RecentlyVisitedHistoryHighlight( recentVisit = recentVisit, menuItems = menuItems, clickableEnabled = listState.atLeastHalfVisibleItems.contains(pageIndex), showDividerLine = index < items.size - 1, onRecentVisitClick = { onRecentVisitClick(it, pageIndex + 1) }, ) is RecentHistoryGroup -> RecentlyVisitedHistoryGroup( recentVisit = recentVisit, menuItems = menuItems, clickableEnabled = listState.atLeastHalfVisibleItems.contains(pageIndex), showDividerLine = index < items.size - 1, onRecentVisitClick = { onRecentVisitClick(it, pageIndex + 1) }, ) } } } } } } }" A list of recently visited items. +"@OptIn( ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class, ) @Composable private fun RecentlyVisitedHistoryGroup( recentVisit: RecentHistoryGroup, menuItems: List, clickableEnabled: Boolean, showDividerLine: Boolean, onRecentVisitClick: (RecentHistoryGroup) -> Unit = { _ -> }, ) { var isMenuExpanded by remember { mutableStateOf(false) } Row( modifier = Modifier .combinedClickable( enabled = clickableEnabled, onClick = { onRecentVisitClick(recentVisit) }, onLongClick = { isMenuExpanded = true }, ) .size(268.dp, 56.dp) .semantics { testTagsAsResourceId = true testTag = ""recent.visits.group"" }, verticalAlignment = Alignment.CenterVertically, ) { Image( painter = painterResource(R.drawable.ic_multiple_tabs), contentDescription = null, modifier = Modifier.size(24.dp), ) Spacer(modifier = Modifier.width(16.dp)) Column( modifier = Modifier.fillMaxSize(), ) { RecentlyVisitedTitle( text = recentVisit.title, modifier = Modifier .padding(top = 7.dp, bottom = 2.dp) .weight(1f) .semantics { testTagsAsResourceId = true testTag = ""recent.visits.group.title"" }, ) RecentlyVisitedCaption( count = recentVisit.historyMetadata.size, modifier = Modifier .weight(1f) .semantics { testTagsAsResourceId = true testTag = ""recent.visits.group.caption"" }, ) if (showDividerLine) { Divider() } } RecentlyVisitedMenu( showMenu = isMenuExpanded, menuItems = menuItems, recentVisit = recentVisit, onDismissRequest = { isMenuExpanded = false }, ) } }" A recently visited history group. +"@OptIn( ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class, ) @Composable private fun RecentlyVisitedHistoryHighlight( recentVisit: RecentHistoryHighlight, menuItems: List, clickableEnabled: Boolean, showDividerLine: Boolean, onRecentVisitClick: (RecentHistoryHighlight) -> Unit = { _ -> }, ) { var isMenuExpanded by remember { mutableStateOf(false) } Row( modifier = Modifier .combinedClickable( enabled = clickableEnabled, onClick = { onRecentVisitClick(recentVisit) }, onLongClick = { isMenuExpanded = true }, ) .size(268.dp, 56.dp) .semantics { testTagsAsResourceId = true testTag = ""recent.visits.highlight"" }, verticalAlignment = Alignment.CenterVertically, ) { Favicon(url = recentVisit.url, size = 24.dp) Spacer(modifier = Modifier.width(16.dp)) Box(modifier = Modifier.fillMaxSize()) { RecentlyVisitedTitle( text = recentVisit.title.trimmed(), modifier = Modifier .align(Alignment.CenterStart) .semantics { testTagsAsResourceId = true testTag = ""recent.visits.highlight.title"" }, ) if (showDividerLine) { Divider(modifier = Modifier.align(Alignment.BottomCenter)) } } RecentlyVisitedMenu( showMenu = isMenuExpanded, menuItems = menuItems, recentVisit = recentVisit, onDismissRequest = { isMenuExpanded = false }, ) } }" A recently visited history item. +"@Composable private fun RecentlyVisitedTitle( text: String, modifier: Modifier = Modifier, ) { Text( text = text, modifier = modifier, color = FirefoxTheme.colors.textPrimary, fontSize = 16.sp, overflow = TextOverflow.Ellipsis, maxLines = 1, ) }" The title of a recent visit. +"@Composable private fun RecentlyVisitedCaption( count: Int, modifier: Modifier, ) { val stringId = if (count == 1) { R.string.history_search_group_site } else { R.string.history_search_group_sites } Text( text = String.format(LocalContext.current.getString(stringId), count), modifier = modifier, color = when (isSystemInDarkTheme()) { true -> FirefoxTheme.colors.textPrimary false -> FirefoxTheme.colors.textSecondary }, fontSize = 12.sp, overflow = TextOverflow.Ellipsis, maxLines = 1, ) }" The caption text for a recent visit. +"@OptIn(ExperimentalComposeUiApi::class) @Composable private fun RecentlyVisitedMenu( showMenu: Boolean, menuItems: List, recentVisit: RecentlyVisitedItem, onDismissRequest: () -> Unit, ) { DisposableEffect(LocalConfiguration.current.orientation) { onDispose { onDismissRequest() } } DropdownMenu( expanded = showMenu, onDismissRequest = { onDismissRequest() }, modifier = Modifier .background(color = FirefoxTheme.colors.layer2) .semantics { testTagsAsResourceId = true testTag = ""recent.visit.menu"" }, ) { for (item in menuItems) { DropdownMenuItem( onClick = { onDismissRequest() item.onClick(recentVisit) }, ) { Text( text = item.title, color = FirefoxTheme.colors.textPrimary, maxLines = 1, modifier = Modifier .fillMaxHeight() .align(Alignment.CenterVertically), ) } } } }" Menu shown for a [RecentlyVisitedItem]. +"private val LazyListState.atLeastHalfVisibleItems get() = layoutInfo .visibleItemsInfo .filter { val startEdge = maxOf(0, layoutInfo.viewportStartOffset - it.offset) val endEdge = maxOf(0, it.offset + it.size - layoutInfo.viewportEndOffset) return@filter startEdge + endEdge < it.size / 2 }.map { it.index }" Get the indexes in list of all items which have more than half showing. +"@VisibleForTesting internal fun getCombinedHistory( historyHighlights: List, historyGroups: List, ): List { // Cleanup highlights now to avoid counting them below and then removing the ones found in groups. val distinctHighlights = historyHighlights .removeHighlightsAlreadyInGroups(historyGroups) val totalItemsCount = distinctHighlights.size + historyGroups.size return if (totalItemsCount <= MAX_RESULTS_TOTAL) { getSortedHistory( distinctHighlights.sortedByDescending { it.lastAccessedTime }, historyGroups.sortedByDescending { it.lastAccessedTime }, ) } else { var groupsCount = 0 var highlightCount = 0 while ((highlightCount + groupsCount) < MAX_RESULTS_TOTAL) { if ((highlightCount + groupsCount) < MAX_RESULTS_TOTAL && distinctHighlights.getOrNull(highlightCount) != null ) { highlightCount += 1 } if ((highlightCount + groupsCount) < MAX_RESULTS_TOTAL && historyGroups.getOrNull(groupsCount) != null ) { groupsCount += 1 } } getSortedHistory( distinctHighlights .sortedByDescending { it.lastAccessedTime } .take(highlightCount), historyGroups .sortedByDescending { it.lastAccessedTime } .take(groupsCount), ) } }" Get up to [MAX_RESULTS_TOTAL] items if available as an even split of history highlights and history groups. If more items then needed are available then highlights will be more by one. +"@VisibleForTesting internal fun getHistoryHighlights( highlights: List, metadata: List, ): List { val highlightsUrls = highlights.map { it.url } val highlightsLastUpdatedTime = metadata .filter { highlightsUrls.contains(it.key.url) } .groupBy { it.key.url } .map { (url, data) -> url to data.maxByOrNull { it.updatedAt }!! } return highlights.map { HistoryHighlightInternal( historyHighlight = it, lastAccessedTime = highlightsLastUpdatedTime .firstOrNull { (url, _) -> url == it.url }?.second?.updatedAt ?: 0, ) } }" Perform an in-memory mapping of a history highlight to metadata records to compute its last access time. +"@VisibleForTesting internal fun getHistorySearchGroups( metadata: List, ): List { return metadata .filter { it.totalViewTime > 0 && it.key.searchTerm != null } .groupBy { it.key.searchTerm!! } .mapValues { group -> // Within a group, we dedupe entries based on their url so we don't display // a page multiple times in the same group, and we sum up the total view time // of deduped entries while making sure to keep the latest updatedAt value. val metadataInGroup = group.value val metadataUrlGroups = metadataInGroup.groupBy { metadata -> metadata.key.url } metadataUrlGroups.map { metadata -> metadata.value.reduce { acc, elem -> acc.copy( totalViewTime = acc.totalViewTime + elem.totalViewTime, updatedAt = max(acc.updatedAt, elem.updatedAt), ) } } } .map { HistoryGroupInternal( groupName = it.key, groupItems = it.value, ) } .filter { it.groupItems.size >= SEARCH_GROUP_MINIMUM_SITES } }" Group all urls accessed following a particular search. Automatically dedupes identical urls and adds each url's view time to the group's total. +"@VisibleForTesting internal fun getSortedHistory( historyHighlights: List, historyGroups: List, ): List { return (historyHighlights + historyGroups) .sortedByDescending { it.lastAccessedTime } .map { when (it) { is HistoryHighlightInternal -> RecentHistoryHighlight( title = if (it.historyHighlight.title.isNullOrBlank()) { it.historyHighlight.url } else { it.historyHighlight.title!! }, url = it.historyHighlight.url, ) is HistoryGroupInternal -> RecentHistoryGroup( title = it.groupName, historyMetadata = it.groupItems, ) } } } override fun stop() { job?.cancel() } }" Maps the internal highlights and search groups to the final objects to be returned. Items will be sorted by their last accessed date so that the most recent will be first. +"@VisibleForTesting internal fun List.removeHighlightsAlreadyInGroups( historyMetadata: List, ): List { return filterNot { highlight -> historyMetadata.any { it.groupItems.any { it.key.url == highlight.historyHighlight.url } } } }" Filter out highlights that are already part of a history group. +"@OptIn(ExperimentalComposeUiApi::class) @Composable fun PocketStory( @PreviewParameter(PocketStoryProvider::class) story: PocketRecommendedStory, backgroundColor: Color, onStoryClick: (PocketRecommendedStory) -> Unit, ) { val imageUrl = story.imageUrl.replace( ""{wh}"", with(LocalDensity.current) { ""${116.dp.toPx().roundToInt()}x${84.dp.toPx().roundToInt()}"" }, ) val isValidPublisher = story.publisher.isNotBlank() val isValidTimeToRead = story.timeToRead >= 0 ListItemTabLarge( imageUrl = imageUrl, backgroundColor = backgroundColor, onClick = { onStoryClick(story) }, title = { Text( text = story.title, modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.story.title"" }, color = FirefoxTheme.colors.textPrimary, overflow = TextOverflow.Ellipsis, maxLines = 2, style = FirefoxTheme.typography.body2, ) }, subtitle = { if (isValidPublisher && isValidTimeToRead) { TabSubtitleWithInterdot(story.publisher, ""${story.timeToRead} min"") } else if (isValidPublisher) { Text( text = story.publisher, modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.story.publisher"" }, color = FirefoxTheme.colors.textSecondary, overflow = TextOverflow.Ellipsis, maxLines = 1, style = FirefoxTheme.typography.caption, ) } else if (isValidTimeToRead) { Text( text = ""${story.timeToRead} min"", modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.story.timeToRead"" }, color = FirefoxTheme.colors.textSecondary, overflow = TextOverflow.Ellipsis, maxLines = 1, style = FirefoxTheme.typography.caption, ) } }, ) }" Displays a single [PocketRecommendedStory]. +"@OptIn(ExperimentalComposeUiApi::class) @Composable fun PocketSponsoredStory( story: PocketSponsoredStory, backgroundColor: Color, onStoryClick: (PocketSponsoredStory) -> Unit, ) { val (imageWidth, imageHeight) = with(LocalDensity.current) { 116.dp.toPx().roundToInt() to 84.dp.toPx().roundToInt() } val imageUrl = story.imageUrl.replace( ""&resize=w[0-9]+-h[0-9]+"".toRegex(), ""&resize=w$imageWidth-h$imageHeight"", ) ListItemTabSurface( imageUrl = imageUrl, backgroundColor = backgroundColor, onClick = { onStoryClick(story) }, ) { Text( text = story.title, modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.sponsoredStory.title"" }, color = FirefoxTheme.colors.textPrimary, overflow = TextOverflow.Ellipsis, maxLines = 2, style = FirefoxTheme.typography.body2, ) Spacer(Modifier.height(9.dp)) Text( text = stringResource(R.string.pocket_stories_sponsor_indication), modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.sponsoredStory.identifier"" }, color = FirefoxTheme.colors.textSecondary, overflow = TextOverflow.Ellipsis, maxLines = 1, style = FirefoxTheme.typography.caption, ) Spacer(Modifier.height(7.dp)) Text( text = story.sponsor, modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.sponsoredStory.sponsor"" }, color = FirefoxTheme.colors.textSecondary, overflow = TextOverflow.Ellipsis, maxLines = 1, style = FirefoxTheme.typography.caption, ) } }" Displays a single [PocketSponsoredStory]. +"@OptIn(ExperimentalComposeUiApi::class) @Suppress(""LongParameterList"") @Composable fun PocketStories( @PreviewParameter(PocketStoryProvider::class) stories: List, contentPadding: Dp, backgroundColor: Color = FirefoxTheme.colors.layer2, onStoryShown: (PocketStory, Pair) -> Unit, onStoryClicked: (PocketStory, Pair) -> Unit, onDiscoverMoreClicked: (String) -> Unit, ) { // Show stories in at most 3 rows but on any number of columns depending on the data received. val maxRowsNo = 3 val storiesToShow = (stories + placeholderStory).chunked(maxRowsNo) val listState = rememberLazyListState() val flingBehavior = EagerFlingBehavior(lazyRowState = listState) LazyRow( modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.stories"" }, contentPadding = PaddingValues(horizontal = contentPadding), state = listState, flingBehavior = flingBehavior, horizontalArrangement = Arrangement.spacedBy(8.dp), ) { itemsIndexed(storiesToShow) { columnIndex, columnItems -> Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { columnItems.forEachIndexed { rowIndex, story -> Box( modifier = Modifier.semantics { testTagsAsResourceId = true testTag = when (story) { placeholderStory -> ""pocket.discover.more.story"" is PocketRecommendedStory -> ""pocket.recommended.story"" else -> ""pocket.sponsored.story"" } }, ) { if (story == placeholderStory) { ListItemTabLargePlaceholder(stringResource(R.string.pocket_stories_placeholder_text)) { onDiscoverMoreClicked(""https://getpocket.com/explore?$POCKET_FEATURE_UTM_KEY_VALUE"") } } else if (story is PocketRecommendedStory) { PocketStory( story = story, backgroundColor = backgroundColor, ) { val uri = Uri.parse(story.url) .buildUpon() .appendQueryParameter(URI_PARAM_UTM_KEY, POCKET_STORIES_UTM_VALUE) .build().toString() onStoryClicked(it.copy(url = uri), rowIndex to columnIndex) } } else if (story is PocketSponsoredStory) { Box( modifier = Modifier.onShown(0.5f) { onStoryShown(story, rowIndex to columnIndex) }, ) { PocketSponsoredStory( story = story, backgroundColor = backgroundColor, ) { onStoryClicked(story, rowIndex to columnIndex) } } } } } } } } }" Displays a list of [PocketStory]es on 3 by 3 grid. If there aren't enough stories to fill all columns placeholders containing an external link to go to Pocket for more recommendations are added. +"private fun Modifier.onShown( @FloatRange(from = 0.0, to = 1.0) threshold: Float, onVisible: () -> Unit, ): Modifier { val initialTime = System.currentTimeMillis() var lastVisibleCoordinates: LayoutCoordinates? = null return composed { if (inComposePreview) { Modifier } else { val context = LocalContext.current var wasEventReported by remember { mutableStateOf(false) } val toolbarHeight = context.resources.getDimensionPixelSize(R.dimen.browser_toolbar_height) val isToolbarPlacedAtBottom = context.settings().shouldUseBottomToolbar // Get a Rect of the entire screen minus system insets minus the toolbar val screenBounds = Rect() .apply { LocalView.current.getWindowVisibleDisplayFrame(this) } .apply { when (isToolbarPlacedAtBottom) { true -> bottom -= toolbarHeight false -> top += toolbarHeight } } // In the event this composable starts as visible but then gets pushed offscreen // before MINIMUM_TIME_TO_SETTLE_MS we will not report is as being visible. // In the LaunchedEffect we add support for when the composable starts as visible and then // it's position isn't changed after MINIMUM_TIME_TO_SETTLE_MS so it must be reported as visible. LaunchedEffect(initialTime) { delay(MINIMUM_TIME_TO_SETTLE_MS.toLong()) if (!wasEventReported && lastVisibleCoordinates?.isVisible(screenBounds, threshold) == true) { wasEventReported = true onVisible() } } onGloballyPositioned { coordinates -> if (!wasEventReported && coordinates.isVisible(screenBounds, threshold)) { if (System.currentTimeMillis() - initialTime > MINIMUM_TIME_TO_SETTLE_MS) { wasEventReported = true onVisible() } else { lastVisibleCoordinates = coordinates } } } } } }" "Add a callback for when this Composable is ""shown"" on the screen. This checks whether the composable has at least [threshold] ratio of it's total area drawn inside the screen bounds. Does not account for other Views / Windows covering it." +Return whether this has at least [threshold] ratio of it's total area drawn inside the screen bounds. "private fun LayoutCoordinates.isVisible( visibleRect: Rect, @FloatRange(from = 0.0, to = 1.0) threshold: Float, ): Boolean { if (!isAttached) return false return boundsInWindow().toAndroidRect().getIntersectPercentage(size, visibleRect) >= threshold }" +"@FloatRange(from = 0.0, to = 1.0) private fun Rect.getIntersectPercentage(realSize: IntSize, other: Rect): Float { val composableArea = realSize.height * realSize.width val heightOverlap = max(0, min(bottom, other.bottom) - max(top, other.top)) val widthOverlap = max(0, min(right, other.right) - max(left, other.left)) val intersectionArea = heightOverlap * widthOverlap return (intersectionArea.toFloat() / composableArea) }" Returns the ratio of how much this intersects with [other]. +"@OptIn(ExperimentalComposeUiApi::class) @Suppress(""LongParameterList"") @Composable fun PocketStoriesCategories( categories: List, selections: List, modifier: Modifier = Modifier, categoryColors: PocketStoriesCategoryColors = PocketStoriesCategoryColors.buildColors(), onCategoryClick: (PocketRecommendedStoriesCategory) -> Unit, ) { Box( modifier = modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.categories"" }, ) { StaggeredHorizontalGrid( horizontalItemsSpacing = 16.dp, verticalItemsSpacing = 16.dp, ) { categories.filter { it.name != POCKET_STORIES_DEFAULT_CATEGORY_NAME }.forEach { category -> SelectableChip( text = category.name, isSelected = selections.map { it.name }.contains(category.name), selectedTextColor = categoryColors.selectedTextColor, unselectedTextColor = categoryColors.unselectedTextColor, selectedBackgroundColor = categoryColors.selectedBackgroundColor, unselectedBackgroundColor = categoryColors.unselectedBackgroundColor, ) { onCategoryClick(category) } } } } }" Displays a list of [PocketRecommendedStoriesCategory]s. +"data class PocketStoriesCategoryColors( val selectedBackgroundColor: Color, val unselectedBackgroundColor: Color, val selectedTextColor: Color, val unselectedTextColor: Color, ) { companion object { @Composable fun buildColors( selectedBackgroundColor: Color = FirefoxTheme.colors.actionPrimary, unselectedBackgroundColor: Color = FirefoxTheme.colors.actionTertiary, selectedTextColor: Color = FirefoxTheme.colors.textActionPrimary, unselectedTextColor: Color = FirefoxTheme.colors.textActionTertiary, ) = PocketStoriesCategoryColors( selectedBackgroundColor = selectedBackgroundColor, unselectedBackgroundColor = unselectedBackgroundColor, selectedTextColor = selectedTextColor, unselectedTextColor = unselectedTextColor, ) } }" Wrapper for the color parameters of [PocketStoriesCategories]. +"@OptIn(ExperimentalComposeUiApi::class) @Composable fun PoweredByPocketHeader( onLearnMoreClicked: (String) -> Unit, modifier: Modifier = Modifier, textColor: Color = FirefoxTheme.colors.textPrimary, linkTextColor: Color = FirefoxTheme.colors.textAccent, ) { val link = stringResource(R.string.pocket_stories_feature_learn_more) val text = stringResource(R.string.pocket_stories_feature_caption, link) val linkStartIndex = text.indexOf(link) val linkEndIndex = linkStartIndex + link.length Column( modifier = modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.header"" }, horizontalAlignment = Alignment.CenterHorizontally, ) { Row( Modifier .fillMaxWidth() .semantics(mergeDescendants = true) {}, verticalAlignment = Alignment.CenterVertically, ) { Icon( painter = painterResource(id = R.drawable.pocket_vector), contentDescription = null, // Apply the red tint in code. Otherwise the image is black and white. tint = Color(0xFFEF4056), ) Spacer(modifier = Modifier.width(16.dp)) Column { Text( text = stringResource( R.string.pocket_stories_feature_title_2, LocalContext.current.getString(R.string.pocket_product_name), ), modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.header.title"" }, color = textColor, style = FirefoxTheme.typography.caption, ) Box( modifier = modifier.semantics { testTagsAsResourceId = true testTag = ""pocket.header.subtitle"" }, ) { ClickableSubstringLink( text = text, textColor = textColor, linkTextColor = linkTextColor, linkTextDecoration = TextDecoration.Underline, clickableStartIndex = linkStartIndex, clickableEndIndex = linkEndIndex, ) { onLearnMoreClicked( ""https://www.mozilla.org/en-US/firefox/pocket/?$POCKET_FEATURE_UTM_KEY_VALUE"", ) } } } } } }" Pocket feature section title. Shows a default text about Pocket and offers a external link to learn more. +"@OptIn(ExperimentalComposeUiApi::class) @Composable private fun RecentBookmarksMenu( showMenu: Boolean, menuItems: List, recentBookmark: RecentBookmark, onDismissRequest: () -> Unit, ) { DropdownMenu( expanded = showMenu, onDismissRequest = { onDismissRequest() }, modifier = Modifier .background(color = FirefoxTheme.colors.layer2) .semantics { testTagsAsResourceId = true testTag = ""recent.bookmark.menu"" }, ) { for (item in menuItems) { DropdownMenuItem( onClick = { onDismissRequest() item.onClick(recentBookmark) }, ) { Text( text = item.title, color = FirefoxTheme.colors.textPrimary, maxLines = 1, modifier = Modifier .fillMaxHeight() .align(Alignment.CenterVertically), ) } } } }" Menu shown for a [RecentBookmark]. +"@OptIn(ExperimentalComposeUiApi::class) @Composable fun RecentBookmarks( bookmarks: List, menuItems: List, backgroundColor: Color, onRecentBookmarkClick: (RecentBookmark) -> Unit = {}, ) { LazyRow( modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""recent.bookmarks"" }, contentPadding = PaddingValues(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), ) { items(bookmarks) { bookmark -> RecentBookmarkItem( bookmark = bookmark, menuItems = menuItems, backgroundColor = backgroundColor, onRecentBookmarkClick = onRecentBookmarkClick, ) } } }" A list of recent bookmarks. +"@OptIn( ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class, ) @Composable private fun RecentBookmarkItem( bookmark: RecentBookmark, menuItems: List, backgroundColor: Color, onRecentBookmarkClick: (RecentBookmark) -> Unit = {}, ) { var isMenuExpanded by remember { mutableStateOf(false) } Card( modifier = Modifier .width(158.dp) .combinedClickable( enabled = true, onClick = { onRecentBookmarkClick(bookmark) }, onLongClick = { isMenuExpanded = true }, ), shape = cardShape, backgroundColor = backgroundColor, elevation = 6.dp, ) { Column( modifier = Modifier .fillMaxWidth() .padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 8.dp), ) { RecentBookmarkImage(bookmark) Spacer(modifier = Modifier.height(8.dp)) Text( text = bookmark.title ?: bookmark.url ?: """", modifier = Modifier.semantics { testTagsAsResourceId = true testTag = ""recent.bookmark.title"" }, color = FirefoxTheme.colors.textPrimary, overflow = TextOverflow.Ellipsis, maxLines = 1, style = FirefoxTheme.typography.caption, ) RecentBookmarksMenu( showMenu = isMenuExpanded, menuItems = menuItems, recentBookmark = bookmark, onDismissRequest = { isMenuExpanded = false }, ) } } }" A recent bookmark item. +@InternalStreamChatApi public const val GIPHY_INFO_DEFAULT_WIDTH_DP: Int = 200 Default width used for Giphy Images if no width metadata is available. +@InternalStreamChatApi public const val GIPHY_INFO_DEFAULT_HEIGHT_DP: Int = 200 Default height used for Giphy Images if no width metadata is available. +"public fun Attachment.giphyInfo(field: GiphyInfoType): GiphyInfo? { val giphyInfoMap =(extraData[ModelType.attach_giphy] as? Map?)?.get(field.value) as? Map? return giphyInfoMap?.let { map -> GiphyInfo( url = map[""url""] ?: """", width = getGiphySize(map, ""width"", Utils.dpToPx(GIPHY_INFO_DEFAULT_WIDTH_DP)), height = getGiphySize(map, ""height"", Utils.dpToPx(GIPHY_INFO_DEFAULT_HEIGHT_DP)) ) } }" Returns an object containing extra information about the Giphy image based on its type. +"private fun getGiphySize(map: Map, size: String, defaultValue: Int): Int { return if (!map[size].isNullOrBlank()) map[size]?.toInt() ?: defaultValue else defaultValue }" Returns specified size for the giphy. +"public data class GiphyInfo( val url: String, @Px val width: Int, @Px val height: Int, )" Contains extra information about Giphy attachments. +"@OptIn(ExperimentalCoroutinesApi::class) @InternalStreamChatApi @Suppress(""TooManyFunctions"") public class MessageComposerController( private val channelId: String, private val chatClient: ChatClient = ChatClient.instance(), private val maxAttachmentCount: Int = AttachmentConstants.MAX_ATTACHMENTS_COUNT,private val maxAttachmentSize: Long = AttachmentConstants.MAX_UPLOAD_FILE_SIZE, ) { }" "Controller responsible for handling the composing and sending of messages. It acts as a central place for both the core business logic and state required to create and send messages, handle attachments, message actions and more. If you require more state and business logic, compose this Controller with your code and apply the necessary changes." +private val scope = CoroutineScope(DispatcherProvider.Immediate) Creates a [CoroutineScope] that allows us to cancel the ongoing work when the parent  ViewModel is disposed. +"public var typingUpdatesBuffer: TypingUpdatesBuffer = DefaultTypingUpdatesBuffer( onTypingStarted = ::sendKeystrokeEvent, onTypingStopped = ::sendStopTypingEvent, coroutineScope = scope )" Buffers typing updates. +"public val channelState: Flow = chatClient.watchChannelAsState( cid = channelId, messageLimit = DefaultMessageLimit, coroutineScope = scope ).filterNotNull()" Holds information about the current state of the [Channel]. +"public val ownCapabilities: StateFlow> = channelState.flatMapLatest { it.channelData } .map { it.ownCapabilities } .stateIn( scope = scope, started = SharingStarted.Eagerly, initialValue = setOf() )" Holds information about the abilities the current user is able to exercise in the given channel. +"private val canSendTypingUpdates = ownCapabilities.map { it.contains(ChannelCapabilities.SEND_TYPING_EVENTS) } .stateIn( scope = scope, started = SharingStarted.Eagerly, initialValue = false )" Signals if the user's typing will send a typing update in the given channel. +"private val canSendLinks = ownCapabilities.map { it.contains(ChannelCapabilities.SEND_LINKS) }.stateIn(scope = scope,started = SharingStarted.Eagerly,initialValue = false)" Signals if the user is allowed to send links. +"private val isSlowModeActive = ownCapabilities.map { it.contains(ChannelCapabilities.SLOW_MODE) } .stateIn( scope = scope, started = SharingStarted.Eagerly, initialValue = false )" Signals if the user needs to wait before sending the next message. +public val state: MutableStateFlow = MutableStateFlow(MessageComposerState()) Full message composer state holding all the required information. +"public val input: MutableStateFlow = MutableStateFlow("""")" UI state of the current composer input. +public val alsoSendToChannel: MutableStateFlow = MutableStateFlow(false) If the message will be shown in the channel after it is sent. +public val cooldownTimer: MutableStateFlow = MutableStateFlow(0) Represents the remaining time until the user is allowed to send the next message. +public val selectedAttachments: MutableStateFlow> = MutableStateFlow(emptyList()) "Represents the currently selected attachments, that are shown within the composer UI." +public val validationErrors: MutableStateFlow> = MutableStateFlow(emptyList()) Represents the list of validation errors for the current text input and the currently selected attachments. +public val mentionSuggestions: MutableStateFlow> = MutableStateFlow(emptyList()) Represents the list of users that can be used to autocomplete the current mention input. +public val commandSuggestions: MutableStateFlow> = MutableStateFlow(emptyList()) Represents the list of commands that can be executed for the channel. +private var users: List = emptyList() Represents the list of users in the channel. +private var commands: List = emptyList() Represents the list of available commands in the channel. \ No newline at end of file