-
Notifications
You must be signed in to change notification settings - Fork 553
/
AnalogWatchCanvasRenderer.kt
521 lines (462 loc) · 20.5 KB
/
AnalogWatchCanvasRenderer.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
/*
* Copyright 2020 The Android Open Source Project
*
* 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
*
* https://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.example.android.wearable.alpha
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.Rect
import android.util.Log
import android.view.SurfaceHolder
import androidx.core.graphics.withRotation
import androidx.core.graphics.withScale
import androidx.wear.watchface.ComplicationSlotsManager
import androidx.wear.watchface.DrawMode
import androidx.wear.watchface.Renderer
import androidx.wear.watchface.WatchState
import androidx.wear.watchface.complications.rendering.CanvasComplicationDrawable
import androidx.wear.watchface.complications.rendering.ComplicationDrawable
import androidx.wear.watchface.style.CurrentUserStyleRepository
import androidx.wear.watchface.style.UserStyle
import androidx.wear.watchface.style.UserStyleSetting
import androidx.wear.watchface.style.WatchFaceLayer
import com.example.android.wearable.alpha.data.watchface.ColorStyleIdAndResourceIds
import com.example.android.wearable.alpha.data.watchface.WatchFaceColorPalette.Companion.convertToWatchFaceColorPalette
import com.example.android.wearable.alpha.data.watchface.WatchFaceData
import com.example.android.wearable.alpha.utils.COLOR_STYLE_SETTING
import com.example.android.wearable.alpha.utils.DRAW_HOUR_PIPS_STYLE_SETTING
import com.example.android.wearable.alpha.utils.WATCH_HAND_LENGTH_STYLE_SETTING
import java.time.Duration
import java.time.ZonedDateTime
import kotlin.math.cos
import kotlin.math.sin
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
// Default for how long each frame is displayed at expected frame rate.
private const val FRAME_PERIOD_MS_DEFAULT: Long = 16L
/**
* Renders watch face via data in Room database. Also, updates watch face state based on setting
* changes by user via [userStyleRepository.addUserStyleListener()].
*/
class AnalogWatchCanvasRenderer(
private val context: Context,
surfaceHolder: SurfaceHolder,
watchState: WatchState,
private val complicationSlotsManager: ComplicationSlotsManager,
currentUserStyleRepository: CurrentUserStyleRepository,
canvasType: Int
) : Renderer.CanvasRenderer2<AnalogWatchCanvasRenderer.AnalogSharedAssets>(
surfaceHolder,
currentUserStyleRepository,
watchState,
canvasType,
FRAME_PERIOD_MS_DEFAULT,
clearWithBackgroundTintBeforeRenderingHighlightLayer = false
) {
class AnalogSharedAssets : SharedAssets {
override fun onDestroy() {
}
}
private val scope: CoroutineScope =
CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
// Represents all data needed to render the watch face. All value defaults are constants. Only
// three values are changeable by the user (color scheme, ticks being rendered, and length of
// the minute arm). Those dynamic values are saved in the watch face APIs and we update those
// here (in the renderer) through a Kotlin Flow.
private var watchFaceData: WatchFaceData = WatchFaceData()
// Converts resource ids into Colors and ComplicationDrawable.
private var watchFaceColors = convertToWatchFaceColorPalette(
context,
watchFaceData.activeColorStyle,
watchFaceData.ambientColorStyle
)
// Initializes paint object for painting the clock hands with default values.
private val clockHandPaint = Paint().apply {
isAntiAlias = true
strokeWidth =
context.resources.getDimensionPixelSize(R.dimen.clock_hand_stroke_width).toFloat()
}
private val outerElementPaint = Paint().apply {
isAntiAlias = true
}
// Used to paint the main hour hand text with the hour pips, i.e., 3, 6, 9, and 12 o'clock.
private val textPaint = Paint().apply {
isAntiAlias = true
textSize = context.resources.getDimensionPixelSize(R.dimen.hour_mark_size).toFloat()
}
private lateinit var hourHandFill: Path
private lateinit var hourHandBorder: Path
private lateinit var minuteHandFill: Path
private lateinit var minuteHandBorder: Path
private lateinit var secondHand: Path
// Changed when setting changes cause a change in the minute hand arm (triggered by user in
// updateUserStyle() via userStyleRepository.addUserStyleListener()).
private var armLengthChangedRecalculateClockHands: Boolean = false
// Default size of watch face drawing area, that is, a no size rectangle. Will be replaced with
// valid dimensions from the system.
private var currentWatchFaceSize = Rect(0, 0, 0, 0)
init {
scope.launch {
currentUserStyleRepository.userStyle.collect { userStyle ->
updateWatchFaceData(userStyle)
}
}
}
override suspend fun createSharedAssets(): AnalogSharedAssets {
return AnalogSharedAssets()
}
/*
* Triggered when the user makes changes to the watch face through the settings activity. The
* function is called by a flow.
*/
private fun updateWatchFaceData(userStyle: UserStyle) {
Log.d(TAG, "updateWatchFace(): $userStyle")
var newWatchFaceData: WatchFaceData = watchFaceData
// Loops through user style and applies new values to watchFaceData.
for (options in userStyle) {
when (options.key.id.toString()) {
COLOR_STYLE_SETTING -> {
val listOption = options.value as
UserStyleSetting.ListUserStyleSetting.ListOption
newWatchFaceData = newWatchFaceData.copy(
activeColorStyle = ColorStyleIdAndResourceIds.getColorStyleConfig(
listOption.id.toString()
)
)
}
DRAW_HOUR_PIPS_STYLE_SETTING -> {
val booleanValue = options.value as
UserStyleSetting.BooleanUserStyleSetting.BooleanOption
newWatchFaceData = newWatchFaceData.copy(
drawHourPips = booleanValue.value
)
}
WATCH_HAND_LENGTH_STYLE_SETTING -> {
val doubleValue = options.value as
UserStyleSetting.DoubleRangeUserStyleSetting.DoubleRangeOption
// The arm lengths are usually only calculated the first time the watch face is
// loaded to reduce the ops in the onDraw(). Because we updated the minute hand
// watch length, we need to trigger a recalculation.
armLengthChangedRecalculateClockHands = true
// Updates length of minute hand based on edits from user.
val newMinuteHandDimensions = newWatchFaceData.minuteHandDimensions.copy(
lengthFraction = doubleValue.value.toFloat()
)
newWatchFaceData = newWatchFaceData.copy(
minuteHandDimensions = newMinuteHandDimensions
)
}
}
}
// Only updates if something changed.
if (watchFaceData != newWatchFaceData) {
watchFaceData = newWatchFaceData
// Recreates Color and ComplicationDrawable from resource ids.
watchFaceColors = convertToWatchFaceColorPalette(
context,
watchFaceData.activeColorStyle,
watchFaceData.ambientColorStyle
)
// Applies the user chosen complication color scheme changes. ComplicationDrawables for
// each of the styles are defined in XML so we need to replace the complication's
// drawables.
for ((_, complication) in complicationSlotsManager.complicationSlots) {
ComplicationDrawable.getDrawable(
context,
watchFaceColors.complicationStyleDrawableId
)?.let {
(complication.renderer as CanvasComplicationDrawable).drawable = it
}
}
}
}
override fun onDestroy() {
Log.d(TAG, "onDestroy()")
scope.cancel("AnalogWatchCanvasRenderer scope clear() request")
super.onDestroy()
}
override fun renderHighlightLayer(
canvas: Canvas,
bounds: Rect,
zonedDateTime: ZonedDateTime,
sharedAssets: AnalogSharedAssets
) {
canvas.drawColor(renderParameters.highlightLayer!!.backgroundTint)
for ((_, complication) in complicationSlotsManager.complicationSlots) {
if (complication.enabled) {
complication.renderHighlightLayer(canvas, zonedDateTime, renderParameters)
}
}
}
override fun render(
canvas: Canvas,
bounds: Rect,
zonedDateTime: ZonedDateTime,
sharedAssets: AnalogSharedAssets
) {
val backgroundColor = if (renderParameters.drawMode == DrawMode.AMBIENT) {
watchFaceColors.ambientBackgroundColor
} else {
watchFaceColors.activeBackgroundColor
}
canvas.drawColor(backgroundColor)
// CanvasComplicationDrawable already obeys rendererParameters.
drawComplications(canvas, zonedDateTime)
if (renderParameters.watchFaceLayers.contains(WatchFaceLayer.COMPLICATIONS_OVERLAY)) {
drawClockHands(canvas, bounds, zonedDateTime)
}
if (renderParameters.drawMode == DrawMode.INTERACTIVE &&
renderParameters.watchFaceLayers.contains(WatchFaceLayer.BASE) &&
watchFaceData.drawHourPips
) {
drawNumberStyleOuterElement(
canvas,
bounds,
watchFaceData.numberRadiusFraction,
watchFaceData.numberStyleOuterCircleRadiusFraction,
watchFaceColors.activeOuterElementColor,
watchFaceData.numberStyleOuterCircleRadiusFraction,
watchFaceData.gapBetweenOuterCircleAndBorderFraction
)
}
}
// ----- All drawing functions -----
private fun drawComplications(canvas: Canvas, zonedDateTime: ZonedDateTime) {
for ((_, complication) in complicationSlotsManager.complicationSlots) {
if (complication.enabled) {
complication.render(canvas, zonedDateTime, renderParameters)
}
}
}
private fun drawClockHands(
canvas: Canvas,
bounds: Rect,
zonedDateTime: ZonedDateTime
) {
// Only recalculate bounds (watch face size/surface) has changed or the arm of one of the
// clock hands has changed (via user input in the settings).
// NOTE: Watch face surface usually only updates one time (when the size of the device is
// initially broadcasted).
if (currentWatchFaceSize != bounds || armLengthChangedRecalculateClockHands) {
armLengthChangedRecalculateClockHands = false
currentWatchFaceSize = bounds
recalculateClockHands(bounds)
}
// Retrieve current time to calculate location/rotation of watch arms.
val secondOfDay = zonedDateTime.toLocalTime().toSecondOfDay()
// Determine the rotation of the hour and minute hand.
// Determine how many seconds it takes to make a complete rotation for each hand
// It takes the hour hand 12 hours to make a complete rotation
val secondsPerHourHandRotation = Duration.ofHours(12).seconds
// It takes the minute hand 1 hour to make a complete rotation
val secondsPerMinuteHandRotation = Duration.ofHours(1).seconds
// Determine the angle to draw each hand expressed as an angle in degrees from 0 to 360
// Since each hand does more than one cycle a day, we are only interested in the remainder
// of the secondOfDay modulo the hand interval
val hourRotation = secondOfDay.rem(secondsPerHourHandRotation) * 360.0f /
secondsPerHourHandRotation
val minuteRotation = secondOfDay.rem(secondsPerMinuteHandRotation) * 360.0f /
secondsPerMinuteHandRotation
canvas.withScale(
x = WATCH_HAND_SCALE,
y = WATCH_HAND_SCALE,
pivotX = bounds.exactCenterX(),
pivotY = bounds.exactCenterY()
) {
val drawAmbient = renderParameters.drawMode == DrawMode.AMBIENT
clockHandPaint.style = if (drawAmbient) Paint.Style.STROKE else Paint.Style.FILL
clockHandPaint.color = if (drawAmbient) {
watchFaceColors.ambientPrimaryColor
} else {
watchFaceColors.activePrimaryColor
}
// Draw hour hand.
withRotation(hourRotation, bounds.exactCenterX(), bounds.exactCenterY()) {
drawPath(hourHandBorder, clockHandPaint)
}
// Draw minute hand.
withRotation(minuteRotation, bounds.exactCenterX(), bounds.exactCenterY()) {
drawPath(minuteHandBorder, clockHandPaint)
}
// Draw second hand if not in ambient mode
if (!drawAmbient) {
clockHandPaint.color = watchFaceColors.activeSecondaryColor
// Second hand has a different color style (secondary color) and is only drawn in
// active mode, so we calculate it here (not above with others).
val secondsPerSecondHandRotation = Duration.ofMinutes(1).seconds
val secondsRotation = secondOfDay.rem(secondsPerSecondHandRotation) * 360.0f /
secondsPerSecondHandRotation
clockHandPaint.color = watchFaceColors.activeSecondaryColor
withRotation(secondsRotation, bounds.exactCenterX(), bounds.exactCenterY()) {
drawPath(secondHand, clockHandPaint)
}
}
}
}
/*
* Rarely called (only when watch face surface changes; usually only once) from the
* drawClockHands() method.
*/
private fun recalculateClockHands(bounds: Rect) {
Log.d(TAG, "recalculateClockHands()")
hourHandBorder =
createClockHand(
bounds,
watchFaceData.hourHandDimensions.lengthFraction,
watchFaceData.hourHandDimensions.widthFraction,
watchFaceData.gapBetweenHandAndCenterFraction,
watchFaceData.hourHandDimensions.xRadiusRoundedCorners,
watchFaceData.hourHandDimensions.yRadiusRoundedCorners
)
hourHandFill = hourHandBorder
minuteHandBorder =
createClockHand(
bounds,
watchFaceData.minuteHandDimensions.lengthFraction,
watchFaceData.minuteHandDimensions.widthFraction,
watchFaceData.gapBetweenHandAndCenterFraction,
watchFaceData.minuteHandDimensions.xRadiusRoundedCorners,
watchFaceData.minuteHandDimensions.yRadiusRoundedCorners
)
minuteHandFill = minuteHandBorder
secondHand =
createClockHand(
bounds,
watchFaceData.secondHandDimensions.lengthFraction,
watchFaceData.secondHandDimensions.widthFraction,
watchFaceData.gapBetweenHandAndCenterFraction,
watchFaceData.secondHandDimensions.xRadiusRoundedCorners,
watchFaceData.secondHandDimensions.yRadiusRoundedCorners
)
}
/**
* Returns a round rect clock hand if {@code rx} and {@code ry} equals to 0, otherwise return a
* rect clock hand.
*
* @param bounds The bounds use to determine the coordinate of the clock hand.
* @param length Clock hand's length, in fraction of {@code bounds.width()}.
* @param thickness Clock hand's thickness, in fraction of {@code bounds.width()}.
* @param gapBetweenHandAndCenter Gap between inner side of arm and center.
* @param roundedCornerXRadius The x-radius of the rounded corners on the round-rectangle.
* @param roundedCornerYRadius The y-radius of the rounded corners on the round-rectangle.
*/
private fun createClockHand(
bounds: Rect,
length: Float,
thickness: Float,
gapBetweenHandAndCenter: Float,
roundedCornerXRadius: Float,
roundedCornerYRadius: Float
): Path {
val width = bounds.width()
val centerX = bounds.exactCenterX()
val centerY = bounds.exactCenterY()
val left = centerX - thickness / 2 * width
val top = centerY - (gapBetweenHandAndCenter + length) * width
val right = centerX + thickness / 2 * width
val bottom = centerY - gapBetweenHandAndCenter * width
val path = Path()
if (roundedCornerXRadius != 0.0f || roundedCornerYRadius != 0.0f) {
path.addRoundRect(
left,
top,
right,
bottom,
roundedCornerXRadius,
roundedCornerYRadius,
Path.Direction.CW
)
} else {
path.addRect(
left,
top,
right,
bottom,
Path.Direction.CW
)
}
return path
}
private fun drawNumberStyleOuterElement(
canvas: Canvas,
bounds: Rect,
numberRadiusFraction: Float,
outerCircleStokeWidthFraction: Float,
outerElementColor: Int,
numberStyleOuterCircleRadiusFraction: Float,
gapBetweenOuterCircleAndBorderFraction: Float
) {
// Draws text hour indicators (12, 3, 6, and 9).
val textBounds = Rect()
textPaint.color = outerElementColor
for (i in 0 until 4) {
val rotation = 0.5f * (i + 1).toFloat() * Math.PI
val dx = sin(rotation).toFloat() * numberRadiusFraction * bounds.width().toFloat()
val dy = -cos(rotation).toFloat() * numberRadiusFraction * bounds.width().toFloat()
textPaint.getTextBounds(HOUR_MARKS[i], 0, HOUR_MARKS[i].length, textBounds)
canvas.drawText(
HOUR_MARKS[i],
bounds.exactCenterX() + dx - textBounds.width() / 2.0f,
bounds.exactCenterY() + dy + textBounds.height() / 2.0f,
textPaint
)
}
// Draws dots for the remain hour indicators between the numbers above.
outerElementPaint.strokeWidth = outerCircleStokeWidthFraction * bounds.width()
outerElementPaint.color = outerElementColor
canvas.save()
for (i in 0 until 12) {
if (i % 3 != 0) {
drawTopMiddleCircle(
canvas,
bounds,
numberStyleOuterCircleRadiusFraction,
gapBetweenOuterCircleAndBorderFraction
)
}
canvas.rotate(360.0f / 12.0f, bounds.exactCenterX(), bounds.exactCenterY())
}
canvas.restore()
}
/** Draws the outer circle on the top middle of the given bounds. */
private fun drawTopMiddleCircle(
canvas: Canvas,
bounds: Rect,
radiusFraction: Float,
gapBetweenOuterCircleAndBorderFraction: Float
) {
outerElementPaint.style = Paint.Style.FILL_AND_STROKE
// X and Y coordinates of the center of the circle.
val centerX = 0.5f * bounds.width().toFloat()
val centerY = bounds.width() * (gapBetweenOuterCircleAndBorderFraction + radiusFraction)
canvas.drawCircle(
centerX,
centerY,
radiusFraction * bounds.width(),
outerElementPaint
)
}
companion object {
private const val TAG = "AnalogWatchCanvasRenderer"
// Painted between pips on watch face for hour marks.
private val HOUR_MARKS = arrayOf("3", "6", "9", "12")
// Used to canvas.scale() to scale watch hands in proper bounds. This will always be 1.0.
private const val WATCH_HAND_SCALE = 1.0f
}
}