diff --git a/backend/common/utils/text.py b/backend/common/utils/text.py index 7032577..c9ed9db 100644 --- a/backend/common/utils/text.py +++ b/backend/common/utils/text.py @@ -1,3 +1,6 @@ +import html + + def hour_label(h: int) -> str: if h == 0: return "자정" @@ -35,3 +38,10 @@ _COMPASS = ("북", "북북동", "북동", "동북동", "동", "동남동", "남 def compass(deg: float) -> str: """방위각 → 16방위 이름. 263 → "서" """ return _COMPASS[round(deg / 22.5) % 16] + + +def plain(s: str) -> str: + """HTML 문자 참조를 다 푼다. 두 번 인코딩돼 오는 출처도 있어("&lt;") 더 안 바뀔 때까지.""" + while (u := html.unescape(s)) != s: + s = u + return s diff --git a/backend/crud/week_crud.py b/backend/crud/week_crud.py index 80a7a0a..b2ae989 100644 --- a/backend/crud/week_crud.py +++ b/backend/crud/week_crud.py @@ -5,6 +5,7 @@ from sqlalchemy.dialects.postgresql import insert from sqlalchemy.ext.asyncio import AsyncSession from common.database.model.models import Event, Holiday, Place, WeatherDaily +from common.utils.text import plain class WeekCRUD: @@ -46,6 +47,8 @@ class WeekCRUD: async def upsert_events(self, s: AsyncSession, rows: list[dict]) -> None: if not rows: return + # 출처마다 이름에 "<" 같은 HTML 문자가 섞여 와서, 넣기 전에 푼다 + rows = [{**r, "name": plain(r["name"]), "place_name": plain(r["place_name"])} for r in rows] stmt = insert(Event).values(rows) await s.execute(stmt.on_conflict_do_update( index_elements=["source_id"], diff --git a/backend/router/v1/watch/protocol.py b/backend/router/v1/watch/protocol.py index b957944..4c4d551 100644 --- a/backend/router/v1/watch/protocol.py +++ b/backend/router/v1/watch/protocol.py @@ -9,6 +9,7 @@ class WatchNow(WebPacketProtocol): temp_c: Optional[float] = None icon: Optional[str] = None rain_2h: Optional[bool] = None + thunder: Optional[bool] = None # 2시간 안에 낙뢰 예보 text: Optional[str] = None diff --git a/backend/router/v1/watch/watch.py b/backend/router/v1/watch/watch.py index b2dc72e..d66c17e 100644 --- a/backend/router/v1/watch/watch.py +++ b/backend/router/v1/watch/watch.py @@ -93,7 +93,7 @@ async def get_watch_summary( for s in today.slots if s.at > now ] if now_w is not None: - res.now = (res.now or WatchNow()).model_copy(update={"rain_2h": now_w.will_rain_2h, "text": now_w.rain_2h_text}) + res.now = (res.now or WatchNow()).model_copy(update={"rain_2h": now_w.will_rain_2h, "thunder": now_w.thunder_2h, "text": now_w.rain_2h_text}) res.warning = now_w.warnings[0].text if now_w.warnings else None if board is not None: diff --git a/backend/services/external/kma.py b/backend/services/external/kma.py index 52de55a..d933c52 100644 --- a/backend/services/external/kma.py +++ b/backend/services/external/kma.py @@ -79,13 +79,13 @@ def day_start_base(day: date) -> datetime: def parse_ultra(items: list[dict]) -> list[dict]: - """초단기예보 6시간: 시각별 비 형태·1시간 강수량·기온.""" + """초단기예보 6시간: 시각별 비 형태·1시간 강수량·기온·낙뢰(LGT, 0 이면 없음).""" by_time: dict[datetime, dict[str, str]] = {} for it in items: at = datetime.strptime(it["fcstDate"] + it["fcstTime"], "%Y%m%d%H%M").replace(tzinfo=KST) by_time.setdefault(at, {})[it["category"]] = it["fcstValue"] return [ - {"at": at, "rain_type": _PTY[v["PTY"]], "rain_mm": parse_amount(v.get("RN1", "")), "temp_c": float(v["T1H"])} + {"at": at, "rain_type": _PTY[v["PTY"]], "rain_mm": parse_amount(v.get("RN1", "")), "temp_c": float(v["T1H"]), "lightning": parse_amount(v.get("LGT", "")) > 0} for at, v in sorted(by_time.items()) if "PTY" in v and "T1H" in v ] diff --git a/backend/services/now_service.py b/backend/services/now_service.py index 47dbec6..93d4e52 100644 --- a/backend/services/now_service.py +++ b/backend/services/now_service.py @@ -33,6 +33,7 @@ class RainHour: at: datetime rain_type: RainType rain_mm: float + lightning: bool = False @dataclass @@ -56,6 +57,7 @@ class NowWeather: air: Optional[AirQuality] air_text: Optional[str] warnings: Optional[list[WarningItem]] = field(default=None) + thunder_2h: bool = False def _weather_word(rain: RainType, sky: Sky, rain_mm: float) -> tuple[str, str]: @@ -139,6 +141,7 @@ class NowService: return ErrorType.SUCCESS, NowWeather( region=region, will_rain_2h=will_rain, rain_2h_text=rain_text, rain_hours=hours, tomorrow_text=tomorrow_text, tomorrow_rain_from=rain_from, commute=commute, air=air, air_text=air_text, warnings=warnings, + thunder_2h=any(h.lightning for h in hours), ) async def _ultra(self, region: Region, now: datetime) -> Optional[list[RainHour]]: @@ -155,7 +158,10 @@ async def _cached_ultra(key: str, base: datetime) -> Optional[list[RainHour]]: data = orjson.loads(cached) if data["base"] != base.isoformat(): return None - return [RainHour(at=datetime.fromisoformat(h["at"]), rain_type=RainType(h["rain_type"]), rain_mm=h["rain_mm"]) for h in data["hours"]] + return [ + RainHour(at=datetime.fromisoformat(h["at"]), rain_type=RainType(h["rain_type"]), rain_mm=h["rain_mm"], lightning=h.get("lightning", False)) + for h in data["hours"] + ] async def ultra_hours(region: Region, now: datetime, wait: bool = False) -> Optional[list[RainHour]]: @@ -173,9 +179,9 @@ async def ultra_hours(region: Region, now: datetime, wait: bool = False) -> Opti continue async with httpx.AsyncClient(timeout=10) as client: parsed = parse_ultra(await fetch_ultra(client, region.nx, region.ny, base)) - hours = [RainHour(at=p["at"], rain_type=p["rain_type"], rain_mm=p["rain_mm"]) for p in parsed] + hours = [RainHour(at=p["at"], rain_type=p["rain_type"], rain_mm=p["rain_mm"], lightning=p["lightning"]) for p in parsed] ttl = int((base + timedelta(hours=1, minutes=15) - now).total_seconds()) - payload = {"base": base.isoformat(), "hours": [{"at": h.at.isoformat(), "rain_type": h.rain_type.value, "rain_mm": h.rain_mm} for h in hours]} + payload = {"base": base.isoformat(), "hours": [{"at": h.at.isoformat(), "rain_type": h.rain_type.value, "rain_mm": h.rain_mm, "lightning": h.lightning} for h in hours]} await REDIS.conn.set(key, orjson.dumps(payload), ex=max(ttl, 60)) return hours return None diff --git a/backend/tests/test_now_parse.py b/backend/tests/test_now_parse.py index 4264b2f..09e8d4d 100644 --- a/backend/tests/test_now_parse.py +++ b/backend/tests/test_now_parse.py @@ -18,7 +18,7 @@ def test_parse_ultra_reads_rain_and_temp(): {"category": c, "fcstDate": "20261002", "fcstTime": "1000", "fcstValue": v} for c, v in [("PTY", "1"), ("RN1", "1mm 미만"), ("T1H", "17")] ] - assert parse_ultra(items) == [{"at": _kst(2, 10), "rain_type": RainType.RAIN, "rain_mm": 0.5, "temp_c": 17.0}] + assert parse_ultra(items) == [{"at": _kst(2, 10), "rain_type": RainType.RAIN, "rain_mm": 0.5, "temp_c": 17.0, "lightning": False}] def _event(area, var, cmd, tm, seq=1, stress=0): @@ -82,3 +82,13 @@ def test_parse_ultra_reads_drizzle_codes(): for c, v in [("PTY", pty), ("RN1", "1mm 미만"), ("T1H", "17")] ] assert [p["rain_type"] for p in parse_ultra(items)] == [RainType.RAIN, RainType.SLEET, RainType.SNOW] + + +def test_parse_ultra_reads_lightning(): + """LGT 는 낙뢰(kA). 0 이면 없음, 칸이 없어도 없음.""" + items = [ + {"fcstDate": "20261013", "fcstTime": f"{h:02d}00", "category": c, "fcstValue": v} + for h, lgt in ((10, "0"), (11, "3"), (12, None)) + for c, v in [("PTY", "1"), ("RN1", "5.0mm"), ("T1H", "17"), ("LGT", lgt)] if v is not None + ] + assert [p["lightning"] for p in parse_ultra(items)] == [False, True, False] diff --git a/backend/tests/test_seoul_culture.py b/backend/tests/test_seoul_culture.py index c430251..d7af6ba 100644 --- a/backend/tests/test_seoul_culture.py +++ b/backend/tests/test_seoul_culture.py @@ -81,3 +81,18 @@ async def test_drop_known_skips_same_festival_from_another_source(): _row("9001", "경복궁 별빛야행", date(2026, 10, 1), date(2026, 10, 25)), ] assert [r["source_id"] for r in await drop_known(rows)] == ["popga:2", "popga:3", "9001"] + + +@pytest.mark.anyio +async def test_upsert_events_stores_names_without_html_entities(): + from sqlalchemy import select + + from common.database.db_session_manager import DB_SESSION_MNG + from common.database.model.models import Event + from crud.week_crud import WeekCRUD + + # 문화정보원 목록은 두 번 인코딩돼 와서 한 번 풀어도 "<" 가 남는다 + row = {**_row("kcis:1", "김상희 2인전 &lt;안녕을 빌었다&gt;", date(2026, 10, 1), date(2026, 10, 24)), "place_name": "갤러리 &middot; 1층"} + await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, [row])]) + _, saved = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(select(Event).where(Event.source_id == "kcis:1"))) + assert (saved.name, saved.place_name) == ("김상희 2인전 <안녕을 빌었다>", "갤러리 · 1층") diff --git a/backend/tests/test_watch.py b/backend/tests/test_watch.py index 9c9ab0a..73a379c 100644 --- a/backend/tests/test_watch.py +++ b/backend/tests/test_watch.py @@ -4,7 +4,9 @@ from types import SimpleNamespace import pytest from httpx import ASGITransport, AsyncClient +import services.now_service as now_service import services.week_service as week_service +from common.cache.redis_client import REDIS from common.utils.kma_time import KST, now_kst from router.router import app from router.v1.watch.watch import timeline @@ -83,3 +85,18 @@ async def test_watch_summary_unknown_region_fails(offline): async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: body = (await client.get("/v1/watch/summary", params={"region": "0000000000"})).json() assert body["result"]["success"] is False + + +@pytest.mark.anyio +async def test_watch_summary_flags_thunder_within_2_hours(offline, monkeypatch): + start = now_kst().replace(minute=0, second=0, microsecond=0) + items = [ + {"category": c, "fcstDate": (start + timedelta(hours=h)).strftime("%Y%m%d"), "fcstTime": (start + timedelta(hours=h)).strftime("%H%M"), "fcstValue": v} + for h in range(1, 7) for c, v in [("PTY", "1"), ("RN1", "5.0mm"), ("T1H", "20"), ("LGT", "2" if h == 1 else "0")] + ] + monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(items)) + # 앞 테스트가 받아 둔 초단기예보 캐시(비 없음)를 지워야 새 예보를 읽는다 + await REDIS.conn.delete(f"ultra:{REGION}", f"lock:ultra:{REGION}") + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + body = (await client.get("/v1/watch/summary", params={"region": REGION})).json() + assert body["now"]["rain_2h"] is True and body["now"]["thunder"] is True diff --git a/watch/app/src/main/java/kr/o2o/nalssigak/MainActivity.kt b/watch/app/src/main/java/kr/o2o/nalssigak/MainActivity.kt index 1e33be1..b48285c 100644 --- a/watch/app/src/main/java/kr/o2o/nalssigak/MainActivity.kt +++ b/watch/app/src/main/java/kr/o2o/nalssigak/MainActivity.kt @@ -50,7 +50,7 @@ class MainActivity : ComponentActivity() { } } -private enum class Page { DETAIL, SKY, TOP, PICKS, EVENTS, SUNSET, HOURS } +private enum class Page { DETAIL, EVENTS, TOP, PICKS, SUNSET, HOURS } @Composable private fun App(s: Summary?, loading: Boolean, opened: String?, onRetry: () -> Unit) { @@ -65,14 +65,13 @@ private fun App(s: Summary?, loading: Boolean, opened: String?, onRetry: () -> U StatePage(loading, onRetry) return } - // 스킨 링에서 누른 각이 있으면 그 상세부터, 아니면 하늘 장부터 + // 스킨 링에서 누른 각이 있으면 그 상세부터, 아니면 주변 축제부터 (축제가 없으면 오늘의 각부터) val detail = opened?.let { c -> (s.top + s.picks).firstOrNull { it.code == c } } val pages = buildList { if (detail != null) add(Page.DETAIL) - add(Page.SKY) + if (s.events.isNotEmpty()) add(Page.EVENTS) if (s.top.isNotEmpty()) add(Page.TOP) if (s.picks.isNotEmpty()) add(Page.PICKS) - if (s.events.isNotEmpty()) add(Page.EVENTS) if (s.sunset != null) add(Page.SUNSET) if (s.slots.isNotEmpty()) add(Page.HOURS) } @@ -81,16 +80,15 @@ private fun App(s: Summary?, loading: Boolean, opened: String?, onRetry: () -> U VerticalPager(state = state, modifier = Modifier.fillMaxSize()) { i -> when (pages[i]) { Page.DETAIL -> DetailPage(detail!!, now) - Page.SKY -> SkyPage(s, now) + Page.EVENTS -> EventsPage(s.events, now) Page.TOP -> GakListPage("오늘의 각", s.top.take(3), bgButter, medals = true, now) Page.PICKS -> GakListPage("내 각", s.picks, bgMint, medals = false, now) - Page.EVENTS -> EventsPage(s.events, now) Page.SUNSET -> SunsetPage(s.sunset!!, now) Page.HOURS -> HoursPage(s, now) } } val page = pages[state.currentPage] - val dot = if (page == Page.SUNSET || (page == Page.SKY && isDark(s.mode))) Color.White else Tok.ink + val dot = if (page == Page.SUNSET) Color.White else Tok.ink VerticalPageIndicator(pagerState = state, selectedColor = dot, unselectedColor = dot.copy(alpha = 0.35f), backgroundColor = Color.Transparent) } } diff --git a/watch/app/src/main/java/kr/o2o/nalssigak/RainComplicationService.kt b/watch/app/src/main/java/kr/o2o/nalssigak/RainComplicationService.kt index 0dba4f0..8eec0f3 100644 --- a/watch/app/src/main/java/kr/o2o/nalssigak/RainComplicationService.kt +++ b/watch/app/src/main/java/kr/o2o/nalssigak/RainComplicationService.kt @@ -10,7 +10,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlin.math.roundToInt -/** 워치 스킨 아래 칩: 글자 = 지금 기온, 제목 = 비 소식. 스킨은 제목("비 와요"·"곧 비"·"눈 와요")을 보고 빗줄기·눈송이도 그린다. */ +/** 워치 스킨 아래 칩: 글자 = 지금 기온, 제목 = 비 소식. 스킨은 제목("비 와요"·"곧 비"·"천둥 쳐요"·"눈 와요")을 보고 빗줄기·눈송이와 가운데 구름도 그린다. */ class RainComplicationService : SuspendingComplicationDataSourceService() { override suspend fun onComplicationRequest(request: ComplicationRequest): ComplicationData? { diff --git a/watch/app/src/main/java/kr/o2o/nalssigak/Screens.kt b/watch/app/src/main/java/kr/o2o/nalssigak/Screens.kt index b00cb24..4fe9887 100644 --- a/watch/app/src/main/java/kr/o2o/nalssigak/Screens.kt +++ b/watch/app/src/main/java/kr/o2o/nalssigak/Screens.kt @@ -56,17 +56,6 @@ import androidx.wear.compose.material3.Text import java.time.Duration import java.time.Instant import kotlin.math.roundToInt -import androidx.compose.animation.core.LinearEasing -import androidx.compose.foundation.layout.BoxWithConstraints -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.mutableFloatStateOf -import androidx.compose.runtime.withFrameNanos -import androidx.compose.ui.draw.shadow -import androidx.compose.ui.geometry.CornerRadius -import java.time.format.TextStyle as DateTextStyle -import java.util.Locale -import kotlin.math.cos -import kotlin.math.sin // 시안 크기는 큰 원형(227dp) 기준. 작은 원형(192dp)에서도 넘치지 않게 비율과 여백으로 잡는다. @@ -102,153 +91,6 @@ fun Clock(now: Instant, color: Color) { T(hhmm(now), 15.sp, FontFamily.Default, color.copy(alpha = 0.85f), Modifier.fillMaxWidth().padding(top = 6.dp), weight = FontWeight.Bold) } -// ───────────── 하늘 (앱 첫 장: 스킨은 초당 10장 안팎이라, 빠르게 흐르는 하늘은 여기서 60장으로) ───────────── - -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 SkyPage(s: Summary, now: Instant) { - val precip = s.precip - 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(if (precip != null) precipBrush(precip, s.mode) else skyBrush(s.mode))) { - val w = maxWidth - if (night && precip == null) Canvas(Modifier.fillMaxSize()) { - STARS.forEach { (x, y) -> drawCircle(Color.White, 1.4.dp.toPx(), Offset(size.width * x, size.height * y)) } - } - val cloudColor = when { precip == "rain" -> Color(0xFFDCE2EB); night -> Color(0xFFC9CDF0); else -> Color.White } - SKY_CLOUDS.forEach { Cloud(cloudColor, it, w) } - precip?.let { Precip(it, Modifier.fillMaxSize()) } - 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 = 32.dp)) - if (!night) SunRays(Modifier.align(Alignment.Center).offset(y = (-6).dp).size(w * 0.62f)) - Orb(night, Modifier.align(Alignment.Center).offset(y = (-6).dp).size(w * 0.44f)) { - T(top?.score?.toString() ?: "-", 38.sp, Tok.bagel, if (night) Color(0xFF2B2A5C) else Color.White) - T(top?.name ?: "날씨각", 12.sp, color = if (night) Color(0xFF2B2A5C) else Color.White) - } - 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", s.rainLabel, dark) - } - } -} - -/** 구슬 둘레의 끝이 둥근 햇살 12개. 1분에 한 바퀴 천천히 돈다 */ -@Composable -private fun SunRays(modifier: Modifier) { - val t = rememberInfiniteTransition(label = "rays") - val turn by t.animateFloat(0f, 360f, infiniteRepeatable(tween(60_000, easing = LinearEasing)), label = "turn") - Canvas(modifier.graphicsLayer { rotationZ = turn }) { - val c = Offset(size.width / 2, size.height / 2) - val r1 = size.width * 0.4f - val r2 = size.width * 0.462f - repeat(12) { i -> - val a = Math.toRadians(i * 30.0) - val dir = Offset(cos(a).toFloat(), sin(a).toFloat()) - drawLine(Color(0xFFFFB347), c + dir * r1, c + dir * r2, size.width * 0.044f, StrokeCap.Round) - } - } -} - -/** 말랑 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)) - // 해에만 볼터치 - if (!night) listOf(0.18f, 0.82f).forEach { x -> - drawOval(Color(0x73FF7A8A), Offset(size.width * x - size.width * 0.07f, size.height * 0.68f), Size(size.width * 0.14f, size.width * 0.08f)) - } - }, - contentAlignment = Alignment.Center, - ) { Column(horizontalAlignment = Alignment.CenterHorizontally) { content() } } -} - -/** 구름 한 줄: 세로 위치·너비·높이(화면 비율), 한 번 가로지르는 초, 시작 위상 */ -private class SkyCloud(val y: Float, val w: Float, val h: Float, val sec: Int, val phase: Float) - -// 위상을 엇갈려, 한쪽으로 빠질 때 다른 줄에서 새 구름이 들어온다 -private val SKY_CLOUDS = listOf( - SkyCloud(0.30f, 0.19f, 0.07f, 9, 0f), SkyCloud(0.30f, 0.14f, 0.05f, 9, 0.5f), - SkyCloud(0.56f, 0.13f, 0.05f, 6, 0.8f), SkyCloud(0.74f, 0.22f, 0.075f, 7, 0.45f), -) - -/** 왼쪽 밖에서 들어와 오른쪽 밖으로 빠지고 다시 왼쪽에서 (끝없이 흐르는 하늘) */ -@Composable -private fun Cloud(c: Color, cl: SkyCloud, screen: Dp) { - val t = rememberInfiniteTransition(label = "cloud") - val p by t.animateFloat(0f, 1f, infiniteRepeatable(tween(cl.sec * 1000, easing = LinearEasing)), label = "drift") - val w = screen * cl.w - Canvas(Modifier.offset(y = screen * cl.y).size(w, screen * cl.h).graphicsLayer { translationX = ((p + cl.phase) % 1f) * (screen + w).toPx() - w.toPx() }) { - 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)) - } -} - -// 빗줄기·눈송이 하나: 가로 위치, 시작 위상, 한 번 떨어지는 데 걸리는 초, 크기 (모두 고정값이라 매번 같은 자리) -private class Drop(val x: Float, val phase: Float, val sec: Float, val size: Float) - -private val DROPS = java.util.Random(7).let { r -> List(42) { Drop(r.nextFloat(), r.nextFloat(), 0.7f + r.nextFloat() * 0.5f, 0.6f + r.nextFloat() * 0.4f) } } - -/** 비는 추적추적 비스듬히, 눈은 천천히 흔들리며. 화면이 켜져 있는 동안만 그린다 */ -@Composable -private fun Precip(kind: String, modifier: Modifier) { - var time by remember { mutableFloatStateOf(0f) } - LaunchedEffect(Unit) { - val start = withFrameNanos { it } - while (true) withFrameNanos { time = (it - start) / 1e9f } - } - val snow = kind == "snow" - Canvas(modifier) { - val h = size.height - DROPS.forEachIndexed { i, d -> - val period = if (snow) d.sec * 7f else d.sec - val p = (time / period + d.phase) % 1f - val y = p * (h + 40.dp.toPx()) - 20.dp.toPx() - if (snow) { - val x = d.x * size.width + sin((time / 2f + d.phase) * 2f * Math.PI.toFloat()) * 6.dp.toPx() - drawCircle(Color.White.copy(alpha = 0.9f), (1.5f + 2f * d.size).dp.toPx(), Offset(x, y)) - } else { - val len = 14.dp.toPx() * d.size - val x = d.x * size.width + y * 0.12f - drawLine(Color(0xCCEAF2FF), Offset(x, y), Offset(x - len * 0.12f, y - len), 1.5.dp.toPx(), StrokeCap.Round) - // 셋 중 하나는 바닥에서 톡 튄다 - if (i % 3 == 0 && p > 0.86f) { - val k = (p - 0.86f) / 0.14f - drawCircle(Color(0x99EAF2FF), (2f + 6f * k).dp.toPx(), Offset(x, h * (0.8f + 0.12f * d.x)), style = Stroke(1.dp.toPx()), alpha = 1f - k) - } - } - } - } -} - -@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) - } -} - // ───────────── 워치 스킨에서 누른 각 ───────────── @Composable diff --git a/watch/app/src/main/java/kr/o2o/nalssigak/Summary.kt b/watch/app/src/main/java/kr/o2o/nalssigak/Summary.kt index cf82459..de85967 100644 --- a/watch/app/src/main/java/kr/o2o/nalssigak/Summary.kt +++ b/watch/app/src/main/java/kr/o2o/nalssigak/Summary.kt @@ -40,6 +40,8 @@ data class Summary( val nowIcon: String?, val rainText: String?, val rain2h: Boolean?, + /** 2시간 안에 낙뢰 예보 */ + val thunder: Boolean?, val warning: String?, val top: List, val picks: List, @@ -51,16 +53,17 @@ data class Summary( /** 컴플리케이션·타일에 올릴 각: 내 각 첫 번째, 없으면 오늘 1위 */ val myGak: Gak? get() = picks.firstOrNull() ?: top.firstOrNull() - /** 비·눈 화면: "rain" | "snow" | null. 지금 칸이 눈이면 눈, 지금 칸이 비거나 2시간 안에 비 소식이면 비 */ + /** 비·눈: "rain" | "snow" | null. 지금 칸이 눈이면 눈, 지금 칸이 비거나 2시간 안에 비 소식이면 비 */ val precip: String? get() = when { nowIcon == "snow" -> "snow" nowIcon == "rain" || rain2h == true -> "rain" else -> null } - /** 스킨 칩의 비 소식. 비·눈 화면과 어긋나지 않게 precip 을 따른다 */ + /** 스킨 칩의 비 소식. 스킨은 이 글자를 보고 가운데를 비구름·천둥 구름·눈구름으로 바꾼다 */ val rainLabel: String get() = when { precip == "snow" -> "눈 와요" + thunder == true -> "천둥 쳐요" nowIcon == "rain" -> "비 와요" precip == "rain" -> "곧 비" rain2h == false -> "비 없음" @@ -95,6 +98,7 @@ fun parseSummary(json: String): Summary { nowIcon = now?.str("icon"), rainText = now?.str("text"), rain2h = now?.takeIf { it.has("rain_2h") }?.getBoolean("rain_2h"), + thunder = now?.takeIf { it.has("thunder") }?.getBoolean("thunder"), warning = o.str("warning"), top = o.list("top", ::gak), picks = o.list("picks", ::gak), @@ -117,9 +121,9 @@ object SummaryRepo { /** 캐시가 refresh_at 전이면 캐시, 아니면 새로 받는다. 받기 실패하면 지난 캐시라도. 네트워크를 쓰니 메인 스레드에서 부르지 않는다. */ fun load(context: Context, force: Boolean = false): Summary? = fetch(context, force)?.let { s -> - // 디버그 빌드 확인용: shared_prefs/debug.xml 의 precip(rain|snow)로 비·눈 화면을 강제로 띄운다 + // 디버그 빌드 확인용: shared_prefs/debug.xml 의 precip(rain|snow|thunder)로 스킨의 비·눈·천둥을 강제로 띄운다 val forced = if (BuildConfig.DEBUG) context.getSharedPreferences("debug", Context.MODE_PRIVATE).getString("precip", null) else null - if (forced == null) s else s.copy(nowIcon = forced, rain2h = forced == "rain") + if (forced == null) s else s.copy(nowIcon = if (forced == "thunder") "rain" else forced, rain2h = forced != "snow", thunder = forced == "thunder") } private fun fetch(context: Context, force: Boolean): Summary? { diff --git a/watch/app/src/main/java/kr/o2o/nalssigak/Theme.kt b/watch/app/src/main/java/kr/o2o/nalssigak/Theme.kt index ca0ec9f..7244695 100644 --- a/watch/app/src/main/java/kr/o2o/nalssigak/Theme.kt +++ b/watch/app/src/main/java/kr/o2o/nalssigak/Theme.kt @@ -18,7 +18,6 @@ object Tok { 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)) @@ -34,16 +33,6 @@ fun skyBrush(mode: String): Brush = when (mode) { else -> v(0f to 0xFF9FD3FF, 0.55f to 0xFFCFE9FF, 1f to 0xFFF1F8FF) } -/** 비·눈 오는 날 하늘. 밤에는 어두운 회청색 */ -fun precipBrush(kind: String, mode: String): Brush = when { - mode == "night" -> v(0f to 0xFF1C2238, 0.6f to 0xFF2E3650, 1f to 0xFF434B66) - kind == "snow" -> v(0f to 0xFFB8C4D6, 0.55f to 0xFFDFE6F0, 1f to 0xFFF4F7FB) - else -> v(0f to 0xFF7F93AD, 0.55f to 0xFFA9B7C9, 1f to 0xFFD5DDE8) -} - -/** 하늘 위 글자가 흰색이어야 하는 시간대 */ -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) diff --git a/watch/watchface/gen_watchface.py b/watch/watchface/gen_watchface.py index c7f6bb9..7b3e7b9 100644 --- a/watch/watchface/gen_watchface.py +++ b/watch/watchface/gen_watchface.py @@ -77,6 +77,33 @@ def sun_rays(): ''' +# 비·눈·천둥 때 해 대신 가운데 구름: 몸통, 아래 그늘. 점수가 흰 글씨라 눈구름도 너무 밝지 않게 +CLOUD_ORB = {"rain": ("#FF8796B0", "#4D394A66"), "thunder": ("#FF5F6684", "#66232A45"), "snow": ("#FF9FB2D3", "#40394A66")} + +def cloud_orb(kind): + """해 구슬 자리에 몽실한 구름 하나 (봉우리 셋 + 둥근 바닥). 천둥이면 오른쪽 아래로 번개, 5초에 한 번 화면이 번쩍""" + body, shade = CLOUD_ORB[kind] + k = ORB / 136 + puffs = [(10, 34, 60), (36, 8, 80), (80, 44, 52)] + shapes = "".join(f'' for x, y, d in puffs) + shapes += f'' + shapes += f'' + shapes += f'' + out = f'{AMB0}{shapes}' + if kind == "thunder": + bolt = [(26, 2), (12, 28), (28, 28), (14, 54)] + lines = "".join(f'' for a, b in zip(bolt, bolt[1:])) + out += f'{AMB0}{lines}' + out += (f'{AMB0}' + f'') + return out + +NIGHT_EXPR = "[HOUR_0_23] < 5 || [HOUR_0_23] >= 21" + +def sun_or_moon(): + """맑을 때(또는 앱 값이 아직 없을 때) 가운데: 밤엔 달빛 구슬, 낮엔 햇살 두른 해""" + return f'{orb_fill(MOON)}{sun_rays()}{orb_fill(SUN)}' + def mode_block(colors, pos, ink, night=False): parts = [sky(colors, pos)] if night: @@ -156,7 +183,8 @@ def chip(x, w, icon, expr): def precip_slot(): """화면 전체를 덮는 숨은 칸. 날씨각 앱(RainComplicationService)이 글자 = 기온, 제목 = 비 소식을 주면 - 아래에 기온·비 칩을 그리고, 비 소식이 "비 와요"·"곧 비"면 빗줄기, "눈 와요"면 눈송이를 그린다. + 아래에 기온·비 칩을 그리고, 비 소식이 "비 와요"·"곧 비"면 빗줄기와 비구름, "천둥 쳐요"면 빗줄기와 번개 구름, + "눈 와요"면 눈송이와 눈구름을 가운데 해 자리에 그린다. 날씨 값은 이 칸 안에서만 읽혀서 맑을 때 해·달 구슬도 여기서 그린다. 터치는 막지 않게 BoundingOval 을 1px 로 둔다. 주기는 60 의 약수여야 분이 바뀔 때 튀지 않는다.""" import random r = random.Random(7) @@ -185,22 +213,37 @@ def precip_slot(): + + + + {shade("#80394766")} + {"".join(drops)} + {cloud_orb("thunder")} + {shade("#66485A78")} {"".join(drops)} + {cloud_orb("rain")} {shade("#40A0AEC4")} {"".join(flakes)} + {cloud_orb("snow")} + {sun_or_moon()} {chip(108, 104, "thermo", "[COMPLICATION.TEXT]")} {chip(220, 122, "umbrella", "[COMPLICATION.TITLE]")} - + + + + {sun_or_moon()} + + ''' def event_slot(): @@ -230,7 +273,7 @@ exprs = "\n ".join(f'\n {mode_block(v[1], v[2], v[3])}\n ' for k, v in MODES.items()) xml = f''' - @@ -247,13 +290,8 @@ xml = f''' + {precip_slot()} - - - = 21]]> - {orb_fill(MOON)} - {sun_rays()}{orb_fill(SUN)} - {clock("#FFFFFFFF", ambient_visible=True)} {orb_slot()} {"".join(ring_slot(i, a) for i, a in enumerate(ANGLES))} diff --git a/watch/watchface/src/main/res/raw/watchface.xml b/watch/watchface/src/main/res/raw/watchface.xml index acc11d3..a0bc3c4 100644 --- a/watch/watchface/src/main/res/raw/watchface.xml +++ b/watch/watchface/src/main/res/raw/watchface.xml @@ -1,5 +1,5 @@ - @@ -147,15 +147,125 @@ + + + = 21]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -261,6 +371,7 @@ + @@ -369,7 +480,20 @@ + + + + + + + + + + + + + @@ -388,17 +512,14 @@ - - - - - = 21]]> - + + + = 21]]> + - - + @@ -406,7 +527,9 @@ - + + + @@ -444,7 +567,7 @@ - + @@ -471,7 +594,7 @@ - + @@ -498,7 +621,7 @@ - + @@ -525,7 +648,7 @@ - + @@ -552,7 +675,7 @@ - + @@ -579,7 +702,7 @@ - +