feat: Wear OS 워치앱 — 웹 시안 B 디자인의 앱 다섯 장, 타일, 컴플리케이션

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
HyeongBaeYangandClaude Opus 5.5 committed 2026-10-06 11:55:17 +09:00
1 parent 6ee2893745
commit 3f806f9955
64 files changed
+1460

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- 로컬 백엔드가 http 라 디버그 빌드에서만 허용한다 -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application android:usesCleartextTraffic="true" />
</manifest>
+48
View File
@@ -0,0 +1,48 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-feature android:name="android.hardware.type.watch" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:icon="@drawable/ic_gak"
android:label="날씨각"
android:theme="@android:style/Theme.DeviceDefault">
<!-- 폰 앱 없이 워치에서 단독으로 동작 -->
<meta-data android:name="com.google.android.wearable.standalone" android:value="true" />
<activity android:name=".MainActivity" android:exported="true" android:taskAffinity="">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".GakComplicationService"
android:exported="true"
android:icon="@drawable/ic_gak"
android:label="날씨각"
android:permission="com.google.android.wearable.permission.BIND_COMPLICATION_PROVIDER">
<intent-filter>
<action android:name="android.support.wearable.complications.ACTION_COMPLICATION_UPDATE_REQUEST" />
</intent-filter>
<meta-data android:name="android.support.wearable.complications.SUPPORTED_TYPES" android:value="SHORT_TEXT,RANGED_VALUE" />
<!-- 30분마다 다시 묻는다. 실제로 서버를 부르는 건 refresh_at 이 지났을 때뿐 -->
<meta-data android:name="android.support.wearable.complications.UPDATE_PERIOD_SECONDS" android:value="1800" />
</service>
<service
android:name=".GakTileService"
android:exported="true"
android:label="오늘의 각"
android:permission="com.google.android.wearable.permission.BIND_TILE_PROVIDER">
<intent-filter>
<action android:name="androidx.wear.tiles.action.BIND_TILE_PROVIDER" />
</intent-filter>
<meta-data android:name="androidx.wear.tiles.PREVIEW" android:resource="@drawable/ic_gak" />
</service>
</application>
</manifest>
@@ -0,0 +1,50 @@
package kr.o2o.nalssigak
import android.graphics.drawable.Icon
import androidx.wear.watchface.complications.data.ComplicationData
import androidx.wear.watchface.complications.data.ComplicationType
import androidx.wear.watchface.complications.data.PlainComplicationText
import androidx.wear.watchface.complications.data.RangedValueComplicationData
import androidx.wear.watchface.complications.data.ShortTextComplicationData
import androidx.wear.watchface.complications.data.SmallImage
import androidx.wear.watchface.complications.data.SmallImageType
import androidx.wear.watchface.complications.datasource.ComplicationDataTimeline
import androidx.wear.watchface.complications.datasource.ComplicationRequest
import androidx.wear.watchface.complications.datasource.SuspendingTimelineComplicationDataSourceService
import androidx.wear.watchface.complications.datasource.TimeInterval
import androidx.wear.watchface.complications.datasource.TimelineEntry
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.time.Duration
/** 시계 화면 칸: 평소엔 내 각 점수, 오늘 노을이 볼 만하면 일몰 전후로 노을 시각. 언제 바뀔지는 서버 timeline 그대로. */
class GakComplicationService : SuspendingTimelineComplicationDataSourceService() {
override suspend fun onComplicationRequest(request: ComplicationRequest): ComplicationDataTimeline? {
val s = withContext(Dispatchers.IO) { SummaryRepo.load(this@GakComplicationService) } ?: return null
val type = request.complicationType
val sunset = s.sunset?.let { data(type, hhmm(it.bestAt), "노을", it.score, "sunset") }
// 각 점수를 못 받았으면 노을이라도
val default = s.myGak?.let { data(type, it.score.toString(), it.name.removeSuffix("각"), it.score, it.icon) } ?: sunset ?: return null
val entries = if (sunset == null) emptyList() else s.timeline.withIndex().filter { it.value.kind == "sunset" }.map { (i, p) ->
val end = s.timeline.getOrNull(i + 1)?.startAt ?: p.startAt.plus(Duration.ofHours(3))
TimelineEntry(TimeInterval(p.startAt, end), sunset)
}
return ComplicationDataTimeline(default, entries)
}
override fun getPreviewData(type: ComplicationType): ComplicationData = data(type, "82", "야장", 82, "yajang")
/** 3D 아이콘은 작은 이미지로 함께 보낸다. 그릴지 말지는 시계 화면이 정한다. */
private fun data(type: ComplicationType, text: String, title: String, score: Int, icon: String): ComplicationData {
val img = SmallImage.Builder(Icon.createWithResource(this, iconRes(icon)), SmallImageType.ICON).build()
val t = PlainComplicationText.Builder(text).build()
val ti = PlainComplicationText.Builder(title).build()
val desc = PlainComplicationText.Builder("$title $text").build()
return if (type == ComplicationType.RANGED_VALUE) {
RangedValueComplicationData.Builder(score.toFloat(), 0f, 100f, desc).setText(t).setTitle(ti).setSmallImage(img).build()
} else {
ShortTextComplicationData.Builder(t, desc).setTitle(ti).setSmallImage(img).build()
}
}
}
@@ -0,0 +1,94 @@
package kr.o2o.nalssigak
import androidx.concurrent.futures.CallbackToFutureAdapter
import androidx.wear.protolayout.ColorBuilders.argb
import androidx.wear.protolayout.DimensionBuilders.dp
import androidx.wear.protolayout.DimensionBuilders.expand
import androidx.wear.protolayout.DimensionBuilders.sp
import androidx.wear.protolayout.LayoutElementBuilders
import androidx.wear.protolayout.LayoutElementBuilders.FONT_WEIGHT_BOLD
import androidx.wear.protolayout.ModifiersBuilders
import androidx.wear.protolayout.ResourceBuilders
import androidx.wear.protolayout.TimelineBuilders
import androidx.wear.tiles.RequestBuilders
import androidx.wear.tiles.TileBuilders
import androidx.wear.tiles.TileService
import com.google.common.util.concurrent.ListenableFuture
import java.time.Duration
import java.time.Instant
import kotlin.concurrent.thread
private const val NAVY = 0xFF141B3D.toInt()
private const val ORANGE = 0xFFFF7A45.toInt()
private const val WHITE = 0xFFFFFFFF.toInt()
/** 타일: 밤하늘 남색 바탕에 내 각(없으면 1위) 3D 아이콘·점수, 아래 노을 칩. 타일은 시스템 글꼴만 쓸 수 있다. */
class GakTileService : TileService() {
override fun onTileRequest(requestParams: RequestBuilders.TileRequest): ListenableFuture<TileBuilders.Tile> =
CallbackToFutureAdapter.getFuture { done ->
thread { done.set(tile(SummaryRepo.load(this))) }
"gak-tile"
}
/** 이미지 id 는 아이콘 이름 그대로. 목록 없이 요청하면 전부 달라는 뜻이라, 버전에 적어 둔 이름들을 담는다 */
override fun onTileResourcesRequest(requestParams: RequestBuilders.ResourcesRequest): ListenableFuture<ResourceBuilders.Resources> =
CallbackToFutureAdapter.getFuture { done ->
val res = ResourceBuilders.Resources.Builder().setVersion(requestParams.version)
requestParams.resourceIds.ifEmpty { requestParams.version.split(",") }.forEach { id ->
res.addIdToImageMapping(id, ResourceBuilders.ImageResource.Builder()
.setAndroidResourceByResId(ResourceBuilders.AndroidImageResourceByResId.Builder().setResourceId(iconRes(id)).build())
.build())
}
done.set(res.build())
"gak-tile-res"
}
private fun tile(s: Summary?): TileBuilders.Tile {
val g = s?.myGak
val col = LayoutElementBuilders.Column.Builder()
if (s == null || g == null) {
col.addContent(image("rabbit", 48f)).addContent(text("날씨를 못 불러왔어요", 13f, WHITE))
} else {
col.addContent(text("${s.regionName.substringAfterLast(' ')} · ${s.tempC?.let { "${Math.round(it)}°" } ?: "-"}", 12f, 0xB3FFFFFF.toInt()))
.addContent(image(g.icon, 52f))
.addContent(text(g.name, 15f, WHITE, bold = true))
.addContent(text(g.score.toString(), 40f, ORANGE, bold = true))
g.summary?.let { col.addContent(text(it, 11f, 0xCCFFFFFF.toInt())) }
s.sunset?.let { sun ->
val pill = LayoutElementBuilders.Row.Builder()
.addContent(image("sunset", 16f))
.addContent(text(" 노을 ${sun.score} · ${hhmm(sun.bestAt)}", 11f, WHITE, bold = true))
.setModifiers(ModifiersBuilders.Modifiers.Builder()
.setBackground(ModifiersBuilders.Background.Builder().setColor(argb(0x21FFFFFF))
.setCorner(ModifiersBuilders.Corner.Builder().setRadius(dp(99f)).build()).build())
.setPadding(ModifiersBuilders.Padding.Builder().setStart(dp(10f)).setEnd(dp(12f)).setTop(dp(4f)).setBottom(dp(4f)).build())
.build())
.build()
col.addContent(LayoutElementBuilders.Spacer.Builder().setHeight(dp(6f)).build()).addContent(pill)
}
}
val root = LayoutElementBuilders.Box.Builder().setWidth(expand()).setHeight(expand())
.setModifiers(ModifiersBuilders.Modifiers.Builder().setBackground(ModifiersBuilders.Background.Builder().setColor(argb(NAVY)).build()).build())
.addContent(col.build())
.build()
// 다음에 서버 값이 바뀌는 시각까지만 유효, 못 받았으면 30분 뒤 다시
val fresh = s?.let { Duration.between(Instant.now(), it.refreshAt).toMillis() }?.takeIf { it > 0 } ?: Duration.ofMinutes(30).toMillis()
return TileBuilders.Tile.Builder()
// 아이콘이 바뀌면 이미지를 다시 받게
.setResourcesVersion(listOfNotNull(g?.icon, "sunset", "rabbit").joinToString(","))
.setFreshnessIntervalMillis(fresh)
.setTileTimeline(TimelineBuilders.Timeline.fromLayoutElement(root))
.build()
}
private fun image(name: String, size: Float) = LayoutElementBuilders.Image.Builder()
.setResourceId(name).setWidth(dp(size)).setHeight(dp(size)).build()
private fun text(t: String, size: Float, color: Int, bold: Boolean = false) = LayoutElementBuilders.Text.Builder()
.setText(t)
.setMaxLines(2)
.setFontStyle(LayoutElementBuilders.FontStyle.Builder().setSize(sp(size)).setColor(argb(color))
.apply { if (bold) setWeight(FONT_WEIGHT_BOLD) }.build())
.build()
}
@@ -0,0 +1,88 @@
package kr.o2o.nalssigak
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.wear.compose.foundation.pager.VerticalPager
import androidx.wear.compose.foundation.pager.rememberPagerState
import androidx.wear.compose.material3.MaterialTheme
import androidx.wear.compose.material3.VerticalPageIndicator
import kotlinx.coroutines.delay
import java.time.Instant
import kotlin.concurrent.thread
class MainActivity : ComponentActivity() {
private var summary by mutableStateOf<Summary?>(null)
private var loading by mutableStateOf(true)
private val askLocation = registerForActivityResult(ActivityResultContracts.RequestPermission()) { load() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent { MaterialTheme { App(summary, loading) { load(force = true) } } }
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) load()
else askLocation.launch(Manifest.permission.ACCESS_COARSE_LOCATION)
}
private fun load(force: Boolean = false) {
loading = true
thread {
val s = SummaryRepo.load(this, force)
runOnUiThread { summary = s; loading = false }
}
}
}
private enum class Page { HERO, TOP, PICKS, SUNSET, HOURS }
@Composable
private fun App(s: Summary?, loading: Boolean, onRetry: () -> Unit) {
var now by remember { mutableStateOf(Instant.now()) }
LaunchedEffect(Unit) {
while (true) {
delay(20_000)
now = Instant.now()
}
}
if (s == null) {
StatePage(loading, onRetry)
return
}
// 받은 재료가 있는 장만
val pages = buildList {
add(Page.HERO)
if (s.top.isNotEmpty()) add(Page.TOP)
if (s.picks.isNotEmpty()) add(Page.PICKS)
if (s.sunset != null) add(Page.SUNSET)
if (s.slots.isNotEmpty()) add(Page.HOURS)
}
val state = rememberPagerState { pages.size }
Box(Modifier.fillMaxSize()) {
VerticalPager(state = state, modifier = Modifier.fillMaxSize()) { i ->
when (pages[i]) {
Page.HERO -> HeroPage(s, now)
Page.TOP -> GakListPage("오늘의 각", s.top, bgButter, medals = true, now)
Page.PICKS -> GakListPage("내 각", s.picks, bgMint, medals = false, now)
Page.SUNSET -> SunsetPage(s.sunset!!, now)
Page.HOURS -> HoursPage(s, now)
}
}
val page = pages[state.currentPage]
val light = page == Page.SUNSET || (page == Page.HERO && isDark(s.mode))
val dot = if (light) Color.White else Tok.ink
VerticalPageIndicator(pagerState = state, selectedColor = dot, unselectedColor = dot.copy(alpha = 0.35f), backgroundColor = Color.Transparent)
}
}
@@ -0,0 +1,358 @@
package kr.o2o.nalssigak
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.wear.compose.material3.Text
import java.time.Duration
import java.time.Instant
import java.time.format.TextStyle as DateTextStyle
import java.util.Locale
import kotlin.math.cos
import kotlin.math.roundToInt
import kotlin.math.sin
// 시안 크기는 큰 원형(227dp) 기준. 작은 원형(192dp)에서도 넘치지 않게 비율과 여백으로 잡는다.
/** 말랑 카드: 반투명 흰 바탕 + 아래쪽 안쪽 그림자 4dp (웹 inset 0 -5px 0 var(--shade)) */
fun Modifier.mallang(color: Color = Tok.card, shade: Color = Tok.shade, radius: Dp = 18.dp): Modifier =
clip(RoundedCornerShape(radius)).drawBehind {
drawRect(color)
val h = 4.dp.toPx()
drawRect(shade, topLeft = Offset(0f, size.height - h), size = Size(size.width, h))
}
@Composable
private fun T(text: String, size: TextUnit, family: FontFamily = Tok.jua, color: Color = Color.Unspecified, modifier: Modifier = Modifier,
weight: FontWeight? = null, align: TextAlign = TextAlign.Center, maxLines: Int = Int.MAX_VALUE) {
Text(text, modifier = modifier, color = color, maxLines = maxLines, overflow = TextOverflow.Ellipsis, textAlign = align,
style = TextStyle(fontFamily = family, fontSize = size, fontWeight = weight, lineHeight = size * 1.15))
}
@Composable
private fun Ic(name: String, size: Dp, modifier: Modifier = Modifier) =
Image(painterResource(iconRes(name)), contentDescription = null, modifier = modifier.size(size))
/** 3D 아이콘이 둥둥 (웹 b-float 4.4s) */
@Composable
private fun Floating(content: @Composable () -> Unit) {
val t = rememberInfiniteTransition(label = "float")
val p by t.animateFloat(0f, 1f, infiniteRepeatable(tween(2200, easing = FastOutSlowInEasing), RepeatMode.Reverse), label = "bob")
Box(Modifier.graphicsLayer { translationY = -6.dp.toPx() * p; rotationZ = 1.2f * p }) { content() }
}
@Composable
fun Clock(now: Instant, color: Color) {
T(hhmm(now), 11.sp, FontFamily.Default, color.copy(alpha = 0.8f), Modifier.fillMaxWidth().padding(top = 8.dp), weight = FontWeight.Bold)
}
// ───────────── 1. 오늘 ─────────────
private val STARS = listOf(0.22f to 0.20f, 0.70f to 0.14f, 0.84f to 0.40f, 0.14f to 0.52f, 0.48f to 0.10f, 0.30f to 0.78f, 0.76f to 0.70f)
@Composable
fun HeroPage(s: Summary, now: Instant) {
val dark = isDark(s.mode)
val night = s.mode == "night"
val fg = if (dark) Color.White else Tok.ink
val top = s.top.firstOrNull()
BoxWithConstraints(Modifier.fillMaxSize().background(skyBrush(s.mode))) {
val w = maxWidth
if (night) Canvas(Modifier.fillMaxSize()) {
STARS.forEach { (x, y) -> drawCircle(Color.White, 1.4.dp.toPx(), Offset(size.width * x, size.height * y)) }
}
Clock(now, fg)
val day = now.atZone(KST).dayOfWeek.getDisplayName(DateTextStyle.FULL, Locale.KOREAN)
T("$day · ${s.regionName.substringAfterLast(' ')}", 12.sp, color = fg, modifier = Modifier.fillMaxWidth().padding(top = 26.dp))
Cloud(night, 7000, 16f, Modifier.offset(w * 0.09f, w * 0.34f).size(w * 0.19f, w * 0.07f))
Cloud(night, 9000, -20f, Modifier.offset(w * 0.6f, w * 0.74f).size(w * 0.22f, w * 0.075f))
Orb(night, Modifier.align(Alignment.Center).offset(y = (-6).dp).size(w * 0.4f)) {
T(top?.score?.toString() ?: "-", 36.sp, Tok.bagel, if (night) Color(0xFF2B2A5C) else Color.White)
T(top?.name ?: "날씨각", 11.sp, color = if (night) Color(0xFF2B2A5C) else Color.White)
}
// 큰 원 둘레에 나머지 각 점수 링 (1위는 큰 원에 있으니 빼고)
val rings = (s.top + s.picks).distinctBy { it.code }.filter { it.code != top?.code }.take(RING_ANGLES.size)
rings.forEachIndexed { i, g ->
val rad = Math.toRadians(RING_ANGLES[i])
val size = w * 0.15f
ScoreRing(g, dark, Modifier.offset(w * (0.5f + 0.33f * cos(rad).toFloat()) - size / 2, w * 0.5f - 6.dp + w * 0.33f * sin(rad).toFloat() - size / 2).size(size))
}
Row(Modifier.align(Alignment.BottomCenter).padding(bottom = w * 0.1f), horizontalArrangement = Arrangement.spacedBy(5.dp)) {
Stat("thermo", s.tempC?.let { "${it.roundToInt()}°" } ?: "-°", dark)
Stat("umbrella", when (s.rain2h) { true -> "곧 비"; false -> "비 없음"; null -> "-" }, dark)
}
s.warning?.let {
T("⚠ $it", 10.sp, color = fg, modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = w * 0.03f), maxLines = 1)
}
}
}
// 링 자리 (0° = 오른쪽, 시계 방향). 위는 날짜, 아래는 칩이라 양옆으로 채운다
private val RING_ANGLES = listOf(210.0, 330.0, 150.0, 30.0, 180.0, 0.0)
/** 작은 점수 링: 3D 아이콘 + 점수, 둘레에 점수만큼 주황 호 (시계 화면 컴플리케이션 모양) */
@Composable
private fun ScoreRing(g: Gak, dark: Boolean, modifier: Modifier) {
val bg = if (dark) Tok.statDark else Tok.stat
val track = if (dark) Color.White.copy(alpha = 0.2f) else Tok.shade
Box(
modifier.drawBehind {
val stroke = 3.dp.toPx()
drawCircle(bg)
val arc = Size(size.width - stroke, size.height - stroke)
val tl = Offset(stroke / 2, stroke / 2)
drawArc(track, -90f, 360f, false, tl, arc, style = Stroke(stroke))
drawArc(Tok.orange, -90f, 360f * g.score / 100f, false, tl, arc, style = Stroke(stroke, cap = StrokeCap.Round))
},
contentAlignment = Alignment.Center,
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Ic(g.icon, 14.dp)
T(g.score.toString(), 9.sp, Tok.bagel, if (dark) Color.White else Tok.ink)
}
}
}
/** 말랑 3D 해 구슬 (웹 .b-sun). 밤에는 달빛 보라 */
@Composable
private fun Orb(night: Boolean, modifier: Modifier, content: @Composable () -> Unit) {
val stops = if (night) arrayOf(0f to Color.White, 0.35f to Color(0xFFE7E3FF), 0.72f to Color(0xFFB9B0F2), 1f to Color(0xFF8F86D9))
else arrayOf(0f to Color(0xFFFFF5CF), 0.3f to Color(0xFFFFC86E), 0.68f to Color(0xFFFF8E4E), 1f to Color(0xFFEE6436))
val glow = if (night) Color(0xFFBEB4FF) else Color(0xFFF06A3A)
Box(
modifier
.shadow(18.dp, CircleShape, ambientColor = glow, spotColor = glow)
.drawBehind {
val c = Offset(size.width * 0.34f, size.height * 0.30f)
drawCircle(Brush.radialGradient(*stops, center = c, radius = size.width * 0.96f))
// 오른쪽 아래 그늘, 왼쪽 위 빛 (웹 inset 그림자 두 개)
drawCircle(Brush.linearGradient(listOf(Color.Transparent, Color(if (night) 0x4D3C328C else 0x57AA3214)), Offset(size.width * 0.45f, size.height * 0.45f), Offset(size.width, size.height)))
drawCircle(Brush.radialGradient(listOf(Color.White.copy(alpha = 0.45f), Color.Transparent), Offset(size.width * 0.28f, size.height * 0.25f), size.width * 0.35f))
},
contentAlignment = Alignment.Center,
) { Column(horizontalAlignment = Alignment.CenterHorizontally) { content() } }
}
/** 구름은 좌우로 천천히 오간다. distance 부호로 방향, ms 로 속도 */
@Composable
private fun Cloud(night: Boolean, ms: Int, distance: Float, modifier: Modifier) {
val c = if (night) Color(0xFFC9CDF0) else Color.White
val t = rememberInfiniteTransition(label = "cloud")
val p by t.animateFloat(0f, 1f, infiniteRepeatable(tween(ms, easing = FastOutSlowInEasing), RepeatMode.Reverse), label = "drift")
Canvas(modifier.graphicsLayer { translationX = distance.dp.toPx() * p }) {
drawCircle(c, size.height * 0.95f, Offset(size.width * 0.38f, size.height * 0.1f))
drawRoundRect(c, cornerRadius = CornerRadius(size.height / 2))
drawRoundRect(Color(0x33A0BEE6), Offset(0f, size.height * 0.55f), Size(size.width, size.height * 0.45f), CornerRadius(size.height / 2))
}
}
@Composable
private fun Stat(icon: String, text: String, dark: Boolean) {
Row(
Modifier.mallang(if (dark) Tok.statDark else Tok.stat, if (dark) Color.White.copy(alpha = 0.12f) else Tok.shade.copy(alpha = 0.9f), 14.dp)
.padding(start = 5.dp, end = 9.dp, top = 3.dp, bottom = 6.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(3.dp),
) {
Ic(icon, 16.dp)
T(text, 12.sp, color = if (dark) Color.White else Tok.ink)
}
}
// ───────────── 2·3. 오늘의 각 · 내 각 ─────────────
@Composable
fun GakListPage(title: String, items: List<Gak>, bg: Brush, medals: Boolean, now: Instant) {
var open by remember { mutableStateOf<String?>(null) }
Box(Modifier.fillMaxSize().background(bg)) {
Clock(now, Tok.ink)
Column(
Modifier.fillMaxSize().padding(start = 20.dp, end = 20.dp, top = 30.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(5.dp),
) {
T(title, 14.sp, color = Tok.ink)
items.forEachIndexed { i, g ->
// 원 위아래가 좁아 가운데 줄만 꽉 채운다
val width = if (i == 1) 1f else 0.88f
GakRow(g, if (medals) MEDALS.getOrNull(i) else null, open == g.code, Modifier.fillMaxWidth(width)) {
open = if (open == g.code) null else g.code
}
}
}
}
}
@Composable
private fun GakRow(g: Gak, medal: String?, open: Boolean, modifier: Modifier, onClick: () -> Unit) {
Row(
modifier.mallang().clickable(onClick = onClick).padding(start = 6.dp, end = 10.dp, top = 5.dp, bottom = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(6.dp),
) {
Box {
Ic(g.icon, 28.dp)
medal?.let { Ic(it, 12.dp, Modifier.offset((-4).dp, (-3).dp)) }
}
Column(Modifier.weight(1f)) {
Row(verticalAlignment = Alignment.CenterVertically) {
T(g.name, 13.sp, color = Tok.ink, align = TextAlign.Start, maxLines = 1)
if (medal == null) {
T("${g.rank}위", 8.sp, FontFamily.Default, Tok.ink2, Modifier.padding(start = 3.dp).background(Color(0xFFEEF3FA), CircleShape).padding(horizontal = 4.dp),
weight = FontWeight.ExtraBold)
}
}
g.summary?.let {
// 누르면 근거 한 줄을 크게
T(it, if (open) 11.sp else 8.5.sp, FontFamily.Default, Tok.ink2, align = TextAlign.Start, weight = FontWeight.Bold, maxLines = if (open) 3 else 1)
}
}
T(g.score.toString(), 18.sp, Tok.bagel, Tok.orange)
}
}
// ───────────── 4. 노을 ─────────────
// 웹 .b-skyline::after 의 건물 윤곽 (x%, y%)
private val SKYLINE = listOf(0 to 55, 8 to 55, 8 to 30, 15 to 30, 15 to 50, 22 to 50, 22 to 10, 28 to 10, 28 to 45, 36 to 45, 36 to 25, 44 to 25, 44 to 55,
52 to 55, 52 to 35, 60 to 35, 60 to 5, 66 to 5, 66 to 40, 74 to 40, 74 to 20, 82 to 20, 82 to 50, 90 to 50, 90 to 30, 100 to 30, 100 to 100, 0 to 100)
@Composable
fun SunsetPage(sun: Sunset, now: Instant) {
Box(Modifier.fillMaxSize().background(bgDusk)) {
Canvas(Modifier.fillMaxSize()) {
val h = size.height * 0.26f
val top = size.height - h
val path = Path().apply {
SKYLINE.forEachIndexed { i, (x, y) ->
val px = size.width * x / 100f
val py = top + h * y / 100f
if (i == 0) moveTo(px, py) else lineTo(px, py)
}
close()
}
drawPath(path, Color(0xFF2D2440))
}
Clock(now, Color.White)
Column(Modifier.fillMaxSize().padding(top = 32.dp), horizontalAlignment = Alignment.CenterHorizontally) {
T(if (sun.isToday) "오늘 노을" else "내일 노을", 13.sp, color = Color.White.copy(alpha = 0.9f))
T(sun.score.toString(), 52.sp, Tok.bagel, Color.White)
T(sun.grade, 12.sp, color = Color.White,
modifier = Modifier.mallang(Color.White.copy(alpha = 0.2f), Color.White.copy(alpha = 0.12f), 99.dp).padding(start = 10.dp, end = 10.dp, top = 2.dp, bottom = 5.dp))
Spacer(Modifier.height(8.dp))
T("가장 붉을 때 ${hhmm(sun.bestAt)}", 14.sp, color = Color.White)
val left = Duration.between(now, sun.sunsetAt)
val tail = if (sun.isToday && !left.isNegative) " · ${left.toHours()}시간 ${left.toMinutes() % 60}분 남음" else ""
T("해 지는 ${hhmm(sun.sunsetAt)}$tail", 9.5.sp, FontFamily.Default, Color.White.copy(alpha = 0.85f), weight = FontWeight.Bold)
}
}
}
// ───────────── 5. 오늘 남은 시간 ─────────────
@Composable
fun HoursPage(s: Summary, now: Instant) {
Box(Modifier.fillMaxSize().background(bgSky)) {
Clock(now, Tok.ink)
Column(Modifier.fillMaxSize().padding(top = 40.dp), horizontalAlignment = Alignment.CenterHorizontally) {
T("오늘 남은 시간", 14.sp, color = Tok.ink)
Spacer(Modifier.height(10.dp))
Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
s.slots.take(4).forEachIndexed { i, slot -> HourCol(slot, i == 0) }
}
s.rainText?.let {
Spacer(Modifier.height(10.dp))
Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(3.dp)) {
Ic(if (s.mode == "night") "bear" else "rabbit", 26.dp)
T(it, 10.5.sp, color = Tok.ink, align = TextAlign.Start,
modifier = Modifier.widthIn(max = 120.dp).background(Color.White, RoundedCornerShape(12.dp, 12.dp, 12.dp, 4.dp)).padding(horizontal = 8.dp, vertical = 4.dp))
}
}
}
}
}
@Composable
private fun HourCol(slot: Slot, first: Boolean) {
val fg = if (first) Color.White else Tok.ink
Column(
Modifier.width(40.dp).then(if (first) Modifier.background(Tok.ink, RoundedCornerShape(15.dp)) else Modifier.mallang(Tok.stat, radius = 15.dp))
.padding(top = 6.dp, bottom = 8.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(2.dp),
) {
T("${slot.at.atZone(KST).hour}시", 8.5.sp, FontFamily.Default, fg.copy(alpha = 0.75f), weight = FontWeight.ExtraBold)
Ic(slot.icon, 22.dp)
T(slot.tempC?.let { "${it.roundToInt()}°" } ?: "-", 14.sp, Tok.bagel, fg)
T("${slot.rainProb ?: "-"}%", 8.sp, FontFamily.Default, if (first) Tok.rainLight else Tok.rain, weight = FontWeight.ExtraBold)
}
}
// ───────────── 불러오는 중 · 실패 ─────────────
@Composable
fun StatePage(loading: Boolean, onRetry: () -> Unit) {
Column(Modifier.fillMaxSize().background(skyBrush("day")), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
Floating { Ic("rabbit", 54.dp) }
Spacer(Modifier.height(6.dp))
T(if (loading) "날씨 보러 가는 중" else "날씨를 못 불러왔어요", 14.sp, color = Tok.ink)
if (!loading) {
Spacer(Modifier.height(10.dp))
T("다시 시도", 12.sp, FontFamily.Default, Color.White, Modifier.clip(CircleShape).background(Tok.ink).clickable(onClick = onRetry).padding(horizontal = 14.dp, vertical = 6.dp),
weight = FontWeight.Bold)
}
}
}
@@ -0,0 +1,129 @@
package kr.o2o.nalssigak
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.LocationManager
import android.util.Log
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.time.Instant
import java.time.OffsetDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
data class Gak(val code: String, val name: String, val icon: String, val score: Int, val rank: Int, val summary: String?)
data class Sunset(val isToday: Boolean, val score: Int, val grade: String, val sunsetAt: Instant, val bestAt: Instant)
data class Slot(val at: Instant, val icon: String, val tempC: Double?, val rainProb: Int?)
data class Phase(val startAt: Instant, val kind: String)
data class Summary(
val regionName: String,
val refreshAt: Instant,
/** morning | day | evening | night (서버 slot_of) */
val mode: String,
val tempC: Double?,
val rainText: String?,
val rain2h: Boolean?,
val warning: String?,
val top: List<Gak>,
val picks: List<Gak>,
val sunset: Sunset?,
val slots: List<Slot>,
val timeline: List<Phase>,
) {
/** 컴플리케이션·타일에 올릴 각: 내 각 첫 번째, 없으면 오늘 1위 */
val myGak: Gak? get() = picks.firstOrNull() ?: top.firstOrNull()
}
val KST: ZoneId = ZoneId.of("Asia/Seoul")
private val HHMM = DateTimeFormatter.ofPattern("HH:mm").withZone(KST)
fun hhmm(at: Instant): String = HHMM.format(at)
private fun time(s: String): Instant = OffsetDateTime.parse(s).toInstant()
private fun JSONObject.str(k: String): String? = if (has(k)) getString(k) else null
private fun JSONObject.dbl(k: String): Double? = if (has(k)) getDouble(k) else null
private fun JSONObject.int(k: String): Int? = if (has(k)) getInt(k) else null
private fun <T> JSONObject.list(k: String, f: (JSONObject) -> T): List<T> {
val a = optJSONArray(k) ?: JSONArray()
return (0 until a.length()).map { f(a.getJSONObject(it)) }
}
private fun gak(o: JSONObject) = Gak(o.getString("code"), o.getString("name"), o.getString("icon"), o.getInt("score"), o.getInt("rank"), o.str("summary"))
fun parseSummary(json: String): Summary {
val o = JSONObject(json)
val now = o.optJSONObject("now")
return Summary(
regionName = o.getString("region_name"),
refreshAt = time(o.getString("refresh_at")),
mode = o.optString("mode", "day"),
tempC = now?.dbl("temp_c"),
rainText = now?.str("text"),
rain2h = now?.takeIf { it.has("rain_2h") }?.getBoolean("rain_2h"),
warning = o.str("warning"),
top = o.list("top", ::gak),
picks = o.list("picks", ::gak),
sunset = o.optJSONObject("sunset")?.let {
Sunset(it.getBoolean("is_today"), it.getInt("score"), it.getString("grade_label"), time(it.getString("sunset_at")), time(it.getString("best_at")))
},
slots = o.list("slots") { Slot(time(it.getString("at")), it.getString("icon"), it.dbl("temp_c"), it.int("rain_prob")) },
timeline = o.list("timeline") { Phase(time(it.getString("start_at")), it.getString("kind")) },
)
}
object SummaryRepo {
private const val TAG = "SummaryRepo"
// ponytail: 내 각 고정값. 설정 화면이 생기면 저장값으로
private const val PICKS = "running,laundry,walk"
// 위치를 못 얻으면 종로구
private const val DEFAULT_REGION = "1111000000"
/** 캐시가 refresh_at 전이면 캐시, 아니면 새로 받는다. 받기 실패하면 지난 캐시라도. 네트워크를 쓰니 메인 스레드에서 부르지 않는다. */
fun load(context: Context, force: Boolean = false): Summary? {
val prefs = context.getSharedPreferences("summary", Context.MODE_PRIVATE)
val cached = prefs.getString("json", null)?.let { runCatching { parseSummary(it) }.getOrNull() }
if (!force && cached != null && Instant.now() < cached.refreshAt) return cached
return try {
val region = prefs.getString("region", null) ?: nearestRegion(context)?.also { prefs.edit().putString("region", it).apply() } ?: DEFAULT_REGION
val json = get("/v1/watch/summary?region=$region&pick=$PICKS")
val fresh = parseSummary(json)
prefs.edit().putString("json", json).apply()
fresh
} catch (e: Exception) {
Log.w(TAG, "summary 받기 실패, 캐시 사용", e)
cached
}
}
private fun nearestRegion(context: Context): String? {
if (context.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) return null
val lm = context.getSystemService(LocationManager::class.java)
val loc = lm.getProviders(true).firstNotNullOfOrNull { lm.getLastKnownLocation(it) } ?: return null
return try {
JSONObject(get("/v1/region/nearest?lat=${loc.latitude}&lon=${loc.longitude}")).getJSONObject("region").getString("code")
} catch (e: IOException) {
// 국내 범위 밖이면 서버가 422 를 준다
Log.w(TAG, "가까운 구 찾기 실패 (${loc.latitude}, ${loc.longitude})", e)
null
}
}
private fun get(path: String): String {
val conn = URL(BuildConfig.API_BASE + path).openConnection() as HttpURLConnection
conn.connectTimeout = 5000
conn.readTimeout = 10000
try {
if (conn.responseCode != 200) throw IOException("HTTP ${conn.responseCode} $path")
val body = conn.inputStream.bufferedReader().readText()
if (!JSONObject(body).getJSONObject("result").getBoolean("success")) throw IOException("실패 응답 $path: $body")
return body
} finally {
conn.disconnect()
}
}
}
@@ -0,0 +1,65 @@
package kr.o2o.nalssigak
import androidx.annotation.DrawableRes
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
// 웹 시안 B 토큰 그대로 (frontend/src/b/b.css, index.css)
object Tok {
val ink = Color(0xFF28304A)
val ink2 = Color(0xFF5A6380)
val shade = Color(0xFFD9E5F4)
val orange = Color(0xFFFF7A45)
val rain = Color(0xFF4F97E3)
val rainLight = Color(0xFF9FD3FF)
val navy = Color(0xFF141B3D)
val navyTop = Color(0xFF2B3577)
val card = Color.White.copy(alpha = 0.78f)
val stat = Color.White.copy(alpha = 0.72f)
val statDark = Color.White.copy(alpha = 0.18f)
val jua = FontFamily(Font(R.font.jua))
val bagel = FontFamily(Font(R.font.bagel_fat_one))
}
private fun v(vararg stops: Pair<Float, Long>) = Brush.verticalGradient(*stops.map { it.first to Color(it.second) }.toTypedArray())
/** 히어로 하늘 (.b-hero[data-t]). 서버 mode 의 evening 이 웹의 sunset */
fun skyBrush(mode: String): Brush = when (mode) {
"morning" -> v(0f to 0xFFFFD9B8, 0.4f to 0xFFFFE9D4, 1f to 0xFFDFF0FF)
"evening" -> v(0f to 0xFF8E7CF0, 0.48f to 0xFFF28AA0, 1f to 0xFFFFC38A)
"night" -> v(0f to 0xFF141B3D, 0.6f to 0xFF27306A, 1f to 0xFF3D3F86)
else -> v(0f to 0xFF9FD3FF, 0.55f to 0xFFCFE9FF, 1f to 0xFFF1F8FF)
}
/** 하늘 위 글자가 흰색이어야 하는 시간대 */
fun isDark(mode: String) = mode == "evening" || mode == "night"
// 카드·장 배경 (.b-bg-*)
val bgButter = v(0f to 0xFFFFE7A0, 1f to 0xFFFFF6D8)
val bgMint = v(0f to 0xFFBFECD6, 1f to 0xFFEFFAF4)
val bgSky = v(0f to 0xFFBFE3FF, 1f to 0xFFEEF7FF)
val bgDusk = v(0f to 0xFF7E6FE6, 0.6f to 0xFFF08AA2, 1f to 0xFFFFC28A)
// 웹 public/icons 의 Fluent 3D 아이콘. 이름은 서버 icon 값과 같다
private val ICONS = mapOf(
"yajang" to R.drawable.e_yajang, "picnic" to R.drawable.e_picnic, "chimaek" to R.drawable.e_chimaek, "walk" to R.drawable.e_walk,
"vent" to R.drawable.e_vent, "hiking" to R.drawable.e_hiking, "carwash" to R.drawable.e_carwash, "camping" to R.drawable.e_camping,
"running" to R.drawable.e_running, "stars" to R.drawable.e_stars, "jjamppong" to R.drawable.e_jjamppong, "makgeolli" to R.drawable.e_makgeolli,
"iced_hot" to R.drawable.e_iced_hot, "laundry" to R.drawable.e_laundry, "bike" to R.drawable.e_bike, "dog" to R.drawable.e_dog,
"glasses" to R.drawable.e_glasses, "makeup" to R.drawable.e_makeup, "naengmyeon" to R.drawable.e_naengmyeon, "taxi" to R.drawable.e_taxi,
"delivery" to R.drawable.e_delivery, "garden" to R.drawable.e_garden, "photo" to R.drawable.e_photo, "baseball" to R.drawable.e_baseball,
"study" to R.drawable.e_study, "netflix" to R.drawable.e_netflix, "chestnut" to R.drawable.e_chestnut,
"sun" to R.drawable.e_sun, "sun_cloud" to R.drawable.e_sun_cloud, "cloud" to R.drawable.e_cloud, "rain" to R.drawable.e_rain,
"snow" to R.drawable.e_snow, "sunset" to R.drawable.e_sunset, "moon" to R.drawable.e_moon,
"gold" to R.drawable.e_gold, "silver" to R.drawable.e_silver, "bronze" to R.drawable.e_bronze,
"rabbit" to R.drawable.e_rabbit, "bear" to R.drawable.e_bear, "umbrella" to R.drawable.e_umbrella, "thermo" to R.drawable.e_thermo,
)
/** 없는 이름은 웹 iconSrc 처럼 sun_cloud */
@DrawableRes
fun iconRes(name: String): Int = ICONS[name] ?: R.drawable.e_sun_cloud
val MEDALS = listOf("gold", "silver", "bronze")
Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- ponytail: 임시 아이콘(노을색 원). 정식 아이콘 나오면 교체 -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="48dp" android:height="48dp" android:viewportWidth="48" android:viewportHeight="48">
<path android:fillColor="#FF8A50" android:pathData="M24,4a20,20 0 1,0 0.01,0z" />
</vector>
Binary file not shown.
Binary file not shown.