/
MuzeiWatchFace.kt
661 lines (604 loc) · 27.4 KB
/
MuzeiWatchFace.kt
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
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.support.wearable.complications.ComplicationData
import android.support.wearable.complications.SystemProviders
import android.support.wearable.complications.rendering.ComplicationDrawable
import android.support.wearable.watchface.CanvasWatchFaceService
import android.support.wearable.watchface.WatchFaceService
import android.support.wearable.watchface.WatchFaceStyle
import android.text.format.DateFormat
import android.util.Log
import android.view.Gravity
import android.view.SurfaceHolder
import androidx.core.content.edit
import androidx.core.content.res.ResourcesCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.lifecycleScope
import androidx.preference.PreferenceManager
import com.google.android.apps.muzei.complications.ArtworkComplicationProviderService
import com.google.android.apps.muzei.datalayer.ActivateMuzeiReceiver
import com.google.android.apps.muzei.featuredart.BuildConfig.FEATURED_ART_AUTHORITY
import com.google.android.apps.muzei.render.ImageLoader
import com.google.android.apps.muzei.room.Artwork
import com.google.android.apps.muzei.room.MuzeiDatabase
import com.google.android.apps.muzei.room.contentUri
import com.google.android.apps.muzei.sync.ProviderManager
import com.google.android.apps.muzei.util.ImageBlurrer
import com.google.android.apps.muzei.util.blur
import com.google.android.apps.muzei.util.collectIn
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.ktx.Firebase
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.launch
import net.nurik.roman.muzei.BuildConfig
import net.nurik.roman.muzei.R
import java.io.FileNotFoundException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import java.util.TimeZone
import java.util.concurrent.TimeUnit
import kotlin.math.max
import kotlin.math.min
/**
* Default watch face for Muzei, showing the current time atop the current artwork. In ambient
* mode, the artwork is invisible. On devices with low-bit ambient mode, the text is drawn without
* anti-aliasing in ambient mode. On devices which require burn-in protection, the hours are drawn
* with a thinner font.
*/
class MuzeiWatchFace : CanvasWatchFaceService(), LifecycleOwner {
companion object {
private const val TAG = "MuzeiWatchFace"
internal const val TOP_COMPLICATION_ID = 0
internal const val BOTTOM_COMPLICATION_ID = 1
/**
* Preference key for saving whether the watch face is blurred
*/
private const val BLURRED_PREF_KEY = "BLURRED"
/**
* Update rate in milliseconds.
*/
private val UPDATE_RATE_MS = TimeUnit.MINUTES.toMillis(1)
internal const val MSG_UPDATE_TIME = 0
}
private val lifecycleRegistry = LifecycleRegistry(this)
override fun getLifecycle(): Lifecycle {
return lifecycleRegistry
}
override fun onCreate() {
super.onCreate()
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
Firebase.analytics.setUserProperty("device_type", BuildConfig.DEVICE_TYPE)
ProviderManager.getInstance(this).observe(this) { provider ->
if (provider == null) {
val context = this@MuzeiWatchFace
lifecycleScope.launch(NonCancellable) {
ProviderManager.select(context, FEATURED_ART_AUTHORITY)
ActivateMuzeiReceiver.checkForPhoneApp(context)
}
}
}
ProviderChangedReceiver.observeForVisibility(this, this)
}
override fun onCreateEngine(): CanvasWatchFaceService.Engine {
return Engine()
}
override fun onDestroy() {
super.onDestroy()
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
}
private inner class Engine : CanvasWatchFaceService.Engine() {
val timeZoneReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
calendar.timeZone = TimeZone.getDefault()
invalidate()
}
}
val localeChangedReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
recomputeDateFormat()
invalidate()
}
}
var registeredTimeZoneReceiver = false
var registeredLocaleChangedReceiver = false
val backgroundPaint: Paint = Paint().apply {
color = Color.BLACK
}
val heavyTypeface: Typeface? by lazy {
ResourcesCompat.getFont(this@MuzeiWatchFace, R.font.nunito_clock_bold)
}
val lightTypeface: Typeface? by lazy {
ResourcesCompat.getFont(this@MuzeiWatchFace, R.font.nunito_clock_regular)
}
val densityMultiplier = resources.displayMetrics.density
lateinit var clockPaint: Paint
lateinit var clockAmbientShadowPaint: Paint
var clockTextHeight: Float = 0f
lateinit var datePaint: Paint
lateinit var dateAmbientShadowPaint: Paint
var dateTextHeight: Float = 0f
lateinit var timeFormat12h: SimpleDateFormat
lateinit var timeFormat24h: SimpleDateFormat
lateinit var dateFormat: SimpleDateFormat
var topComplication: ComplicationDrawable? = null
var bottomComplication: ComplicationDrawable? = null
private val drawableCallback = object : Drawable.Callback {
override fun invalidateDrawable(who: Drawable) {
invalidate()
}
override fun scheduleDrawable(who: Drawable, what: Runnable, `when`: Long) {
}
override fun unscheduleDrawable(who: Drawable, what: Runnable) {
}
}
/**
* Handler to update the time periodically in interactive mode.
*/
val updateTimeHandler: Handler = @SuppressLint("HandlerLeak")
object : Handler(Looper.getMainLooper()) {
override fun handleMessage(message: Message) {
when (message.what) {
MSG_UPDATE_TIME -> {
invalidate()
if (isVisible) {
val timeMs = System.currentTimeMillis()
val delayMs = UPDATE_RATE_MS - timeMs % UPDATE_RATE_MS
this.sendEmptyMessageDelayed(MSG_UPDATE_TIME, delayMs)
}
}
}
}
}
var backgroundScaledBlurredBitmap: Bitmap? = null
var backgroundScaledBitmap: Bitmap? = null
var backgroundBitmap: Bitmap? = null
val clockMargin: Float by lazy {
resources.getDimension(R.dimen.clock_margin)
}
val dateMinAvailableMargin: Float by lazy {
resources.getDimension(R.dimen.date_min_available_margin)
}
val complicationMaxHeight: Float by lazy {
resources.getDimension(R.dimen.complication_max_height)
}
var ambient: Boolean = false
val calendar: Calendar = Calendar.getInstance()
var cardBounds = Rect()
var currentWidth = 0
var currentHeight = 0
/**
* Whether the display supports fewer bits for each color in ambient mode. When true, we
* disable anti-aliasing in ambient mode.
*/
var lowBitAmbient: Boolean = false
lateinit var tapAction: String
var blurred: Boolean = false
private suspend fun loadImage(artwork: Artwork?) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Artwork = ${artwork?.contentUri}")
}
val bitmap: Bitmap? = try {
artwork?.run {
ImageLoader.decode(contentResolver, contentUri)
}
} catch (e: FileNotFoundException) {
Log.w(TAG, "Could not find current artwork image", e)
null
}
if (bitmap != null && !bitmap.sameAs(backgroundBitmap)) {
backgroundBitmap = bitmap
createScaledBitmap()
postInvalidate()
}
}
override fun onCreate(holder: SurfaceHolder) {
super.onCreate(holder)
Firebase.analytics.logEvent("watchface_created", null)
val database = MuzeiDatabase.getInstance(this@MuzeiWatchFace)
database.artworkDao().currentArtwork.collectIn(this@MuzeiWatchFace) { artwork ->
loadImage(artwork)
}
clockPaint = Paint().apply {
color = Color.WHITE
setShadowLayer(1f * densityMultiplier, 0f, 0.5f * densityMultiplier,
-0x34000000)
isAntiAlias = true
typeface = heavyTypeface
textAlign = Paint.Align.CENTER
textSize = resources.getDimension(R.dimen.clock_text_size)
}
recomputeClockTextHeight()
clockAmbientShadowPaint = Paint(clockPaint).apply {
color = Color.TRANSPARENT
setShadowLayer(6f * densityMultiplier, 0f, 2f * densityMultiplier,
0x66000000)
}
datePaint = Paint().apply {
color = Color.WHITE
setShadowLayer(1f * densityMultiplier, 0f, 0.5f * densityMultiplier,
-0x34000000)
isAntiAlias = true
typeface = lightTypeface
textAlign = Paint.Align.CENTER
textSize = resources.getDimension(R.dimen.date_text_size)
}
val fm = datePaint.fontMetrics
dateTextHeight = -fm.top
dateAmbientShadowPaint = Paint(datePaint).apply {
color = Color.TRANSPARENT
setShadowLayer(4f * densityMultiplier, 0f, 2f * densityMultiplier,
0x66000000)
}
recomputeDateFormat()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(
this@MuzeiWatchFace)
val showDate = sharedPreferences.getBoolean(
ConfigActivity.SHOW_DATE_PREFERENCE_KEY, true)
if (showDate) {
setDefaultSystemComplicationProvider(TOP_COMPLICATION_ID, SystemProviders.DATE,
ComplicationData.TYPE_SHORT_TEXT)
}
setDefaultComplicationProvider(BOTTOM_COMPLICATION_ID,
ComponentName(this@MuzeiWatchFace,
ArtworkComplicationProviderService::class.java),
ComplicationData.TYPE_LONG_TEXT)
setActiveComplications(TOP_COMPLICATION_ID, BOTTOM_COMPLICATION_ID)
topComplication = (getDrawable(R.drawable.complication)
as ComplicationDrawable).apply {
setContext(this@MuzeiWatchFace)
}
bottomComplication = (getDrawable(R.drawable.complication)
as ComplicationDrawable).apply {
setContext(this@MuzeiWatchFace)
}
listOfNotNull(topComplication, bottomComplication).forEach {
it.callback = drawableCallback
}
}
updateBlurredStatus()
}
private fun updateBlurredStatus() {
val preferences = PreferenceManager.getDefaultSharedPreferences(this@MuzeiWatchFace)
tapAction = preferences.getString(ConfigActivity.TAP_PREFERENCE_KEY,
null) ?: getString(R.string.config_tap_default)
blurred = when(tapAction) {
"always" -> true
"never" -> false
else -> preferences.getBoolean(BLURRED_PREF_KEY, false)
}
updateWatchFaceStyle()
}
private fun recomputeClockTextHeight() {
val fm = clockPaint.fontMetrics
clockTextHeight = -fm.top
}
private fun recomputeDateFormat() {
timeFormat12h = SimpleDateFormat("h:mm", Locale.getDefault())
timeFormat24h = SimpleDateFormat("H:mm", Locale.getDefault())
val bestPattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), "Md")
dateFormat = SimpleDateFormat(bestPattern, Locale.getDefault())
}
@Suppress("DEPRECATION")
private fun updateWatchFaceStyle() {
setWatchFaceStyle(WatchFaceStyle.Builder(this@MuzeiWatchFace)
.setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_INTERRUPTIVE)
.setCardPeekMode(WatchFaceStyle.PEEK_MODE_VARIABLE)
.setPeekOpacityMode(if (blurred)
WatchFaceStyle.PEEK_OPACITY_MODE_TRANSLUCENT
else
WatchFaceStyle.PEEK_OPACITY_MODE_OPAQUE)
.setStatusBarGravity(Gravity.TOP or Gravity.START)
.setHotwordIndicatorGravity(Gravity.TOP or Gravity.START)
.setViewProtectionMode(if (blurred)
0
else
WatchFaceStyle.PROTECT_HOTWORD_INDICATOR or WatchFaceStyle.PROTECT_STATUS_BAR)
.setAcceptsTapEvents(true)
.build())
listOfNotNull(topComplication, bottomComplication).forEach {
it.setBackgroundColorActive(if (blurred) Color.TRANSPARENT else 0x66000000)
}
invalidate()
}
override fun onDestroy() {
Firebase.analytics.logEvent("watchface_destroyed", null)
updateTimeHandler.removeMessages(MSG_UPDATE_TIME)
super.onDestroy()
}
override fun onSurfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
super.onSurfaceChanged(holder, format, width, height)
currentWidth = width
currentHeight = height
createScaledBitmap()
}
private fun createScaledBitmap() {
if (currentWidth == 0 || currentHeight == 0) {
// Wait for the surface to be created
return
}
val background = backgroundBitmap ?: return
val scaleHeightFactor = currentHeight * 1f / background.height
val scaleWidthFactor = currentWidth * 1f / background.width
// Use the larger scale factor to ensure that we center crop and don't show any
// black bars (rather than use the minimum and scale down to see the whole image)
val scalingFactor = max(scaleHeightFactor, scaleWidthFactor)
backgroundScaledBitmap = Bitmap.createScaledBitmap(
background,
(scalingFactor * background.width).toInt(),
(scalingFactor * background.height).toInt(),
true /* filter */)
backgroundScaledBlurredBitmap = backgroundScaledBitmap.blur(this@MuzeiWatchFace,
(ImageBlurrer.MAX_SUPPORTED_BLUR_PIXELS / 2).toFloat())
}
override fun onVisibilityChanged(visible: Boolean) {
super.onVisibilityChanged(visible)
if (BuildConfig.DEBUG) {
Log.d(TAG, "onVisibilityChanged: visible = $visible")
}
if (visible) {
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
registerReceiver()
// Update time zone in case it changed while we weren't visible.
calendar.timeZone = TimeZone.getDefault()
// Update the blurred status in case the preference has changed
updateBlurredStatus()
updateTimeHandler.sendEmptyMessage(MSG_UPDATE_TIME)
} else {
lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
updateTimeHandler.removeMessages(MSG_UPDATE_TIME)
unregisterReceiver()
}
}
private fun registerReceiver() {
if (registeredTimeZoneReceiver) {
return
}
registeredTimeZoneReceiver = true
val filter = IntentFilter(Intent.ACTION_TIMEZONE_CHANGED)
this@MuzeiWatchFace.registerReceiver(timeZoneReceiver, filter)
registeredLocaleChangedReceiver = true
val localeFilter = IntentFilter(Intent.ACTION_LOCALE_CHANGED)
this@MuzeiWatchFace.registerReceiver(localeChangedReceiver, localeFilter)
}
private fun unregisterReceiver() {
if (registeredTimeZoneReceiver) {
registeredTimeZoneReceiver = false
this@MuzeiWatchFace.unregisterReceiver(timeZoneReceiver)
}
if (registeredLocaleChangedReceiver) {
registeredLocaleChangedReceiver = false
this@MuzeiWatchFace.unregisterReceiver(localeChangedReceiver)
}
}
override fun onPropertiesChanged(properties: Bundle) {
super.onPropertiesChanged(properties)
val burnInProtection = properties.getBoolean(WatchFaceService.PROPERTY_BURN_IN_PROTECTION, false)
val textTypeface = if (burnInProtection) lightTypeface else heavyTypeface
clockPaint.typeface = textTypeface
clockAmbientShadowPaint.typeface = textTypeface
recomputeClockTextHeight()
lowBitAmbient = properties.getBoolean(WatchFaceService.PROPERTY_LOW_BIT_AMBIENT, false)
listOfNotNull(topComplication, bottomComplication).forEach {
it.setBurnInProtection(burnInProtection)
it.setLowBitAmbient(lowBitAmbient)
}
invalidate()
if (BuildConfig.DEBUG) {
Log.d(TAG, "onPropertiesChanged: burn-in protection = $burnInProtection, " +
"low-bit ambient = $lowBitAmbient")
}
}
@Suppress("OverridingDeprecatedMember", "DEPRECATION")
override fun onPeekCardPositionUpdate(bounds: Rect) {
super.onPeekCardPositionUpdate(bounds)
if (bounds != cardBounds) {
cardBounds.set(bounds)
if (BuildConfig.DEBUG) {
Log.d(TAG, "onPeekCardPositionUpdate: $cardBounds")
}
invalidate()
}
}
override fun onTimeTick() {
super.onTimeTick()
invalidate()
}
override fun onComplicationDataUpdate(watchFaceComplicationId: Int, data: ComplicationData?) {
when (watchFaceComplicationId) {
TOP_COMPLICATION_ID -> {
topComplication?.setComplicationData(data)
}
BOTTOM_COMPLICATION_ID -> {
bottomComplication?.setComplicationData(data)
}
}
invalidate()
}
override fun onTapCommand(@TapType tapType: Int, x: Int, y: Int, eventTime: Long) {
when (tapType) {
WatchFaceService.TAP_TYPE_TAP -> {
when {
topComplication?.onTap(x, y) == true -> {
invalidate()
}
bottomComplication?.onTap(x, y) == true -> {
invalidate()
}
tapAction == "toggle" -> {
blurred = !blurred
val preferences = PreferenceManager.getDefaultSharedPreferences(this@MuzeiWatchFace)
preferences.edit { putBoolean(BLURRED_PREF_KEY, blurred) }
updateWatchFaceStyle()
invalidate()
}
}
}
else -> super.onTapCommand(tapType, x, y, eventTime)
}
}
override fun onAmbientModeChanged(inAmbientMode: Boolean) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "onAmbientModeChanged: $inAmbientMode")
}
super.onAmbientModeChanged(inAmbientMode)
if (ambient != inAmbientMode) {
ambient = inAmbientMode
if (lowBitAmbient) {
val antiAlias = !inAmbientMode
clockPaint.isAntiAlias = antiAlias
clockAmbientShadowPaint.isAntiAlias = antiAlias
datePaint.isAntiAlias = antiAlias
dateAmbientShadowPaint.isAntiAlias = antiAlias
}
listOfNotNull(topComplication, bottomComplication).forEach {
it.setInAmbientMode(ambient)
}
invalidate()
}
}
override fun onDraw(canvas: Canvas, bounds: Rect) {
calendar.timeInMillis = System.currentTimeMillis()
val width = canvas.width
val height = canvas.height
// Draw the background
val background = if (blurred)
backgroundScaledBlurredBitmap
else
backgroundScaledBitmap
if (ambient || background == null) {
canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), backgroundPaint)
} else {
// Draw the scaled background
canvas.drawBitmap(background,
((width - background.width) / 2).toFloat(),
((height - background.height) / 2).toFloat(), null)
if (blurred) {
canvas.drawColor(Color.argb(68, 0, 0, 0))
}
}
// Draw the time
val formattedTime = if (DateFormat.is24HourFormat(this@MuzeiWatchFace))
timeFormat24h.format(calendar.time)
else
timeFormat12h.format(calendar.time)
val xOffset = width / 2f
val yOffset = min((height + clockTextHeight) / 2, (if (cardBounds.top == 0) height else cardBounds.top) - clockMargin)
if (!blurred) {
canvas.drawText(formattedTime,
xOffset,
yOffset,
clockAmbientShadowPaint)
}
canvas.drawText(formattedTime,
xOffset,
yOffset,
clockPaint)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
topComplication?.run {
val (top, bottom) = run {
var top = clockMargin.toInt()
var bottom = ((height - clockTextHeight - clockMargin) / 2).toInt()
val maxHeight = bottom - top
if (maxHeight > complicationMaxHeight.toInt()) {
val difference = maxHeight - complicationMaxHeight.toInt()
top += difference / 2
bottom -= difference / 2
}
Pair(top, bottom)
}
val complicationHeight = bottom - top
setBounds((canvas.width - complicationHeight) / 2, top,
(canvas.width + complicationHeight) / 2, bottom)
draw(canvas, calendar.timeInMillis)
}
} else {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(
this@MuzeiWatchFace)
val showDate = sharedPreferences.getBoolean(
ConfigActivity.SHOW_DATE_PREFERENCE_KEY, true)
// If no card is visible, we have the entire screen.
// Otherwise, only the space above the card is available
val spaceAvailable = (if (cardBounds.top == 0) height else cardBounds.top).toFloat()
// Compute the height of the clock and date
val clockHeight = clockTextHeight + clockMargin
val dateHeight = dateTextHeight + clockMargin
// Only show the date if the height of the clock + date + margin fits in the
// available space Otherwise it may be obstructed by an app icon (square)
// or unread notification / charging indicator (round)
if (showDate &&
clockHeight + dateHeight + dateMinAvailableMargin < spaceAvailable) {
// Draw the date
val formattedDate = dateFormat.format(calendar.time)
val yDateOffset = yOffset - clockTextHeight - clockMargin // date above centered time
if (!blurred) {
canvas.drawText(formattedDate,
xOffset,
yDateOffset,
dateAmbientShadowPaint)
}
canvas.drawText(formattedDate,
xOffset,
yDateOffset,
datePaint)
}
}
// Draw the bottom complication
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
bottomComplication?.run {
val (top, bottom) = run {
var top = ((height + clockTextHeight + clockMargin) / 2).toInt()
var bottom = height - clockMargin.toInt()
val maxHeight = bottom - top
if (maxHeight > complicationMaxHeight.toInt()) {
val difference = maxHeight - complicationMaxHeight.toInt()
top += difference / 2
bottom -= difference / 2
}
Pair(top, bottom)
}
val complicationHeight = bottom - top
val complicationWidth = (2.75f * complicationHeight).toInt()
setBounds((canvas.width - complicationWidth) / 2, top,
(canvas.width + complicationWidth) / 2, bottom)
draw(canvas, calendar.timeInMillis)
}
}
}
}
}