-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathMainActivity.kt
More file actions
1019 lines (922 loc) · 37.2 KB
/
MainActivity.kt
File metadata and controls
1019 lines (922 loc) · 37.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.immichframe.immichframe
import android.animation.ObjectAnimator
import android.animation.PropertyValuesHolder
import android.annotation.SuppressLint
import android.app.KeyguardManager
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.PowerManager
import android.provider.Settings
import android.text.SpannableString
import android.text.Spanned
import android.text.style.RelativeSizeSpan
import android.util.Log
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.WindowInsets
import android.view.WindowInsetsController
import android.view.WindowManager
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.view.WindowCompat
import androidx.preference.PreferenceManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import kotlinx.coroutines.*
import androidx.lifecycle.lifecycleScope
import androidx.core.graphics.toColorInt
import androidx.core.graphics.drawable.toDrawable
import androidx.core.net.toUri
import androidx.core.view.isVisible
class MainActivity : AppCompatActivity() {
private lateinit var webView: WebView
private lateinit var imageView1: ImageView
private lateinit var imageView2: ImageView
private lateinit var txtPhotoInfo: TextView
private lateinit var txtDateTime: TextView
private lateinit var btnPrevious: Button
private lateinit var btnPause: Button
private lateinit var btnNext: Button
private lateinit var dimOverlay: View
private lateinit var swipeRefreshLayout: View
private lateinit var serverSettings: Helpers.ServerSettings
private var retrofit: Retrofit? = null
private lateinit var apiService: Helpers.ApiService
private lateinit var rcpServer: RpcHttpServer
private var isWeatherTimerRunning = false
private var useWebView = true
private var keepScreenOn = true
private var blurredBackground = true
private var showCurrentDate = true
private var currentWeather = ""
private var isImageTimerRunning = false
private val handler = Handler(Looper.getMainLooper())
private var previousImage: Helpers.ImageResponse? = null
private var currentImage: Helpers.ImageResponse? = null
private var portraitCache: Helpers.ImageResponse? = null
private var originalScreenTimeout: Int = -1
private var isSnoozing = false
private val imageRunnable = object : Runnable {
override fun run() {
if (isImageTimerRunning) {
handler.postDelayed(this, (serverSettings.interval * 1000).toLong())
getNextImage()
}
}
}
private val weatherRunnable = object : Runnable {
override fun run() {
if (isWeatherTimerRunning) {
handler.postDelayed(this, 600000)
getWeather()
}
}
}
private val dimCheckRunnable = object : Runnable {
override fun run() {
checkDimTime()
handler.postDelayed(this, 30000)
}
}
private val redimRunnable = object : Runnable {
override fun run() {
isSnoozing = false
screenDim(true)
}
}
private var isShowingFirst = true
private var zoomAnimator: ObjectAnimator? = null
private val settingsLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == RESULT_OK) {
loadSettings()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
//force dark mode
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
super.onCreate(savedInstanceState)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
setContentView(R.layout.main_view)
hideSystemUI()
webView = findViewById(R.id.webView)
webView.setBackgroundColor(Color.BLACK)
webView.loadUrl("about:blank")
imageView1 = findViewById(R.id.imageView1)
imageView2 = findViewById(R.id.imageView2)
txtPhotoInfo = findViewById(R.id.txtPhotoInfo)
txtDateTime = findViewById(R.id.txtDateTime)
btnPrevious = findViewById(R.id.btnPrevious)
btnPause = findViewById(R.id.btnPause)
btnNext = findViewById(R.id.btnNext)
dimOverlay = findViewById(R.id.dimOverlay)
swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout)
val swipeRefreshLayout = findViewById<SwipeRefreshLayout>(R.id.swipeRefreshLayout)
swipeRefreshLayout.setOnRefreshListener {
swipeRefreshLayout.isRefreshing = false
settingsAction()
}
btnPrevious.setOnClickListener {
val toast = Toast.makeText(this, "Previous", Toast.LENGTH_SHORT)
toast.setGravity(Gravity.CENTER_VERTICAL or Gravity.START, 0, 0)
toast.show()
previousAction()
}
btnPause.setOnClickListener {
val toast = Toast.makeText(this, "Pause", Toast.LENGTH_SHORT)
toast.setGravity(Gravity.CENTER, 0, 0)
toast.show()
pauseAction()
}
btnNext.setOnClickListener {
val toast = Toast.makeText(this, "Next", Toast.LENGTH_SHORT)
toast.setGravity(Gravity.CENTER_VERTICAL or Gravity.END, 0, 0)
toast.show()
nextAction()
}
rcpServer = RpcHttpServer(
onDimCommand = { dim -> runOnUiThread { screenDim(dim) } },
onNextCommand = { runOnUiThread { nextAction() } },
onPreviousCommand = { runOnUiThread { previousAction() } },
onPauseCommand = { runOnUiThread { pauseAction() } },
onSettingsCommand = { runOnUiThread { settingsAction() } },
onBrightnessCommand = { brightness -> runOnUiThread { screenBrightnessAction(brightness) } },
)
rcpServer.start()
val prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext)
val savedUrl = prefs.getString("webview_url", "") ?: ""
if (savedUrl.isBlank()) {
val intent = Intent(this@MainActivity, SettingsActivity::class.java)
settingsLauncher.launch(intent)
} else {
loadSettings()
}
}
private fun showImage(imageResponse: Helpers.ImageResponse) {
CoroutineScope(Dispatchers.IO).launch {
//get the window size
val decorView = window.decorView
val width = decorView.width
val height = decorView.height
val maxSize = maxOf(width, height)
var randomBitmap = Helpers.decodeBitmapFromBytes(imageResponse.randomImageBase64)
val thumbHashBitmap = Helpers.decodeBitmapFromBytes(imageResponse.thumbHashImageBase64)
var isMerged = false
val isPortrait = randomBitmap.height > randomBitmap.width
if (isPortrait && serverSettings.layout == "splitview") {
if (portraitCache != null) {
var decodedPortraitImageBitmap =
Helpers.decodeBitmapFromBytes(portraitCache!!.randomImageBase64)
decodedPortraitImageBitmap =
Helpers.reduceBitmapQuality(decodedPortraitImageBitmap, maxSize)
randomBitmap = Helpers.reduceBitmapQuality(randomBitmap, maxSize)
val colorString =
serverSettings.primaryColor?.takeIf { it.isNotBlank() } ?: "#FFFFFF"
val parsedColor = colorString.toColorInt()
randomBitmap =
Helpers.mergeImages(decodedPortraitImageBitmap, randomBitmap, parsedColor)
isMerged = true
decodedPortraitImageBitmap.recycle()
} else {
portraitCache = imageResponse
getNextImage()
return@launch
}
} else {
randomBitmap = Helpers.reduceBitmapQuality(randomBitmap, maxSize * 2)
}
withContext(Dispatchers.Main) {
updateUI(randomBitmap, thumbHashBitmap, isMerged, imageResponse)
}
}
}
private fun updateUI(
finalImage: Bitmap,
thumbHashBitmap: Bitmap,
isMerged: Boolean,
imageResponse: Helpers.ImageResponse
) {
val imageViewOld = if (isShowingFirst) imageView1 else imageView2
val imageViewNew = if (isShowingFirst) imageView2 else imageView1
zoomAnimator?.cancel()
imageViewNew.alpha = 0f
imageViewNew.scaleX = 1f
imageViewNew.scaleY = 1f
imageViewNew.setImageBitmap(finalImage)
imageViewNew.visibility = View.VISIBLE
if (blurredBackground) {
imageViewNew.background = thumbHashBitmap.toDrawable(resources)
} else {
imageViewNew.background = null
}
imageViewNew.animate()
.alpha(1f)
.setDuration((serverSettings.transitionDuration * 1000).toLong())
.withEndAction {
if (serverSettings.imageZoom) {
startZoomAnimation(imageViewNew)
}
}
.start()
imageViewOld.animate()
.alpha(0f)
.setDuration((serverSettings.transitionDuration * 1000).toLong())
.withEndAction {
imageViewOld.visibility = View.GONE
}
.start()
// Toggle active ImageView
isShowingFirst = !isShowingFirst
if (isMerged) {
val mergedPhotoDate =
if (portraitCache!!.photoDate.isNotEmpty() || imageResponse.photoDate.isNotEmpty()) {
"${portraitCache!!.photoDate} | ${imageResponse.photoDate}"
} else {
""
}
val mergedImageLocation =
if (portraitCache!!.imageLocation.isNotEmpty() || imageResponse.imageLocation.isNotEmpty()) {
"${portraitCache!!.imageLocation} | ${imageResponse.imageLocation}"
} else {
""
}
updatePhotoInfo(mergedPhotoDate, mergedImageLocation)
portraitCache = null
} else {
updatePhotoInfo(imageResponse.photoDate, imageResponse.imageLocation)
}
updateDateTimeWeather()
}
private fun updatePhotoInfo(photoDate: String, photoLocation: String) {
if (serverSettings.showPhotoDate || serverSettings.showImageLocation) {
val photoInfo = buildString {
if (serverSettings.showPhotoDate && photoDate.isNotEmpty()) {
append(photoDate)
}
if (serverSettings.showImageLocation && photoLocation.isNotEmpty()) {
if (isNotEmpty()) append("\n")
append(photoLocation)
}
}
txtPhotoInfo.text = photoInfo
}
}
private fun updateDateTimeWeather() {
if (serverSettings.showClock) {
val currentDateTime = Calendar.getInstance().time
val formattedDate = try {
SimpleDateFormat(serverSettings.photoDateFormat, Locale.getDefault()).format(
currentDateTime
)
} catch (_: Exception) {
""
}
val formattedTime = try {
SimpleDateFormat(serverSettings.clockFormat, Locale.getDefault()).format(
currentDateTime
)
} catch (_: Exception) {
""
}
val dt = if (showCurrentDate && formattedDate.isNotEmpty()) {
"$formattedDate\n$formattedTime"
} else {
formattedTime
}
txtDateTime.text = SpannableString(dt).apply {
val start =
if (showCurrentDate && formattedDate.isNotEmpty()) formattedDate.length + 1 else 0
setSpan(RelativeSizeSpan(2f), start, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
if (serverSettings.showWeatherDescription) {
txtDateTime.append(currentWeather)
}
}
private fun getNextImage() {
apiService.getImageData().enqueue(object : Callback<Helpers.ImageResponse> {
override fun onResponse(
call: Call<Helpers.ImageResponse>,
response: Response<Helpers.ImageResponse>
) {
if (response.isSuccessful) {
val imageResponse = response.body()
if (imageResponse != null) {
previousImage = currentImage
currentImage = imageResponse
showImage(imageResponse)
}
} else {
Toast.makeText(
this@MainActivity,
"Failed to load image (HTTP ${response.code()})",
Toast.LENGTH_SHORT
).show()
}
}
override fun onFailure(call: Call<Helpers.ImageResponse>, t: Throwable) {
t.printStackTrace()
Toast.makeText(
this@MainActivity,
"Failed to load image: ${t.localizedMessage}",
Toast.LENGTH_SHORT
).show()
}
})
}
private fun startImageTimer() {
if (!isImageTimerRunning) {
isImageTimerRunning = true
handler.postDelayed(imageRunnable, (serverSettings.interval * 1000).toLong())
}
}
private fun stopImageTimer() {
isImageTimerRunning = false
handler.removeCallbacks(imageRunnable)
}
private fun startWeatherTimer() {
if (!isWeatherTimerRunning) {
isWeatherTimerRunning = true
handler.post(weatherRunnable)
}
}
private fun stopWeatherTimer() {
isWeatherTimerRunning = false
handler.removeCallbacks(weatherRunnable)
}
private fun startZoomAnimation(imageView: ImageView) {
zoomAnimator?.cancel()
zoomAnimator = ObjectAnimator.ofPropertyValuesHolder(
imageView,
PropertyValuesHolder.ofFloat("scaleX", 1f, 1.2f),
PropertyValuesHolder.ofFloat("scaleY", 1f, 1.2f)
)
zoomAnimator?.duration = (serverSettings.interval * 1000).toLong()
zoomAnimator?.start()
}
private fun getWeather() {
apiService.getWeather().enqueue(object : Callback<Helpers.Weather> {
override fun onResponse(
call: Call<Helpers.Weather>,
response: Response<Helpers.Weather>
) {
if (response.isSuccessful) {
val weatherResponse = response.body()
if (weatherResponse != null) {
currentWeather =
"\n ${weatherResponse.location}, ${"%.1f".format(weatherResponse.temperature)}${weatherResponse.unit} \n ${weatherResponse.description}"
}
}
}
override fun onFailure(call: Call<Helpers.Weather>, t: Throwable) {
Log.e("Weather", "Failed to fetch weather: ${t.message}")
}
})
}
private fun getServerSettings(
onSuccess: (Helpers.ServerSettings) -> Unit,
onFailure: (Throwable) -> Unit,
maxRetries: Int = 36,
retryDelayMillis: Long = 5000
) {
var retryCount = 0
fun attemptFetch() {
if (useWebView) {
return
}
apiService.getServerSettings().enqueue(object : Callback<Helpers.ServerSettings> {
override fun onResponse(
call: Call<Helpers.ServerSettings>,
response: Response<Helpers.ServerSettings>
) {
if (response.isSuccessful) {
val serverSettingsResponse = response.body()
if (serverSettingsResponse != null) {
onSuccess(serverSettingsResponse)
} else {
handleFailure(Exception("Empty response body"))
}
} else {
handleFailure(Exception("HTTP ${response.code()}: ${response.message()}"))
}
}
override fun onFailure(call: Call<Helpers.ServerSettings>, t: Throwable) {
handleFailure(t)
}
private fun handleFailure(t: Throwable) {
if (useWebView) {
return
}
if (retryCount < maxRetries) {
retryCount++
Toast.makeText(
this@MainActivity,
"Retrying to fetch server settings... Attempt $retryCount of $maxRetries",
Toast.LENGTH_SHORT
).show()
Handler(Looper.getMainLooper()).postDelayed({
attemptFetch()
}, retryDelayMillis)
} else {
onFailure(t)
}
}
})
}
attemptFetch()
}
// called when app starts and when user returns from settings screen
@SuppressLint("SetJavaScriptEnabled")
private fun loadSettings() {
val prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext)
blurredBackground = prefs.getBoolean("blurredBackground", true)
showCurrentDate = prefs.getBoolean("showCurrentDate", true)
var savedUrl = prefs.getString("webview_url", "") ?: ""
useWebView = prefs.getBoolean("useWebView", true)
keepScreenOn = prefs.getBoolean("keepScreenOn", true)
val authSecret = prefs.getString("authSecret", "") ?: ""
val screenDim = prefs.getBoolean("screenDim", false)
val settingsLock = prefs.getBoolean("settingsLock", false)
webView.visibility = if (useWebView) View.VISIBLE else View.GONE
imageView1.visibility = if (useWebView) View.GONE else View.VISIBLE
imageView2.visibility = if (useWebView) View.GONE else View.VISIBLE
btnPrevious.visibility = if (useWebView) View.GONE else View.VISIBLE
btnPause.visibility = if (useWebView) View.GONE else View.VISIBLE
btnNext.visibility = if (useWebView) View.GONE else View.VISIBLE
swipeRefreshLayout.isEnabled = !settingsLock
txtPhotoInfo.visibility = View.GONE //enabled in onSettingsLoaded based on server settings
txtDateTime.visibility = View.GONE //enabled in onSettingsLoaded based on server settings
if (keepScreenOn) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
if (screenDim) {
handler.post(dimCheckRunnable)
} else {
handler.removeCallbacks(dimCheckRunnable)
removeDimOverlay()
val lp = WindowManager.LayoutParams()
lp.copyFrom(window.attributes)
lp.screenBrightness = 1f
window.attributes = lp
}
if (useWebView) {
savedUrl = if (authSecret.isNotEmpty()) {
savedUrl.toUri()
.buildUpon()
.appendQueryParameter("authsecret", authSecret)
.build()
.toString()
} else {
savedUrl
}
handler.removeCallbacks(imageRunnable)
handler.removeCallbacks(weatherRunnable)
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
val url = request?.url
if (url != null) {
// Open the URL in the default browser
val intent = Intent(Intent.ACTION_VIEW, url)
startActivity(intent)
return true
}
return false
}
override fun onReceivedError(
view: WebView?,
request: WebResourceRequest?,
error: WebResourceError?
) {
super.onReceivedError(view, request, error)
if (request?.isForMainFrame == true && error != null) {
view?.loadUrl("file:///android_asset/error_page.html")
Handler(Looper.getMainLooper()).postDelayed({
val errorCode = error.errorCode
val errorDescription = error.description.toString().replace("'", "\\'")
view?.evaluateJavascript("showError('$errorCode', '$errorDescription')", null)
}, 500)
}
Handler(Looper.getMainLooper()).postDelayed({
//check url again in case the user has changed it
var currentUrl = prefs.getString("webview_url", "")?.trim() ?: ""
currentUrl = if (authSecret.isNotEmpty()) {
savedUrl.toUri()
.buildUpon()
.appendQueryParameter("authsecret", authSecret)
.build()
.toString()
} else {
currentUrl
}
if (currentUrl.isNotEmpty()) {
webView.loadUrl(currentUrl)
}
}, 5000)
}
}
webView.settings.javaScriptEnabled = true
webView.settings.cacheMode = WebSettings.LOAD_NO_CACHE
webView.settings.domStorageEnabled = true
loadWebViewWithRetry(savedUrl)
} else {
retrofit = Helpers.createRetrofit(savedUrl, authSecret)
apiService = retrofit!!.create(Helpers.ApiService::class.java)
getServerSettings(
onSuccess = { settings ->
serverSettings = settings
onSettingsLoaded()
},
onFailure = { error ->
Toast.makeText(
this,
"Failed to load server settings: ${error.localizedMessage}",
Toast.LENGTH_SHORT
).show()
}
)
}
applyScreenTimeout()
}
private fun onSettingsLoaded() {
if (serverSettings.imageFill) {
imageView1.scaleType = ImageView.ScaleType.CENTER_CROP
imageView2.scaleType = ImageView.ScaleType.CENTER_CROP
} else {
imageView1.scaleType = ImageView.ScaleType.FIT_CENTER
imageView2.scaleType = ImageView.ScaleType.FIT_CENTER
}
if (serverSettings.showPhotoDate || serverSettings.showImageLocation) {
txtPhotoInfo.visibility = View.VISIBLE
txtPhotoInfo.textSize =
Helpers.cssFontSizeToSp(serverSettings.baseFontSize, this)
if (serverSettings.primaryColor != null) {
txtPhotoInfo.setTextColor(
runCatching { serverSettings.primaryColor!!.toColorInt() }
.getOrDefault(Color.WHITE)
)
} else {
txtPhotoInfo.setTextColor(Color.WHITE)
}
}
if (serverSettings.showClock) {
txtDateTime.visibility = View.VISIBLE
txtDateTime.textSize = Helpers.cssFontSizeToSp(serverSettings.baseFontSize, this)
if (serverSettings.primaryColor != null) {
txtDateTime.setTextColor(
runCatching { serverSettings.primaryColor!!.toColorInt() }
.getOrDefault(Color.WHITE)
)
} else {
txtDateTime.setTextColor(Color.WHITE)
}
} else {
txtDateTime.visibility = View.GONE
}
getNextImage()
startImageTimer()
if (serverSettings.showWeatherDescription) {
startWeatherTimer()
}
}
private fun previousAction() {
if (useWebView) {
// Simulate a key press
webView.requestFocus()
val event = KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT)
dispatchKeyEvent(event)
} else {
val safePreviousImage = previousImage
if (safePreviousImage != null) {
stopImageTimer()
showImage(safePreviousImage)
startImageTimer()
}
}
}
private fun nextAction() {
if (useWebView) {
// Simulate a key press
webView.requestFocus()
val event = KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT)
dispatchKeyEvent(event)
} else {
stopImageTimer()
getNextImage()
startImageTimer()
}
}
private fun pauseAction() {
if (useWebView) {
// Simulate a key press
webView.requestFocus()
val event = KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SPACE)
dispatchKeyEvent(event)
} else {
zoomAnimator?.cancel()
if (isImageTimerRunning) {
stopImageTimer()
} else {
getNextImage()
startImageTimer()
}
}
}
private fun settingsAction() {
val intent = Intent(this, SettingsActivity::class.java)
stopImageTimer()
settingsLauncher.launch(intent)
}
private fun screenBrightnessAction(brightness: Float) {
val lp = window.attributes
lp.screenBrightness = brightness
window.attributes = lp
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (event.action == KeyEvent.ACTION_DOWN) {
when (event.keyCode) {
KeyEvent.KEYCODE_DPAD_UP -> {
settingsAction()
return true
}
KeyEvent.KEYCODE_DPAD_CENTER -> {
pauseAction()
return true
}
}
if (!useWebView) {
when (event.keyCode) {
KeyEvent.KEYCODE_DPAD_LEFT -> {
previousAction()
return true
}
KeyEvent.KEYCODE_DPAD_RIGHT -> {
nextAction()
return true
}
KeyEvent.KEYCODE_SPACE -> {
pauseAction()
return true
}
}
}
}
return super.dispatchKeyEvent(event)
}
@SuppressLint("NewApi")
@Suppress("DEPRECATION")
private fun hideSystemUI() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// For API 30 and above
WindowCompat.setDecorFitsSystemWindows(window, false)
window.insetsController?.let { controller ->
controller.hide(WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars())
controller.systemBarsBehavior =
WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
} else {
// For API 21 to 29
window.decorView.systemUiVisibility = (
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
)
}
}
// set screen timeout in Android settings in microseconds
private fun setScreenTimeout(timeout: Int) {
try {
Settings.System.putInt(
contentResolver,
Settings.System.SCREEN_OFF_TIMEOUT,
timeout
)
} catch (e: Exception) {
Log.e("Settings", "Could not set screen timeout: ${e.message}")
}
}
// apply user-entered screen timeout value
private fun applyScreenTimeout() {
val prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext)
if (keepScreenOn) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
val timeoutMinutes = prefs.getString("screenTimeout", "10")?.toIntOrNull() ?: 10
// capture original system timeout once if we haven't yet
if (originalScreenTimeout == -1) {
originalScreenTimeout = Settings.System.getInt(
contentResolver, Settings.System.SCREEN_OFF_TIMEOUT, 30000
)
}
setScreenTimeout(timeoutMinutes * 60 * 1000)
}
}
// show the black overlay and pause activity
private fun applyDimOverlay() {
if (dimOverlay.visibility != View.VISIBLE || dimOverlay.alpha < 0.5f) {
dimOverlay.apply {
visibility = View.VISIBLE
alpha = 0f
if (useWebView) {
webView.loadUrl("about:blank")
} else {
stopImageTimer()
stopWeatherTimer()
}
animate()
.alpha(0.99f)
.setDuration(500L)
.start()
}
// display message to user that screen is going to sleep
Toast.makeText(
this@MainActivity,
"Going to sleep",
Toast.LENGTH_LONG
).show()
}
}
// hide the black overlay and resume activity
private fun removeDimOverlay() {
// remove black overlay and restore webview settings
handler.removeCallbacks(redimRunnable)
if (dimOverlay.isVisible) {
dimOverlay.animate()
.alpha(0f)
.setDuration(500L)
.withEndAction {
dimOverlay.visibility = View.GONE
loadSettings() // Restores WebView and timers
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setShowWhenLocked(false)
}
}
.start()
}
}
@Suppress("DEPRECATION")
private fun screenDim(dim: Boolean) {
if (dim) {
// save user's screen timeout and set to 3s to show "going to sleep" message
if (originalScreenTimeout == -1) {
originalScreenTimeout = Settings.System.getInt(
contentResolver, Settings.System.SCREEN_OFF_TIMEOUT, 30000
)
}
setScreenTimeout(3000)
// create black overlay, set webview to blank to reduce activity, and
// wait for screen to go to sleep after inactivity
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
applyDimOverlay()
} else {
// restore user's screen timeout value
if (originalScreenTimeout != -1) {
setScreenTimeout(originalScreenTimeout)
originalScreenTimeout = -1
}
// acquire WakeLock to turn screen on for short time, just to wake device
// FLAG_KEEP_SCREEN_ON will keep it on afterwards
val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
val wakeLock = powerManager.newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP,
"ImmichFrame:WakeLockTag"
)
wakeLock.acquire(10 * 1000L) // 10 second timeout
wakeLock.release()
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
removeDimOverlay()
// turn screen back on, dismissing keyguard lockscreen
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setShowWhenLocked(true)
setTurnScreenOn(true)
val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
keyguardManager.requestDismissKeyguard(this, null)
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
keyguardManager.requestDismissKeyguard(this, null)
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON or
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED)
} else {
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON or
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD)
}
}
}
private fun checkDimTime() {
val prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext)
val startHour = prefs.getInt("dimStartHour", 22)
val startMinute = prefs.getInt("dimStartMinute", 0)
val endHour = prefs.getInt("dimEndHour", 6)
val endMinute = prefs.getInt("dimEndMinute", 0)
val now = Calendar.getInstance()
val nowMinutes = now.get(Calendar.HOUR_OF_DAY) * 60 + now.get(Calendar.MINUTE)
val startMinutes = startHour * 60 + startMinute
val endMinutes = endHour * 60 + endMinute
val shouldDim =
if (startMinutes < endMinutes) {
nowMinutes in startMinutes until endMinutes
} else {
nowMinutes !in endMinutes until startMinutes
}
val isOverlayVisible = dimOverlay.isVisible
if (shouldDim && !isOverlayVisible && !isSnoozing) {
isSnoozing = false
screenDim(true)
} else if (!shouldDim && isOverlayVisible) {
isSnoozing = false
screenDim(false)
}
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) {
hideSystemUI()
}
}
// called when user returns to app
override fun onResume() {
super.onResume()
// if we are already in dim state, but screen just woke up,
// hide overlay and schedule screen to re-dim in 30 seconds
if (dimOverlay.isVisible) {
isSnoozing = true
setScreenTimeout(40000)
removeDimOverlay()
handler.postDelayed(redimRunnable, 30000)
} else {
applyScreenTimeout()
}
hideSystemUI()
}
// called when app is closed
override fun onDestroy() {
super.onDestroy()
rcpServer.stop()
handler.removeCallbacksAndMessages(null)
// restore timeout if we changed it
if (originalScreenTimeout != -1) {
setScreenTimeout(originalScreenTimeout)
}
}
private fun loadWebViewWithRetry(
url: String,
attempt: Int = 1,
maxAttempts: Int = 36
) {
lifecycleScope.launch {
val reachable = withContext(Dispatchers.IO) {
Helpers.isServerReachable(url)
}
if (reachable) {
webView.loadUrl(url)
} else if (attempt <= maxAttempts) {
Toast.makeText(