diff --git a/backend/router/router.py b/backend/router/router.py index 2038e3b..6598437 100644 --- a/backend/router/router.py +++ b/backend/router/router.py @@ -14,6 +14,7 @@ from router.v1.reaction.reaction import router as reaction_router from router.v1.region.region import router as region_router from router.v1.season.season import router as season_router from router.v1.sky.sky import router as sky_router +from router.v1.watch.watch import router as watch_router from router.v1.weather.weather import router as weather_router from router.v1.week.week import router as week_router @@ -39,6 +40,7 @@ app.include_router(season_router) app.include_router(feed_router) app.include_router(auth_router) app.include_router(reaction_router) +app.include_router(watch_router) class Res_Health(Res_WebPacketProtocol): diff --git a/backend/router/v1/watch/__init__.py b/backend/router/v1/watch/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/router/v1/watch/protocol.py b/backend/router/v1/watch/protocol.py new file mode 100644 index 0000000..9a7fac7 --- /dev/null +++ b/backend/router/v1/watch/protocol.py @@ -0,0 +1,47 @@ +from datetime import datetime +from typing import Literal, Optional + +from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol +from router.v1.feed.protocol import TopIndex + + +class WatchNow(WebPacketProtocol): + temp_c: Optional[float] = None + icon: Optional[str] = None + rain_2h: Optional[bool] = None + text: Optional[str] = None + + +class WatchSunset(WebPacketProtocol): + is_today: bool + score: int + grade_label: str + sunset_at: datetime + best_at: datetime + + +class WatchSlot(WebPacketProtocol): + at: datetime + icon: str + temp_c: Optional[float] = None + rain_prob: Optional[int] = None + + +class WatchTimeline(WebPacketProtocol): + start_at: datetime + kind: Literal["gak", "sunset"] + + +class Res_WatchSummary(Res_WebPacketProtocol): + region_code: Optional[str] = None + region_name: Optional[str] = None + issued_at: Optional[datetime] = None + refresh_at: Optional[datetime] = None + mode: Optional[Literal["morning", "day", "evening", "night"]] = None + now: Optional[WatchNow] = None + warning: Optional[str] = None + top: list[TopIndex] = [] + picks: list[TopIndex] = [] + sunset: Optional[WatchSunset] = None + slots: list[WatchSlot] = [] + timeline: list[WatchTimeline] = [] diff --git a/backend/router/v1/watch/watch.py b/backend/router/v1/watch/watch.py new file mode 100644 index 0000000..757d34f --- /dev/null +++ b/backend/router/v1/watch/watch.py @@ -0,0 +1,98 @@ +import asyncio +from datetime import datetime, timedelta +from typing import Optional + +from fastapi import APIRouter, Depends, Query + +from common.database.model.models import SkyScore +from common.enums import ErrorType, SkyGrade +from common.models.errors import error_info +from common.utils.kma_time import KST, now_kst +from router.v1.watch.protocol import Res_WatchSummary, WatchNow, WatchSlot, WatchSunset, WatchTimeline +from services.calc.sky_score import GRADE_LABEL +from services.calc.sun import sun_times +from services.feed_service import _SUNSET_FULL, _top, feed_ttl_sec, slot_of +from services.index_service import IndexService +from services.now_service import NowService +from services.sky_service import SkyService +from services.weather_service import WeatherService + +router = APIRouter(prefix="/v1/watch", tags=["watch"]) + +MAX_PICKS = 3 +# 워치 스킨이 큰 원(1위) + 둘레 링 6개(2~7위)를 채운다 +TOP_N = 7 + + +def _best(score: SkyScore, kind: str) -> datetime: + return datetime.fromisoformat(next(b["at"] for b in score.best_times if b["kind"] == kind)).astimezone(KST) + + +def timeline(now: datetime, sunset: Optional[SkyScore], is_today: bool) -> list[WatchTimeline]: + """컴플리케이션이 언제 무엇을 보여줄지. 오늘 노을이 볼 만하면(60점 이상) 일몰 2시간 전부터 보랏빛 하늘까지 노을, 나머지는 각.""" + if sunset is None or not is_today or sunset.score < _SUNSET_FULL: + return [WatchTimeline(start_at=now, kind="gak")] + start, end = _best(sunset, "sun") - timedelta(hours=2), _best(sunset, "twilight") + if now >= end: + return [WatchTimeline(start_at=now, kind="gak")] + items = [WatchTimeline(start_at=now, kind="gak")] if now < start else [] + return items + [WatchTimeline(start_at=max(start, now), kind="sunset"), WatchTimeline(start_at=end, kind="gak")] + + +@router.get("/summary", response_model=Res_WatchSummary, response_model_exclude_none=True, summary="워치 한 번에: 지금 날씨, 각 1~7위·내 각, 노을, 남은 3시간 칸, 컴플리케이션 시간표") +async def get_watch_summary( + region: str = Query(..., description="구 행정코드"), + pick: Optional[str] = Query(None, description="내 각 코드, 쉼표로 최대 3개 (예: running,laundry)"), + weather: WeatherService = Depends(), + now_service: NowService = Depends(), + sky: SkyService = Depends(), + index: IndexService = Depends(), +) -> Res_WatchSummary: + (err_t, today), (err_n, now_w), (err_s, view), (err_i, board) = await asyncio.gather( + weather.today(region), now_service.now(region), sky.view(region), index.board(region), + ) + today = today if err_t is ErrorType.SUCCESS else None + now_w = now_w if err_n is ErrorType.SUCCESS else None + view = view if err_s is ErrorType.SUCCESS else None + board = board if err_i is ErrorType.SUCCESS else None + found = next((x.region for x in (today, now_w, view, board) if x is not None), None) + if found is None: + return Res_WatchSummary(result=error_info(err_t)) + + now = now_kst() + sunset_at = sun_times(now.date(), float(found.lat), float(found.lon)).sunset_at + res = Res_WatchSummary( + region_code=found.code, region_name=found.name, issued_at=now, refresh_at=now + timedelta(seconds=feed_ttl_sec(now, sunset_at)), + mode=slot_of(now, sunset_at), + ) + + if today is not None: + past = [s for s in today.slots if s.at <= now] + cur = past[-1] if past else (today.slots[0] if today.slots else None) + if cur is not None: + res.now = WatchNow(temp_c=float(cur.row.temp_c) if cur.row else None, icon=cur.icon) + res.slots = [ + WatchSlot(at=s.at.astimezone(KST), icon=s.icon, temp_c=float(s.row.temp_c) if s.row else None, rain_prob=s.row.rain_prob if s.row else None) + 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.warning = now_w.warnings[0].text if now_w.warnings else None + + if board is not None: + res.top = [_top(i) for i in board.items[:TOP_N]] + codes = [c.strip() for c in (pick or "").split(",") if c.strip()][:MAX_PICKS] + by_code = {i.definition.code: i for i in board.items} + res.picks = [_top(by_code[c]) for c in codes if c in by_code] + + target, is_today = None, False + if view is not None: + is_today = now < sunset_at + target = view.sunset if is_today else next((x for x in view.days if x.score_date > now.date()), None) + if target is not None: + res.sunset = WatchSunset( + is_today=is_today, score=target.score, grade_label=GRADE_LABEL[SkyGrade(target.grade)], + sunset_at=_best(target, "sun"), best_at=_best(target, "peak"), + ) + res.timeline = timeline(now, target, is_today) + return res diff --git a/backend/tests/test_watch.py b/backend/tests/test_watch.py new file mode 100644 index 0000000..e22bb28 --- /dev/null +++ b/backend/tests/test_watch.py @@ -0,0 +1,62 @@ +from datetime import datetime, timedelta +from types import SimpleNamespace + +import pytest +from httpx import ASGITransport, AsyncClient + +from common.utils.kma_time import KST +from router.router import app +from router.v1.watch.watch import timeline + +REGION = "1141000000" +SUN = datetime(2026, 10, 6, 18, 0, tzinfo=KST) + + +def _sunset(score: int) -> SimpleNamespace: + return SimpleNamespace(score=score, best_times=[ + {"at": SUN.isoformat(), "kind": "sun", "label": "해 져요"}, + {"at": (SUN + timedelta(minutes=15)).isoformat(), "kind": "peak", "label": "가장 붉을 때"}, + {"at": (SUN + timedelta(minutes=30)).isoformat(), "kind": "twilight", "label": "보랏빛 하늘"}, + ]) + + +def test_timeline_switches_to_sunset_two_hours_before_and_back_after_twilight(): + now = SUN.replace(hour=12) + assert [(t.start_at.hour, t.start_at.minute, t.kind) for t in timeline(now, _sunset(80), True)] == [ + (12, 0, "gak"), (16, 0, "sunset"), (18, 30, "gak"), + ] + + +def test_timeline_starts_with_sunset_inside_window(): + now = SUN.replace(hour=17) + assert [t.kind for t in timeline(now, _sunset(80), True)] == ["sunset", "gak"] + + +def test_timeline_skips_weak_tomorrow_or_finished_sunset(): + noon, late = SUN.replace(hour=12), SUN.replace(hour=19) + assert [t.kind for t in timeline(noon, _sunset(59), True)] == ["gak"] + assert [t.kind for t in timeline(noon, _sunset(80), False)] == ["gak"] + assert [t.kind for t in timeline(late, _sunset(80), True)] == ["gak"] + assert [t.kind for t in timeline(noon, None, True)] == ["gak"] + + +@pytest.mark.anyio +async def test_watch_summary_bundles_now_top_picks_sunset(offline): + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + body = (await client.get("/v1/watch/summary", params={"region": REGION, "pick": "laundry, nope,running,carwash,bike"})).json() + assert body["result"]["success"] is True + assert body["region_code"] == REGION and body["mode"] in ("morning", "day", "evening", "night") + assert body["refresh_at"] > body["issued_at"] + assert body["now"]["rain_2h"] is False and body["now"]["temp_c"] == 20.0 + assert [t["rank"] for t in body["top"]] == list(range(1, 8)) + assert [p["code"] for p in body["picks"]] == ["laundry", "running"] + assert body["sunset"]["best_at"] > body["sunset"]["sunset_at"] + assert all(s["at"] > body["issued_at"] for s in body["slots"]) + assert body["timeline"][0]["start_at"] == body["issued_at"] + + +@pytest.mark.anyio +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 diff --git a/watch/.gitignore b/watch/.gitignore new file mode 100644 index 0000000..b33ab3f --- /dev/null +++ b/watch/.gitignore @@ -0,0 +1,7 @@ +.gradle/ +build/ +local.properties +.idea/ +*.iml +*.jks +*.keystore diff --git a/watch/app/build.gradle.kts b/watch/app/build.gradle.kts new file mode 100644 index 0000000..ad65748 --- /dev/null +++ b/watch/app/build.gradle.kts @@ -0,0 +1,41 @@ +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.plugin.compose") +} + +android { + namespace = "kr.o2o.nalssigak" + compileSdk = 37 + + defaultConfig { + applicationId = "kr.o2o.nalssigak" + minSdk = 30 + targetSdk = 34 + versionCode = 1 + versionName = "0.1" + } + buildTypes { + // 에뮬레이터에서 본 맥의 로컬 백엔드 (compose 포트 9810) + debug { buildConfigField("String", "API_BASE", "\"http://10.0.2.2:9810\"") } + // 운영 서버 https 주소는 -PNALSSIGAK_API_BASE=… 또는 ~/.gradle/gradle.properties 로 + release { + buildConfigField("String", "API_BASE", "\"${providers.gradleProperty("NALSSIGAK_API_BASE").getOrElse("")}\"") + isMinifyEnabled = true + isShrinkResources = true + } + } + // 오픈소스 라이선스 전문을 앱에 같이 싣는다 (MIT·OFL 고지 조건) + sourceSets["main"].assets.directories.add("../licenses") + buildFeatures { + compose = true + buildConfig = true + } +} + +dependencies { + implementation("androidx.activity:activity-compose:1.13.0") + implementation("androidx.wear.compose:compose-material3:1.7.0") + implementation("androidx.wear.tiles:tiles:1.6.2") + implementation("androidx.concurrent:concurrent-futures:1.3.0") + implementation("androidx.wear.watchface:watchface-complications-data-source-ktx:1.3.0") +} diff --git a/watch/app/src/debug/AndroidManifest.xml b/watch/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..678b73c --- /dev/null +++ b/watch/app/src/debug/AndroidManifest.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/watch/app/src/main/AndroidManifest.xml b/watch/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..01402e0 --- /dev/null +++ b/watch/app/src/main/AndroidManifest.xml @@ -0,0 +1,154 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/watch/app/src/main/java/kr/o2o/nalssigak/GakComplicationService.kt b/watch/app/src/main/java/kr/o2o/nalssigak/GakComplicationService.kt new file mode 100644 index 0000000..221fa55 --- /dev/null +++ b/watch/app/src/main/java/kr/o2o/nalssigak/GakComplicationService.kt @@ -0,0 +1,58 @@ +package kr.o2o.nalssigak + +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +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 { gakData(this, type, hhmm(it.bestAt), "노을", it.score, "sunset") } + // 각 점수를 못 받았으면 노을이라도 + val default = s.myGak?.let { gakData(this, type, it.score.toString(), it.name.removeSuffix("각"), it.score, it.icon, it.code) } ?: 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 = gakData(this, type, "82", "야장", 82, "yajang") +} + +/** 3D 아이콘은 작은 이미지로 함께 보낸다. 그릴지 말지는 시계 화면이 정한다. 누르면 날씨각 앱이 열린다. */ +/** 누르면 앱이 열린다. code 를 주면 그 각 상세 장부터 */ +fun gakData(context: Context, type: ComplicationType, text: String, title: String, score: Int, icon: String, code: String? = null): ComplicationData { + val img = SmallImage.Builder(Icon.createWithResource(context, iconRes(icon)), SmallImageType.ICON).build() + val t = PlainComplicationText.Builder(text).build() + val ti = PlainComplicationText.Builder(title).build() + val desc = PlainComplicationText.Builder("$title $text").build() + // 각마다 다른 PendingIntent 여야 extra 가 섞이지 않고, 이미 열린 앱이 있어도 새로 열어야 누른 각이 첫 장에 온다 + val intent = Intent(context, MainActivity::class.java).putExtra(EXTRA_GAK, code) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) + val open = PendingIntent.getActivity(context, code.hashCode(), intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + return if (type == ComplicationType.RANGED_VALUE) { + RangedValueComplicationData.Builder(score.toFloat(), 0f, 100f, desc).setText(t).setTitle(ti).setSmallImage(img).setTapAction(open).build() + } else { + ShortTextComplicationData.Builder(t, desc).setTitle(ti).setSmallImage(img).setTapAction(open).build() + } +} diff --git a/watch/app/src/main/java/kr/o2o/nalssigak/GakTileService.kt b/watch/app/src/main/java/kr/o2o/nalssigak/GakTileService.kt new file mode 100644 index 0000000..14793c1 --- /dev/null +++ b/watch/app/src/main/java/kr/o2o/nalssigak/GakTileService.kt @@ -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 = + CallbackToFutureAdapter.getFuture { done -> + thread { done.set(tile(SummaryRepo.load(this))) } + "gak-tile" + } + + /** 이미지 id 는 아이콘 이름 그대로. 목록 없이 요청하면 전부 달라는 뜻이라, 버전에 적어 둔 이름들을 담는다 */ + override fun onTileResourcesRequest(requestParams: RequestBuilders.ResourcesRequest): ListenableFuture = + 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() +} diff --git a/watch/app/src/main/java/kr/o2o/nalssigak/MainActivity.kt b/watch/app/src/main/java/kr/o2o/nalssigak/MainActivity.kt new file mode 100644 index 0000000..bbd76eb --- /dev/null +++ b/watch/app/src/main/java/kr/o2o/nalssigak/MainActivity.kt @@ -0,0 +1,95 @@ +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 + +/** 컴플리케이션 탭이 실어 보내는 각 코드 */ +const val EXTRA_GAK = "gak" + +class MainActivity : ComponentActivity() { + private var summary by mutableStateOf(null) + private var loading by mutableStateOf(true) + + private val askLocation = registerForActivityResult(ActivityResultContracts.RequestPermission()) { load() } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val opened = intent.getStringExtra(EXTRA_GAK) + setContent { MaterialTheme { App(summary, loading, opened) { 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 { DETAIL, TOP, PICKS, SUNSET, HOURS } + +@Composable +private fun App(s: Summary?, loading: Boolean, opened: String?, 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 detail = opened?.let { c -> (s.top + s.picks).firstOrNull { it.code == c } } + val pages = buildList { + if (detail != null) add(Page.DETAIL) + 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) + } + if (pages.isEmpty()) { + StatePage(loading = false, onRetry) + return + } + val state = rememberPagerState { pages.size } + Box(Modifier.fillMaxSize()) { + VerticalPager(state = state, modifier = Modifier.fillMaxSize()) { i -> + when (pages[i]) { + Page.DETAIL -> DetailPage(detail!!, now) + Page.TOP -> GakListPage("오늘의 각", s.top.take(3), 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 dot = if (pages[state.currentPage] == 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 new file mode 100644 index 0000000..0dba4f0 --- /dev/null +++ b/watch/app/src/main/java/kr/o2o/nalssigak/RainComplicationService.kt @@ -0,0 +1,27 @@ +package kr.o2o.nalssigak + +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.ShortTextComplicationData +import androidx.wear.watchface.complications.datasource.ComplicationRequest +import androidx.wear.watchface.complications.datasource.SuspendingComplicationDataSourceService +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import kotlin.math.roundToInt + +/** 워치 스킨 아래 칩: 글자 = 지금 기온, 제목 = 비 소식. 스킨은 제목("비 와요"·"곧 비"·"눈 와요")을 보고 빗줄기·눈송이도 그린다. */ +class RainComplicationService : SuspendingComplicationDataSourceService() { + + override suspend fun onComplicationRequest(request: ComplicationRequest): ComplicationData? { + val s = withContext(Dispatchers.IO) { SummaryRepo.load(this@RainComplicationService) } ?: return null + return data(s.tempC?.let { "${it.roundToInt()}°" } ?: "-°", s.rainLabel) + } + + override fun getPreviewData(type: ComplicationType): ComplicationData = data("20°", "비 없음") + + private fun data(temp: String, rain: String) = ShortTextComplicationData.Builder( + PlainComplicationText.Builder(temp).build(), + PlainComplicationText.Builder("$temp $rain").build(), + ).setTitle(PlainComplicationText.Builder(rain).build()).build() +} diff --git a/watch/app/src/main/java/kr/o2o/nalssigak/RankComplicationService.kt b/watch/app/src/main/java/kr/o2o/nalssigak/RankComplicationService.kt new file mode 100644 index 0000000..e194e23 --- /dev/null +++ b/watch/app/src/main/java/kr/o2o/nalssigak/RankComplicationService.kt @@ -0,0 +1,28 @@ +package kr.o2o.nalssigak + +import androidx.wear.watchface.complications.data.ComplicationData +import androidx.wear.watchface.complications.data.ComplicationType +import androidx.wear.watchface.complications.datasource.ComplicationRequest +import androidx.wear.watchface.complications.datasource.SuspendingComplicationDataSourceService +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +/** 워치 스킨용 N위 각. 칸 하나에 공급원 하나라 순위마다 서비스를 하나씩 둔다 (큰 원 1위, 둘레 링 2~7위). */ +open class RankComplicationService(private val rank: Int) : SuspendingComplicationDataSourceService() { + + override suspend fun onComplicationRequest(request: ComplicationRequest): ComplicationData? { + val s = withContext(Dispatchers.IO) { SummaryRepo.load(this@RankComplicationService) } ?: return null + val g = s.top.getOrNull(rank - 1) ?: return null + return gakData(this, request.complicationType, g.score.toString(), g.name, g.score, g.icon, g.code) + } + + override fun getPreviewData(type: ComplicationType): ComplicationData = gakData(this, type, "${90 - rank * 2}", "${rank}위", 90 - rank * 2, "sun_cloud") +} + +class Rank1ComplicationService : RankComplicationService(1) +class Rank2ComplicationService : RankComplicationService(2) +class Rank3ComplicationService : RankComplicationService(3) +class Rank4ComplicationService : RankComplicationService(4) +class Rank5ComplicationService : RankComplicationService(5) +class Rank6ComplicationService : RankComplicationService(6) +class Rank7ComplicationService : RankComplicationService(7) diff --git a/watch/app/src/main/java/kr/o2o/nalssigak/Screens.kt b/watch/app/src/main/java/kr/o2o/nalssigak/Screens.kt new file mode 100644 index 0000000..1877be3 --- /dev/null +++ b/watch/app/src/main/java/kr/o2o/nalssigak/Screens.kt @@ -0,0 +1,271 @@ +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.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.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 kotlin.math.roundToInt + +// 시안 크기는 큰 원형(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) +} + +// ───────────── 워치 스킨에서 누른 각 ───────────── + +@Composable +fun DetailPage(g: Gak, now: Instant) { + Box(Modifier.fillMaxSize().background(bgButter)) { + Clock(now, Tok.ink) + Column(Modifier.fillMaxSize().padding(horizontal = 30.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { + Box( + Modifier.size(96.dp).drawBehind { + val stroke = 6.dp.toPx() + val arc = Size(size.width - stroke, size.height - stroke) + val tl = Offset(stroke / 2, stroke / 2) + drawCircle(Tok.stat) + drawArc(Tok.shade, -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, 36.dp) + T(g.score.toString(), 24.sp, Tok.bagel, Tok.ink) + } + } + Spacer(Modifier.height(6.dp)) + T(g.name, 17.sp, color = Tok.ink) + T("오늘 ${g.rank}위", 10.sp, FontFamily.Default, Tok.ink.copy(alpha = 0.7f), weight = FontWeight.Bold) + g.summary?.let { + Spacer(Modifier.height(6.dp)) + T(it, 11.sp, FontFamily.Default, Tok.ink, Modifier.mallang().padding(horizontal = 10.dp, vertical = 6.dp), maxLines = 3) + } + } + } +} + +// ───────────── 2·3. 오늘의 각 · 내 각 ───────────── + +@Composable +fun GakListPage(title: String, items: List, bg: Brush, medals: Boolean, now: Instant) { + var open by remember { mutableStateOf(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) + } + } +} diff --git a/watch/app/src/main/java/kr/o2o/nalssigak/Summary.kt b/watch/app/src/main/java/kr/o2o/nalssigak/Summary.kt new file mode 100644 index 0000000..1b61961 --- /dev/null +++ b/watch/app/src/main/java/kr/o2o/nalssigak/Summary.kt @@ -0,0 +1,168 @@ +package kr.o2o.nalssigak + +import android.Manifest +import android.content.ComponentName +import android.content.Context +import android.content.pm.PackageManager +import android.location.LocationManager +import android.util.Log +import androidx.wear.tiles.TileService +import androidx.wear.watchface.complications.datasource.ComplicationDataSourceUpdateRequester +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?, + /** 지금 3시간 칸 아이콘 (sun, rain, snow …) */ + val nowIcon: String?, + val rainText: String?, + val rain2h: Boolean?, + val warning: String?, + val top: List, + val picks: List, + val sunset: Sunset?, + val slots: List, + val timeline: List, +) { + /** 컴플리케이션·타일에 올릴 각: 내 각 첫 번째, 없으면 오늘 1위 */ + val myGak: Gak? get() = picks.firstOrNull() ?: top.firstOrNull() + + /** 비·눈 화면: "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" -> "눈 와요" + nowIcon == "rain" -> "비 와요" + precip == "rain" -> "곧 비" + rain2h == false -> "비 없음" + else -> "-" + } +} + +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 JSONObject.list(k: String, f: (JSONObject) -> T): List { + 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"), + nowIcon = now?.str("icon"), + 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? = fetch(context, force)?.let { s -> + // 디버그 빌드 확인용: shared_prefs/debug.xml 의 precip(rain|snow)로 비·눈 화면을 강제로 띄운다 + 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") + } + + private fun fetch(context: Context, force: Boolean): 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() + refreshSurfaces(context) + fresh + } catch (e: Exception) { + Log.w(TAG, "summary 받기 실패, 캐시 사용", e) + cached + } + } + + /** 새 값을 받으면 시계 화면 칸·타일을 모두 다시 그리게 한다. 칸마다 갱신 시점이 달라 순위가 섞이는 걸 막는다. + * 다시 불린 칸들은 방금 저장한 캐시를 읽으니 서버를 또 부르지 않는다. */ + private fun refreshSurfaces(context: Context) { + val sources = listOf(GakComplicationService::class.java, RainComplicationService::class.java, Rank1ComplicationService::class.java, + Rank2ComplicationService::class.java, Rank3ComplicationService::class.java, Rank4ComplicationService::class.java, + Rank5ComplicationService::class.java, Rank6ComplicationService::class.java, Rank7ComplicationService::class.java) + sources.forEach { ComplicationDataSourceUpdateRequester.create(context, ComponentName(context, it)).requestUpdateAll() } + TileService.getUpdater(context).requestUpdate(GakTileService::class.java) + } + + 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() + } + } +} diff --git a/watch/app/src/main/java/kr/o2o/nalssigak/Theme.kt b/watch/app/src/main/java/kr/o2o/nalssigak/Theme.kt new file mode 100644 index 0000000..9504e07 --- /dev/null +++ b/watch/app/src/main/java/kr/o2o/nalssigak/Theme.kt @@ -0,0 +1,62 @@ +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) = 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) +} + +// 카드·장 배경 (.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") diff --git a/watch/app/src/main/res/drawable-nodpi/e_baseball.png b/watch/app/src/main/res/drawable-nodpi/e_baseball.png new file mode 100644 index 0000000..f3d8487 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_baseball.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_bear.png b/watch/app/src/main/res/drawable-nodpi/e_bear.png new file mode 100644 index 0000000..2640eca Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_bear.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_bike.png b/watch/app/src/main/res/drawable-nodpi/e_bike.png new file mode 100644 index 0000000..0be9901 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_bike.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_bronze.png b/watch/app/src/main/res/drawable-nodpi/e_bronze.png new file mode 100644 index 0000000..9b02e64 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_bronze.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_camping.png b/watch/app/src/main/res/drawable-nodpi/e_camping.png new file mode 100644 index 0000000..f04d077 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_camping.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_carwash.png b/watch/app/src/main/res/drawable-nodpi/e_carwash.png new file mode 100644 index 0000000..5c21a5b Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_carwash.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_chestnut.png b/watch/app/src/main/res/drawable-nodpi/e_chestnut.png new file mode 100644 index 0000000..9c694e7 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_chestnut.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_chimaek.png b/watch/app/src/main/res/drawable-nodpi/e_chimaek.png new file mode 100644 index 0000000..a0c4f49 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_chimaek.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_cloud.png b/watch/app/src/main/res/drawable-nodpi/e_cloud.png new file mode 100644 index 0000000..47aa41c Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_cloud.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_delivery.png b/watch/app/src/main/res/drawable-nodpi/e_delivery.png new file mode 100644 index 0000000..504615e Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_delivery.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_dog.png b/watch/app/src/main/res/drawable-nodpi/e_dog.png new file mode 100644 index 0000000..6763a76 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_dog.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_garden.png b/watch/app/src/main/res/drawable-nodpi/e_garden.png new file mode 100644 index 0000000..dbde969 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_garden.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_glasses.png b/watch/app/src/main/res/drawable-nodpi/e_glasses.png new file mode 100644 index 0000000..b099365 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_glasses.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_gold.png b/watch/app/src/main/res/drawable-nodpi/e_gold.png new file mode 100644 index 0000000..8bb3651 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_gold.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_hiking.png b/watch/app/src/main/res/drawable-nodpi/e_hiking.png new file mode 100644 index 0000000..5f92ba3 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_hiking.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_iced_hot.png b/watch/app/src/main/res/drawable-nodpi/e_iced_hot.png new file mode 100644 index 0000000..444fae2 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_iced_hot.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_jjamppong.png b/watch/app/src/main/res/drawable-nodpi/e_jjamppong.png new file mode 100644 index 0000000..0e05b74 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_jjamppong.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_laundry.png b/watch/app/src/main/res/drawable-nodpi/e_laundry.png new file mode 100644 index 0000000..804d560 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_laundry.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_makeup.png b/watch/app/src/main/res/drawable-nodpi/e_makeup.png new file mode 100644 index 0000000..6fe4d61 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_makeup.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_makgeolli.png b/watch/app/src/main/res/drawable-nodpi/e_makgeolli.png new file mode 100644 index 0000000..fa704b2 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_makgeolli.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_moon.png b/watch/app/src/main/res/drawable-nodpi/e_moon.png new file mode 100644 index 0000000..2f05938 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_moon.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_naengmyeon.png b/watch/app/src/main/res/drawable-nodpi/e_naengmyeon.png new file mode 100644 index 0000000..f112f43 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_naengmyeon.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_netflix.png b/watch/app/src/main/res/drawable-nodpi/e_netflix.png new file mode 100644 index 0000000..0f4de56 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_netflix.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_photo.png b/watch/app/src/main/res/drawable-nodpi/e_photo.png new file mode 100644 index 0000000..f1fe476 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_photo.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_picnic.png b/watch/app/src/main/res/drawable-nodpi/e_picnic.png new file mode 100644 index 0000000..28fb4b2 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_picnic.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_rabbit.png b/watch/app/src/main/res/drawable-nodpi/e_rabbit.png new file mode 100644 index 0000000..86e9f90 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_rabbit.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_rain.png b/watch/app/src/main/res/drawable-nodpi/e_rain.png new file mode 100644 index 0000000..9839854 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_rain.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_running.png b/watch/app/src/main/res/drawable-nodpi/e_running.png new file mode 100644 index 0000000..46a18e8 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_running.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_silver.png b/watch/app/src/main/res/drawable-nodpi/e_silver.png new file mode 100644 index 0000000..52d9949 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_silver.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_snow.png b/watch/app/src/main/res/drawable-nodpi/e_snow.png new file mode 100644 index 0000000..1bee97e Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_snow.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_stars.png b/watch/app/src/main/res/drawable-nodpi/e_stars.png new file mode 100644 index 0000000..3e0be15 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_stars.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_study.png b/watch/app/src/main/res/drawable-nodpi/e_study.png new file mode 100644 index 0000000..e7803c1 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_study.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_sun.png b/watch/app/src/main/res/drawable-nodpi/e_sun.png new file mode 100644 index 0000000..f7590eb Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_sun.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_sun_cloud.png b/watch/app/src/main/res/drawable-nodpi/e_sun_cloud.png new file mode 100644 index 0000000..7284b42 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_sun_cloud.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_sunset.png b/watch/app/src/main/res/drawable-nodpi/e_sunset.png new file mode 100644 index 0000000..c1d2559 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_sunset.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_taxi.png b/watch/app/src/main/res/drawable-nodpi/e_taxi.png new file mode 100644 index 0000000..268a464 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_taxi.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_thermo.png b/watch/app/src/main/res/drawable-nodpi/e_thermo.png new file mode 100644 index 0000000..c1ac7ac Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_thermo.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_umbrella.png b/watch/app/src/main/res/drawable-nodpi/e_umbrella.png new file mode 100644 index 0000000..2ddda45 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_umbrella.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_vent.png b/watch/app/src/main/res/drawable-nodpi/e_vent.png new file mode 100644 index 0000000..c9e9c70 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_vent.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_walk.png b/watch/app/src/main/res/drawable-nodpi/e_walk.png new file mode 100644 index 0000000..d1fc03d Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_walk.png differ diff --git a/watch/app/src/main/res/drawable-nodpi/e_yajang.png b/watch/app/src/main/res/drawable-nodpi/e_yajang.png new file mode 100644 index 0000000..8eafdd3 Binary files /dev/null and b/watch/app/src/main/res/drawable-nodpi/e_yajang.png differ diff --git a/watch/app/src/main/res/drawable/ic_gak.xml b/watch/app/src/main/res/drawable/ic_gak.xml new file mode 100644 index 0000000..fb7070c --- /dev/null +++ b/watch/app/src/main/res/drawable/ic_gak.xml @@ -0,0 +1,6 @@ + + + + + diff --git a/watch/app/src/main/res/font/bagel_fat_one.ttf b/watch/app/src/main/res/font/bagel_fat_one.ttf new file mode 100644 index 0000000..c512166 Binary files /dev/null and b/watch/app/src/main/res/font/bagel_fat_one.ttf differ diff --git a/watch/app/src/main/res/font/jua.ttf b/watch/app/src/main/res/font/jua.ttf new file mode 100644 index 0000000..b2ac41e Binary files /dev/null and b/watch/app/src/main/res/font/jua.ttf differ diff --git a/watch/build.gradle.kts b/watch/build.gradle.kts new file mode 100644 index 0000000..9cf18ac --- /dev/null +++ b/watch/build.gradle.kts @@ -0,0 +1,21 @@ +plugins { + id("com.android.application") version "9.4.1" apply false + id("org.jetbrains.kotlin.plugin.compose") version "2.4.20" apply false +} + +// 앱·스킨 공통 업로드 키. 키 파일·비밀번호는 저장소 밖 ~/.gradle/gradle.properties 에 둔다. +// 값이 없으면 서명 없는 릴리스가 나온다(Play 에 올릴 수 없음). +subprojects { + plugins.withId("com.android.application") { + extensions.configure { + val store = providers.gradleProperty("NALSSIGAK_STORE_FILE").orNull ?: return@configure + val upload = signingConfigs.create("upload") { + storeFile = file(store) + storePassword = providers.gradleProperty("NALSSIGAK_STORE_PASSWORD").get() + keyAlias = providers.gradleProperty("NALSSIGAK_KEY_ALIAS").get() + keyPassword = providers.gradleProperty("NALSSIGAK_KEY_PASSWORD").get() + } + buildTypes.getByName("release").signingConfig = upload + } + } +} diff --git a/watch/gradle.properties b/watch/gradle.properties new file mode 100644 index 0000000..660848f --- /dev/null +++ b/watch/gradle.properties @@ -0,0 +1,2 @@ +org.gradle.jvmargs=-Xmx2g +android.useAndroidX=true diff --git a/watch/gradle/wrapper/gradle-wrapper.jar b/watch/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..5097068 Binary files /dev/null and b/watch/gradle/wrapper/gradle-wrapper.jar differ diff --git a/watch/gradle/wrapper/gradle-wrapper.properties b/watch/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..9b7cb4a --- /dev/null +++ b/watch/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.0-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/watch/gradlew b/watch/gradlew new file mode 100755 index 0000000..249efbb --- /dev/null +++ b/watch/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# 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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/watch/gradlew.bat b/watch/gradlew.bat new file mode 100644 index 0000000..03754c4 --- /dev/null +++ b/watch/gradlew.bat @@ -0,0 +1,112 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +@rem Catch executions from older scripts and ensure they exit cleanly. +@rem This can be removed once we can be reasonably confident that few people +@rem will be migrating directly to this new wrapper. +goto afterSafetyNet +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +goto exitWithErrorLevel +:afterSafetyNet + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. + +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel + +@rem This label must not be changed. We rely on old scripts being able to jump to this point. +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/watch/licenses/LICENSE-fluent-emoji.txt b/watch/licenses/LICENSE-fluent-emoji.txt new file mode 100644 index 0000000..fc6fd7f --- /dev/null +++ b/watch/licenses/LICENSE-fluent-emoji.txt @@ -0,0 +1,23 @@ +3D icons in this folder are from Microsoft Fluent Emoji (https://github.com/microsoft/fluentui-emoji), licensed under the MIT License. Copyright (c) Microsoft Corporation. + +MIT License + +Copyright (c) Microsoft Corporation. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/watch/licenses/OFL-BagelFatOne.txt b/watch/licenses/OFL-BagelFatOne.txt new file mode 100644 index 0000000..21c7b2d --- /dev/null +++ b/watch/licenses/OFL-BagelFatOne.txt @@ -0,0 +1,93 @@ +Copyright 2022 The Bagel Fat Project Authors (https://github.com/JAMO-TYPEFACE/BagelFat) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/watch/licenses/OFL-Jua.txt b/watch/licenses/OFL-Jua.txt new file mode 100644 index 0000000..6971a3e --- /dev/null +++ b/watch/licenses/OFL-Jua.txt @@ -0,0 +1,93 @@ +Copyright 2018 The Jua Project Authors + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/watch/settings.gradle.kts b/watch/settings.gradle.kts new file mode 100644 index 0000000..5a1993b --- /dev/null +++ b/watch/settings.gradle.kts @@ -0,0 +1,15 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositories { + google() + mavenCentral() + } +} +rootProject.name = "nalssigak-watch" +include(":app", ":watchface") diff --git a/watch/watchface/build.gradle.kts b/watch/watchface/build.gradle.kts new file mode 100644 index 0000000..85b7ff9 --- /dev/null +++ b/watch/watchface/build.gradle.kts @@ -0,0 +1,25 @@ +plugins { + id("com.android.application") +} + +// 코드 없는 워치 스킨(Watch Face Format). 점수는 날씨각 앱(:app)의 순위별 컴플리케이션이 공급한다. +android { + enableKotlin = false + namespace = "kr.o2o.nalssigak.watchface" + compileSdk = 37 + + defaultConfig { + applicationId = "kr.o2o.nalssigak.watchface" + // WFF 버전 2 는 Wear OS 5(API 34)부터 + minSdk = 34 + targetSdk = 34 + versionCode = 1 + versionName = "0.1" + } + buildTypes.getByName("release") { + // 스킨 번들엔 dex 가 없어야 한다. R8 이 R 클래스까지 다 걷어내게 + isMinifyEnabled = true + // 스킨 XML 이 이름으로만 부르는 아이콘·글꼴을 안 쓰는 걸로 보고 지운다. 켜지 말 것 + isShrinkResources = false + } +} diff --git a/watch/watchface/gen_watchface.py b/watch/watchface/gen_watchface.py new file mode 100644 index 0000000..046a607 --- /dev/null +++ b/watch/watchface/gen_watchface.py @@ -0,0 +1,237 @@ +import json, math, os, sys +HERE = os.path.dirname(os.path.abspath(__file__)) +# 각 이름 → 아이콘. 시계 런타임이 점수 링 안의 작은 이미지를 그려 주지 않아, 이름을 보고 스킨에 넣은 아이콘을 고른다 +GAK_ICONS = [(d["name"], d["icon"]) for d in json.load(open(os.path.join(HERE, "../../backend/seed/index_definition.json"), encoding="utf-8"))] +W = 450 +CX, CY = 225, 235 +ORB = 162 +RING, RR = 68, 148 +ANGLES = [210, 330, 150, 30, 180, 0] +APP = "kr.o2o.nalssigak" +INK, ORANGE, SHADE, CARD = "#FF28304A", "#FFFF7A45", "#FFD9E5F4", "#B8FFFFFF" +AMB0 = '' + +MODES = { # 웹 .b-hero[data-t] 그라데이션, 시간대는 고정 시각 근사 + "morning": ("[HOUR_0_23] >= 5 && [HOUR_0_23] < 11", "#FFFFD9B8 #FFFFE9D4 #FFDFF0FF", "0 0.4 1", INK), + "day": ("[HOUR_0_23] >= 11 && [HOUR_0_23] < 16", "#FF9FD3FF #FFCFE9FF #FFF1F8FF", "0 0.55 1", INK), + "evening": ("[HOUR_0_23] >= 16 && [HOUR_0_23] < 21", "#FF8E7CF0 #FFF28AA0 #FFFFC38A", "0 0.48 1", "#FFFFFFFF"), +} +NIGHT = ("#FF141B3D #FF27306A #FF3D3F86", "0 0.6 1", "#FFFFFFFF") +STARS = [(0.22, 0.20), (0.70, 0.14), (0.84, 0.40), (0.14, 0.52), (0.48, 0.10), (0.30, 0.78), (0.76, 0.70)] + +def sky(colors, pos): + return f'''{AMB0} + + ''' + +def clock(color, ambient_visible=False): + alpha = "0" if ambient_visible else "255" + var = '' if ambient_visible else AMB0 + return f''' + {var} + + + ''' + +def stars(): + dots = "".join(f'' for x, y in STARS) + return f'{AMB0}{dots}' + +def cloud(x, y, w, h, dist, period, color="#FFFFFFFF"): + # 화면이 켜져 있는 동안만 period 초마다 부드럽게 한 번 왕복 (period 는 60 의 약수여야 분이 바뀔 때 튀지 않는다). 저전력 화면에서는 숨긴다 + return f'''{AMB0} + + + + ''' + +def orb_fill(colors): + blush = "" if colors == MOON else "".join( + f'' for x in (0.2, 0.8)) + return f'''{AMB0} + + + {blush} + ''' + +SUN = "#FFFFF5CF #FFFFC86E #FFFF8E4E #FFEE6436" +MOON = "#FFFFFFFF #FFD9D3FF #FFA99FEA #FF7F75CC" + +def sun_rays(): + """구슬 둘레의 끝이 둥근 햇살 12개. 1분에 한 바퀴""" + size = int(ORB / 0.72) + c, r1, r2 = size / 2, size * 0.4, size * 0.462 + lines = "".join( + f'' + for a in range(0, 360, 30)) + return f'''{AMB0} + {lines} + + ''' + +def mode_block(colors, pos, ink, night=False): + parts = [sky(colors, pos)] + if night: + parts.append(stars()) + cc = "#FFC9CDF0" if night else "#FFFFFFFF" + parts += [cloud(40, 160, 86, 30, 20, 10, cc), cloud(270, 345, 100, 32, -24, 12, cc), clock(ink), date_line(ink)] + return "\n ".join(parts) + +def text(x, y, w, h, family, size, color, expr, amb=False): + return f'''{AMB0 if amb else ""} + + ''' + +def orb_slot(): + x, y = CX - ORB // 2, CY - ORB // 2 + body = text(0, 30, ORB, 74, "bagel_fat_one", 58, "#FFFFFFFF", "[COMPLICATION.TEXT]") + text(14, 100, ORB - 28, 30, "jua", 21, "#FFFFFFFF", "[COMPLICATION.TITLE]") + return f''' + + + + {body} + + + {body} + + + ''' + +PROGRESS = "clamp([COMPLICATION.RANGED_VALUE_VALUE], [COMPLICATION.RANGED_VALUE_MIN], [COMPLICATION.RANGED_VALUE_MAX]) / ([COMPLICATION.RANGED_VALUE_MAX] - [COMPLICATION.RANGED_VALUE_MIN]) * 360" + +def icon_by_title(x, y, size): + exprs = "".join(f'' for n, (name, _) in enumerate(GAK_ICONS)) + cmps = "".join(f'{AMB0}' + for n, (_, icon) in enumerate(GAK_ICONS)) + return f"{exprs}{cmps}" + +def ring_slot(i, angle): + r = math.radians(angle) + x = int(CX + RR * math.cos(r) - RING / 2) + y = int(CY + RR * math.sin(r) - RING / 2) + s, a = RING, RING - 6 + return f''' + + + + {AMB0} + + + {AMB0} + + + + + + {icon_by_title(s // 2 - 14, 9, 28)} + {text(0, 35, s, 24, "bagel_fat_one", 18, INK, "[COMPLICATION.TEXT]", amb=True)} + + + {AMB0} + + + {text(0, 22, s, 24, "bagel_fat_one", 18, INK, "[COMPLICATION.TEXT]", amb=True)} + + + ''' + +# 기기 언어와 상관없이 한글 요일 ([DAY_OF_WEEK] 1 = 일요일) +WEEKDAY = " : ".join(f'[DAY_OF_WEEK] == {n + 1} ? "{d}"' for n, d in enumerate("일월화수목금")) + " : "토"" + +def chip(x, w, icon, expr): + return f'''{AMB0} + + + + {AMB0} + {text(x + 32, 369, w - 38, 30, "jua", 21, INK, expr, amb=True)}''' + +def precip_slot(): + """화면 전체를 덮는 숨은 칸. 날씨각 앱(RainComplicationService)이 글자 = 기온, 제목 = 비 소식을 주면 + 아래에 기온·비 칩을 그리고, 비 소식이 "비 와요"·"곧 비"면 빗줄기, "눈 와요"면 눈송이를 그린다. + 터치는 막지 않게 BoundingOval 을 1px 로 둔다. 주기는 60 의 약수여야 분이 바뀔 때 튀지 않는다.""" + import random + r = random.Random(7) + drops, flakes = [], [] + for i in range(34): + x, ph = r.randint(0, W), r.random() + period = r.choice([1, 1.2, 1.5]) + ln = r.randint(16, 26) + drops.append(f'''{AMB0} + + + ''') + for i in range(26): + x, ph = r.randint(0, W), r.random() + period = r.choice([6, 10, 12]) + d = r.randint(5, 10) + flakes.append(f'''{AMB0} + + + + ''') + shade = lambda c: f'{AMB0}' + return f''' + + + + + + + + + + {shade("#66485A78")} + {"".join(drops)} + + + {shade("#40A0AEC4")} + {"".join(flakes)} + + + {chip(108, 104, "thermo", "[COMPLICATION.TEXT]")} + {chip(220, 122, "umbrella", "[COMPLICATION.TITLE]")} + + + ''' + +def date_line(ink): + return f'''{AMB0} + + ''' + +exprs = "\n ".join(f'").replace("<", "<").replace("&", "&")}]]>' for k, v in MODES.items()) +compares = "\n ".join(f'\n {mode_block(v[1], v[2], v[3])}\n ' for k, v in MODES.items()) + +xml = f''' + + + + + + + + + {exprs} + + {compares} + + {mode_block(NIGHT[0], NIGHT[1], NIGHT[2], night=True)} + + + + {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))} + + +''' +open(sys.argv[1], "w").write(xml) diff --git a/watch/watchface/src/main/AndroidManifest.xml b/watch/watchface/src/main/AndroidManifest.xml new file mode 100644 index 0000000..c2ea7a3 --- /dev/null +++ b/watch/watchface/src/main/AndroidManifest.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_baseball.png b/watch/watchface/src/main/res/drawable-nodpi/e_baseball.png new file mode 100644 index 0000000..f3d8487 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_baseball.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_bike.png b/watch/watchface/src/main/res/drawable-nodpi/e_bike.png new file mode 100644 index 0000000..0be9901 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_bike.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_camping.png b/watch/watchface/src/main/res/drawable-nodpi/e_camping.png new file mode 100644 index 0000000..f04d077 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_camping.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_carwash.png b/watch/watchface/src/main/res/drawable-nodpi/e_carwash.png new file mode 100644 index 0000000..5c21a5b Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_carwash.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_chestnut.png b/watch/watchface/src/main/res/drawable-nodpi/e_chestnut.png new file mode 100644 index 0000000..9c694e7 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_chestnut.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_chimaek.png b/watch/watchface/src/main/res/drawable-nodpi/e_chimaek.png new file mode 100644 index 0000000..a0c4f49 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_chimaek.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_delivery.png b/watch/watchface/src/main/res/drawable-nodpi/e_delivery.png new file mode 100644 index 0000000..504615e Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_delivery.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_dog.png b/watch/watchface/src/main/res/drawable-nodpi/e_dog.png new file mode 100644 index 0000000..6763a76 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_dog.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_garden.png b/watch/watchface/src/main/res/drawable-nodpi/e_garden.png new file mode 100644 index 0000000..dbde969 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_garden.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_glasses.png b/watch/watchface/src/main/res/drawable-nodpi/e_glasses.png new file mode 100644 index 0000000..b099365 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_glasses.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_hiking.png b/watch/watchface/src/main/res/drawable-nodpi/e_hiking.png new file mode 100644 index 0000000..5f92ba3 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_hiking.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_iced_hot.png b/watch/watchface/src/main/res/drawable-nodpi/e_iced_hot.png new file mode 100644 index 0000000..444fae2 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_iced_hot.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_jjamppong.png b/watch/watchface/src/main/res/drawable-nodpi/e_jjamppong.png new file mode 100644 index 0000000..0e05b74 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_jjamppong.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_laundry.png b/watch/watchface/src/main/res/drawable-nodpi/e_laundry.png new file mode 100644 index 0000000..804d560 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_laundry.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_makeup.png b/watch/watchface/src/main/res/drawable-nodpi/e_makeup.png new file mode 100644 index 0000000..6fe4d61 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_makeup.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_makgeolli.png b/watch/watchface/src/main/res/drawable-nodpi/e_makgeolli.png new file mode 100644 index 0000000..fa704b2 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_makgeolli.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_naengmyeon.png b/watch/watchface/src/main/res/drawable-nodpi/e_naengmyeon.png new file mode 100644 index 0000000..f112f43 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_naengmyeon.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_netflix.png b/watch/watchface/src/main/res/drawable-nodpi/e_netflix.png new file mode 100644 index 0000000..0f4de56 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_netflix.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_photo.png b/watch/watchface/src/main/res/drawable-nodpi/e_photo.png new file mode 100644 index 0000000..f1fe476 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_photo.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_picnic.png b/watch/watchface/src/main/res/drawable-nodpi/e_picnic.png new file mode 100644 index 0000000..28fb4b2 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_picnic.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_running.png b/watch/watchface/src/main/res/drawable-nodpi/e_running.png new file mode 100644 index 0000000..46a18e8 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_running.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_stars.png b/watch/watchface/src/main/res/drawable-nodpi/e_stars.png new file mode 100644 index 0000000..3e0be15 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_stars.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_study.png b/watch/watchface/src/main/res/drawable-nodpi/e_study.png new file mode 100644 index 0000000..e7803c1 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_study.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_taxi.png b/watch/watchface/src/main/res/drawable-nodpi/e_taxi.png new file mode 100644 index 0000000..268a464 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_taxi.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_thermo.png b/watch/watchface/src/main/res/drawable-nodpi/e_thermo.png new file mode 100644 index 0000000..c1ac7ac Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_thermo.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_umbrella.png b/watch/watchface/src/main/res/drawable-nodpi/e_umbrella.png new file mode 100644 index 0000000..2ddda45 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_umbrella.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_vent.png b/watch/watchface/src/main/res/drawable-nodpi/e_vent.png new file mode 100644 index 0000000..c9e9c70 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_vent.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_walk.png b/watch/watchface/src/main/res/drawable-nodpi/e_walk.png new file mode 100644 index 0000000..d1fc03d Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_walk.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/e_yajang.png b/watch/watchface/src/main/res/drawable-nodpi/e_yajang.png new file mode 100644 index 0000000..8eafdd3 Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/e_yajang.png differ diff --git a/watch/watchface/src/main/res/drawable-nodpi/preview.png b/watch/watchface/src/main/res/drawable-nodpi/preview.png new file mode 100644 index 0000000..43b962b Binary files /dev/null and b/watch/watchface/src/main/res/drawable-nodpi/preview.png differ diff --git a/watch/watchface/src/main/res/font/bagel_fat_one.ttf b/watch/watchface/src/main/res/font/bagel_fat_one.ttf new file mode 100644 index 0000000..c512166 Binary files /dev/null and b/watch/watchface/src/main/res/font/bagel_fat_one.ttf differ diff --git a/watch/watchface/src/main/res/font/jua.ttf b/watch/watchface/src/main/res/font/jua.ttf new file mode 100644 index 0000000..b2ac41e Binary files /dev/null and b/watch/watchface/src/main/res/font/jua.ttf differ diff --git a/watch/watchface/src/main/res/raw/watchface.xml b/watch/watchface/src/main/res/raw/watchface.xml new file mode 100644 index 0000000..c561206 --- /dev/null +++ b/watch/watchface/src/main/res/raw/watchface.xml @@ -0,0 +1,558 @@ + + + + + + + + + + = 5 && [HOUR_0_23] < 11]]> + = 11 && [HOUR_0_23] < 16]]> + = 16 && [HOUR_0_23] < 21]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + = 21]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/watch/watchface/src/main/res/values/strings.xml b/watch/watchface/src/main/res/values/strings.xml new file mode 100644 index 0000000..0bd6ab2 --- /dev/null +++ b/watch/watchface/src/main/res/values/strings.xml @@ -0,0 +1,7 @@ + + + 날씨각 + 오늘 1위 각 + 둘레 각 + 비·눈 + diff --git a/watch/watchface/src/main/res/xml/watch_face_info.xml b/watch/watchface/src/main/res/xml/watch_face_info.xml new file mode 100644 index 0000000..8d4e649 --- /dev/null +++ b/watch/watchface/src/main/res/xml/watch_face_info.xml @@ -0,0 +1,5 @@ + + + + +