Skip to content

Commit 4b8ce31

Browse files
committed
code improvement and bug fixes
Change-Id: I0e1d4f2b69acebe3f3b0f7541b9294579c78c392 Signed-off-by: AbdAlMoniem AlHifnawy <hifnawy_moniem@hotmail.com>
1 parent d9b7014 commit 4b8ce31

File tree

6 files changed

+60
-52
lines changed

6 files changed

+60
-52
lines changed

app/src/main/java/com/hifnawy/caffeinate/CaffeinateApplication.kt

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,14 @@ import android.content.Context
55
import android.os.Build
66
import android.util.LayoutDirection
77
import androidx.core.text.layoutDirection
8+
import com.hifnawy.caffeinate.controller.Observer
89
import com.hifnawy.caffeinate.controller.QuickTileService
910
import com.hifnawy.caffeinate.controller.ServiceStatus
1011
import com.hifnawy.caffeinate.controller.ServiceStatusObserver
11-
import com.hifnawy.caffeinate.view.CheckBoxItem
12-
import com.hifnawy.caffeinate.utils.LogDebugTree
1312
import com.hifnawy.caffeinate.controller.SharedPrefsManager
1413
import com.hifnawy.caffeinate.controller.SharedPrefsObserver
14+
import com.hifnawy.caffeinate.utils.LogDebugTree
15+
import com.hifnawy.caffeinate.view.CheckBoxItem
1516
import com.hifnawy.caffeinate.view.Widget
1617
import java.util.Locale
1718
import kotlin.time.Duration
@@ -225,8 +226,9 @@ class CaffeinateApplication : Application() {
225226
if (status is ServiceStatus.Stopped) timeout = firstTimeout
226227

227228
keepAwakeServiceObservers.forEach { observer ->
228-
Log.d("observer: <${observer::class.simpleName}> $observer")
229+
Log.d("notifying ${Observer::class.simpleName}<${observer::class.simpleName}@${observer.hashCode().toString(16).uppercase()}>...")
229230
observer.onServiceStatusUpdated(status)
231+
Log.d("${Observer::class.simpleName}<${observer::class.simpleName}@${observer.hashCode().toString(16).uppercase()}> notified!")
230232
}
231233

232234
QuickTileService.requestTileStateUpdate(this)

app/src/main/java/com/hifnawy/caffeinate/controller/KeepAwakeService.kt

Lines changed: 29 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -368,7 +368,7 @@ class KeepAwakeService : Service(), SharedPrefsObserver, ServiceStatusObserver {
368368
override fun onTaskRemoved(rootIntent: Intent?) {
369369
super.onTaskRemoved(rootIntent)
370370

371-
Log.d("${this::class.simpleName} service removed from task manager! restarting...")
371+
Log.d("${javaClass.simpleName} service removed from task manager! restarting...")
372372

373373
Intent(this, KeepAwakeService::class.java).apply {
374374
action = ACTION_RESTART.name
@@ -470,15 +470,16 @@ class KeepAwakeService : Service(), SharedPrefsObserver, ServiceStatusObserver {
470470
* @see [acquireWakeLock]
471471
*/
472472
private fun prepareService(startAfter: Duration? = null) = caffeinateApplication.run {
473-
Log.d("starting ${this@KeepAwakeService::class.simpleName} service...")
473+
Log.d("starting ${localizedApplicationContext.getString(R.string.app_name)} with duration: ${timeout.toFormattedTime()}}")
474+
474475
val status = when (val status = lastStatusUpdate) {
475476
is ServiceStatus.Running -> status.apply { remaining = timeout }
476477
is ServiceStatus.Stopped -> ServiceStatus.Running(timeout)
477478
}
478479

479480
lastStatusUpdate = status
480481

481-
Log.d("status: $status, selectedDuration: ${status.remaining.toFormattedTime()}")
482+
Log.d("starting status: $status")
482483

483484
Log.d("sending foreground notification...")
484485
startForeground(NOTIFICATION_ID, buildForegroundNotification(status))
@@ -492,7 +493,7 @@ class KeepAwakeService : Service(), SharedPrefsObserver, ServiceStatusObserver {
492493

493494
startCaffeine(status.remaining, startAfter)
494495

495-
Log.d("${this@KeepAwakeService::class.simpleName} service started!")
496+
Log.d("${localizedApplicationContext.getString(R.string.app_name)} started!")
496497
}
497498

498499
/**
@@ -604,9 +605,9 @@ class KeepAwakeService : Service(), SharedPrefsObserver, ServiceStatusObserver {
604605
val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
605606

606607
wakeLock?.apply {
607-
Log.d("releasing ${this@KeepAwakeService::wakeLock.name}...")
608+
Log.d("releasing ${::wakeLock.name}...")
608609
releaseSafely(::wakeLock.name)
609-
Log.d("${this@KeepAwakeService::wakeLock.name} released!")
610+
Log.d("${::wakeLock.name} released!")
610611
} ?: Log.d("wakeLock is not held!")
611612
@Suppress("DEPRECATION")
612613
val wakeLockLevel = when {
@@ -625,12 +626,12 @@ class KeepAwakeService : Service(), SharedPrefsObserver, ServiceStatusObserver {
625626
wakeLockLevel,
626627
"${caffeinateApplication.localizedApplicationContext.getString(R.string.app_name)}:wakeLockTag"
627628
).apply {
628-
Log.d("acquiring ${this@KeepAwakeService::wakeLock.name}, isDimmingEnabled: $isDimmingEnabled...")
629+
Log.d("acquiring ${::wakeLock.name}, isDimmingEnabled: $isDimmingEnabled...")
629630
when {
630631
duration.isInfinite() -> acquire()
631632
else -> acquire(duration.inWholeMilliseconds)
632633
}
633-
Log.d("${this@KeepAwakeService::wakeLock.name} acquired, isDimmingEnabled: $isDimmingEnabled!")
634+
Log.d("${::wakeLock.name} acquired, isDimmingEnabled: $isDimmingEnabled!")
634635
}
635636
}
636637

@@ -646,25 +647,25 @@ class KeepAwakeService : Service(), SharedPrefsObserver, ServiceStatusObserver {
646647
* @param startAfter [Duration] the duration to delay before starting the service
647648
*/
648649
private fun startCaffeine(duration: Duration, startAfter: Duration? = null) = caffeinateApplication.run {
649-
Log.d("starting ${localizedApplicationContext.getString(R.string.app_name)} with duration: ${duration.toFormattedTime()}, isIndefinite: ${duration.isInfinite()}")
650+
Log.d("starting ${this@KeepAwakeService::class.simpleName} service...")
650651

651652
acquireWakeLock(duration)
652653

653654
if (isOverlayEnabled) overlayHandler.showOverlay()
654655

655-
caffeineTimeoutJob.apply {
656-
Log.d("stopping ${this@KeepAwakeService::caffeineTimeoutJob.name}...")
656+
with(caffeineTimeoutJob) {
657+
Log.d("stopping ${::caffeineTimeoutJob.name}...")
657658
stop()
658-
Log.d("${this@KeepAwakeService::caffeineTimeoutJob.name} stopped!")
659-
}
660-
661-
Log.d("starting ${this@KeepAwakeService::caffeineTimeoutJob.name}...")
662-
caffeineTimeoutJob.start(duration, startAfter)
663-
Log.d("${this@KeepAwakeService::caffeineTimeoutJob.name} started!")
659+
Log.d("${::caffeineTimeoutJob.name} stopped!")
664660

665-
Log.d("${localizedApplicationContext.getString(R.string.app_name)} started!")
661+
Log.d("starting ${::caffeineTimeoutJob.name}...")
662+
start(duration, startAfter)
663+
Log.d("${::caffeineTimeoutJob.name} started!")
664+
}
666665

667666
sharedPreferences.isServiceRunning = true
667+
668+
Log.d("${this@KeepAwakeService::class.simpleName} service started!")
668669
}
669670

670671
/**
@@ -679,21 +680,22 @@ class KeepAwakeService : Service(), SharedPrefsObserver, ServiceStatusObserver {
679680
*/
680681
private fun stopCaffeine() = caffeinateApplication.run {
681682
Log.d("stopping ${localizedApplicationContext.getString(R.string.app_name)}...")
683+
Log.d("stopping ${this@KeepAwakeService::class.simpleName} service...")
682684

683685
wakeLock?.apply {
684-
Log.d("releasing ${this@KeepAwakeService::wakeLock.name}...")
686+
Log.d("releasing ${::wakeLock.name}...")
685687
releaseSafely(::wakeLock.name)
686-
Log.d("${this@KeepAwakeService::wakeLock.name} released!")
688+
Log.d("${::wakeLock.name} released!")
687689
} ?: Log.d("wakeLock is not held!")
688690

689691
caffeineTimeoutJob.apply {
690-
Log.d("stopping ${this@KeepAwakeService::caffeineTimeoutJob.name}...")
692+
Log.d("stopping ${::caffeineTimeoutJob.name}...")
691693
stop()
692-
Log.d("${this@KeepAwakeService::caffeineTimeoutJob.name} stopped!")
694+
Log.d("${::caffeineTimeoutJob.name} stopped!")
693695

694-
Log.d("cancelling ${this@KeepAwakeService::caffeineTimeoutJob.name}...")
696+
Log.d("cancelling ${::caffeineTimeoutJob.name}...")
695697
cancel()
696-
Log.d("${this@KeepAwakeService::caffeineTimeoutJob.name} cancelled!")
698+
Log.d("${::caffeineTimeoutJob.name} cancelled!")
697699
}
698700

699701
localeChangeReceiver.isRegistered = false
@@ -706,13 +708,14 @@ class KeepAwakeService : Service(), SharedPrefsObserver, ServiceStatusObserver {
706708

707709
notificationManager.cancel(NOTIFICATION_ID)
708710

709-
Log.d("${localizedApplicationContext.getString(R.string.app_name)} stopped!")
710-
711711
if (isOverlayEnabled) overlayHandler.hideOverlay()
712712

713713
sharedPreferences.isServiceRunning = false
714714

715715
stopSelf()
716+
717+
Log.d("${this@KeepAwakeService::class.simpleName} service stopped!")
718+
Log.d("${localizedApplicationContext.getString(R.string.app_name)} stopped!")
716719
}
717720

718721
/**

app/src/main/java/com/hifnawy/caffeinate/controller/ServiceStatus.kt

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ sealed class ServiceStatus {
9595
* @see ServiceStatus.Running.startTimeout
9696
*/
9797
var isCountingDown: Boolean = false
98-
get() = prevRemaining?.let { remaining < it && remaining in Duration.ZERO..startTimeout && startTimeout.isFinite() } ?: false
98+
get() = prevRemaining?.let { remaining < it && remaining in Duration.ZERO..startTimeout && remaining.isFinite() } ?: false
9999
private set
100100

101101
/**
@@ -110,7 +110,7 @@ sealed class ServiceStatus {
110110
* @see ServiceStatus.Running.startTimeout
111111
*/
112112
var isRestarted: Boolean = false
113-
get() = prevRemaining?.let { remaining > it && remaining == startTimeout && startTimeout.isFinite() } ?: false
113+
get() = prevRemaining?.let { remaining > it && remaining == startTimeout && remaining.isFinite() } ?: false
114114
private set
115115

116116
/**
@@ -157,8 +157,7 @@ sealed class ServiceStatus {
157157

158158
/**
159159
* Returns a string in the format
160-
* "Running([remaining].[toFormattedTime]
161-
* , isRestarted: [isRestarted], isCountingDown: [isCountingDown], isIndefinite: [isIndefinite])".
160+
* "Running([remaining].[toFormattedTime], isRestarted: [isRestarted], isCountingDown: [isCountingDown], isIndefinite: [isIndefinite])".
162161
*
163162
* @return [String] a string representation of the object.
164163
*/

app/src/main/java/com/hifnawy/caffeinate/controller/TimeoutJob.kt

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ class TimeoutJob(private val caffeinateApplication: CaffeinateApplication) : Cor
7676
* @see [start]
7777
* @see [cancel]
7878
*/
79-
fun stop() = job?.cancel(CancellationException("${this::class.simpleName} cancelled!"))
79+
fun stop() = job?.cancel(CancellationException("${javaClass.simpleName} cancelled!"))
8080

8181
/**
8282
* Cancels the timeout job and releases any system resources that were allocated
@@ -90,7 +90,7 @@ class TimeoutJob(private val caffeinateApplication: CaffeinateApplication) : Cor
9090
* @see [start]
9191
* @see [stop]
9292
*/
93-
fun cancel() = cancel(CancellationException("${this::class.simpleName} cancelled!"))
93+
fun cancel() = cancel(CancellationException("${javaClass.simpleName} cancelled!"))
9494

9595
/**
9696
* Starts the timeout job.
@@ -106,15 +106,18 @@ class TimeoutJob(private val caffeinateApplication: CaffeinateApplication) : Cor
106106
*/
107107
fun start(startDuration: Duration, startAfter: Duration? = null) {
108108
job = launch {
109-
Log.d("$currentTime: timeout initialized with duration: ${startDuration.toFormattedTime()}, isIndefinite: ${startDuration.isInfinite()}")
110-
111109
startAfter?.let { delay(it) }
112110

113111
val delayDuration = when {
114112
startDuration.isInfinite() -> 10.seconds
115113
else -> 1.seconds
116114
}
117115

116+
Log.d(
117+
"$currentTime: timeout initialized with duration: ${startDuration.toFormattedTime()}, " +
118+
"timeout update period: ${delayDuration.toFormattedTime()}"
119+
)
120+
118121
generateSequence(startDuration) { it - delayDuration }.forEach { duration ->
119122
update(duration)
120123

@@ -143,6 +146,6 @@ class TimeoutJob(private val caffeinateApplication: CaffeinateApplication) : Cor
143146
else -> status.run { if (newRemaining < remaining || !isRestarted) remaining = newRemaining }
144147
}
145148

146-
Log.d("$currentTime: duration: ${newRemaining.toFormattedTime()}, status: $status, isIndefinite: ${newRemaining.isInfinite()}")
149+
Log.d("$currentTime: updated status: $status")
147150
}
148151
}

app/src/main/java/com/hifnawy/caffeinate/utils/MutableListExtensionFunctions.kt

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -34,17 +34,17 @@ object MutableListExtensionFunctions {
3434
inline fun <reified ObserverType : Observer> MutableList<ObserverType>.addObserver(observer: ObserverType) {
3535
when {
3636
observer !in this -> {
37-
Log.d("adding ${observer::class.simpleName} to ${this::class.simpleName}<${ObserverType::class.simpleName}>...")
37+
Log.d("adding ${observer::class.simpleName} to ${javaClass.simpleName}<${ObserverType::class.simpleName}>...")
3838
add(observer)
39-
Log.d("${observer::class.simpleName} added to ${this::class.simpleName}<${ObserverType::class.simpleName}>!")
39+
Log.d("${observer::class.simpleName} added to ${javaClass.simpleName}<${ObserverType::class.simpleName}>!")
4040
}
4141

42-
else -> Log.d("${observer::class.simpleName} is already added to ${this::class.simpleName}<${ObserverType::class.simpleName}>!")
42+
else -> Log.d("${observer::class.simpleName} is already added to ${javaClass.simpleName}<${ObserverType::class.simpleName}>!")
4343
}
4444

4545
if (isNotEmpty()) {
4646
Log.d(
47-
"Items in ${this::class.simpleName}<${ObserverType::class.simpleName}>:\n" +
47+
"Items in ${javaClass.simpleName}<${ObserverType::class.simpleName}>: " +
4848
"[${joinToString(", ") { "${it::class.simpleName.toString()}@${it.hashCode().toString(16).uppercase()}" }}]"
4949
)
5050
}
@@ -62,20 +62,20 @@ object MutableListExtensionFunctions {
6262
inline fun <reified ObserverType : Observer> MutableList<ObserverType>.removeObserver(observer: ObserverType) {
6363
when {
6464
observer in this -> {
65-
Log.d("removing ${observer::class.simpleName} from ${this::class.simpleName}<${ObserverType::class.simpleName}>...")
65+
Log.d("removing ${observer::class.simpleName} from ${javaClass.simpleName}<${ObserverType::class.simpleName}>...")
6666

6767
when (remove(observer)) {
68-
true -> Log.d("${observer::class.simpleName} removed from ${this::class.simpleName}<${ObserverType::class.simpleName}>!")
69-
else -> Log.d("${observer::class.simpleName} is not present in ${this::class.simpleName}<${ObserverType::class.simpleName}>!")
68+
true -> Log.d("${observer::class.simpleName} removed from ${javaClass.simpleName}<${ObserverType::class.simpleName}>!")
69+
else -> Log.d("${observer::class.simpleName} is not present in ${javaClass.simpleName}<${ObserverType::class.simpleName}>!")
7070
}
7171
}
7272

73-
else -> Log.d("${observer::class.simpleName} is not present in ${this::class.simpleName}<${ObserverType::class.simpleName}>!")
73+
else -> Log.d("${observer::class.simpleName} is not present in ${javaClass.simpleName}<${ObserverType::class.simpleName}>!")
7474
}
7575

7676
if (isNotEmpty()) {
7777
Log.d(
78-
"Items in ${this::class.simpleName}<${ObserverType::class.simpleName}>:\n" +
78+
"Items in ${javaClass.simpleName}<${ObserverType::class.simpleName}>: " +
7979
"[${joinToString(", ") { "${it::class.simpleName.toString()}@${it.hashCode().toString(16).uppercase()}" }}]"
8080
)
8181
}

app/src/main/java/com/hifnawy/caffeinate/view/MainActivity.kt

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -389,7 +389,7 @@ class MainActivity : AppCompatActivity(), SharedPrefsObserver, ServiceStatusObse
389389
updatePictureInPictureView(caffeinateApplication.lastStatusUpdate)
390390
}
391391

392-
root.onSizeChange { view, newWidth, newHeight, _, _ ->
392+
root.onSizeChange { _, newWidth, newHeight, _, _ ->
393393
Log.d("root layout size changed, newWidth: $newWidth, newHeight: $newHeight")
394394

395395
with(pipLayout.progressIndicator) {
@@ -401,7 +401,7 @@ class MainActivity : AppCompatActivity(), SharedPrefsObserver, ServiceStatusObse
401401

402402
pipParamsBuilder?.run {
403403
pipSourceRectHint = Rect(0, 0, newWidth, newHeight / 2)
404-
// view.getGlobalVisibleRect(pipSourceRectHint)
404+
405405
setAspectRatio(Rational(1, 1))
406406
setSourceRectHint(pipSourceRectHint)
407407
setPictureInPictureParams(build())
@@ -1180,9 +1180,10 @@ class MainActivity : AppCompatActivity(), SharedPrefsObserver, ServiceStatusObse
11801180
}
11811181

11821182
val progress = when {
1183-
status is ServiceStatus.Running && status.remaining.isInfinite() -> 100
1184-
status is ServiceStatus.Running && status.remaining.isFinite() -> status.remaining.inWholeSeconds.toInt()
1185-
else -> 100
1183+
status is ServiceStatus.Running && status.remaining.isInfinite() -> 100
1184+
status is ServiceStatus.Running && (status.isRestarted || !status.isCountingDown) -> 0
1185+
status is ServiceStatus.Running && status.remaining.isFinite() -> status.remaining.inWholeSeconds.toInt()
1186+
else -> 100
11861187
}
11871188

11881189
pipLayout.progressIndicator.max = max

0 commit comments

Comments
 (0)