build: Task 22 완료 - :feature:feature-wallpaper 모듈 분리 및 LocationUpdateService/R.font 디커플링
- feature/feature-wallpaper 모듈 신규 생성 (namespace: bums.lunatic.launcher.feature.wallpaper): * MyWallpaperService.kt, NativeRenderer.kt를 :app에서 :feature:feature-wallpaper로 이동 - MyWallpaperService.kt 디커플링: * LocationUpdateService.lastWeather 직접 참조 -> weatherSummaryProvider 람다 주입으로 분리 * R.font.* 직접 참조 -> symbolFontResId, wallpaperFontResIds 주입 및 randomFontOrDefault() 폴백 처리 * LunaticLauncher.onCreate()에서 날씨 프로바이더 및 폰트 리소스 ID 목록 바인딩 - settings.gradle.kts, app/build.gradle.kts, ARCHITECTURE.md, TODO.md(6-2 완료) 갱신 - 검증: ./gradlew :app:compileDebugKotlin 빌드 성공 확인 (12s, 97 actionable tasks)
This commit is contained in:
@@ -118,6 +118,27 @@ prefs:
|
||||
PrefHelper.initialize(this)
|
||||
bums.lunatic.launcher.model.RssDataType.enabledChecker = { key -> PrefHelper.getBoolean(key, false) }
|
||||
bums.lunatic.launcher.workers.WorkersDb.schemaVersion = BuildConfig.BuildDateTime
|
||||
bums.lunatic.launcher.wall.MyWallpaperService.weatherSummaryProvider = {
|
||||
bums.lunatic.launcher.workers.LocationUpdateService.lastWeather
|
||||
}
|
||||
bums.lunatic.launcher.wall.MyWallpaperService.symbolFontResId = R.font.material_symbols
|
||||
bums.lunatic.launcher.wall.MyWallpaperService.wallpaperFontResIds = listOf(
|
||||
R.font.cafe24ohsquareair, R.font.cafe24oneprettynight, R.font.cafe24ssukssukregular,
|
||||
R.font.dovemayo, R.font.ebs_r, R.font.gabia_solmee, R.font.godomaum,
|
||||
R.font.jsarirang_hon, R.font.jsarirang_ppuri, R.font.jsdongkang_regular,
|
||||
R.font.kcc_kimhoon, R.font.kcc_sonkeechung, R.font.kccahnjunggeun,
|
||||
R.font.kotra_bold, R.font.kotra_songeulssi, R.font.kyobo_handwriting_2019,
|
||||
R.font.kyobo_handwriting_2021sjy, R.font.kyobohandwriting2024psw,
|
||||
R.font.mapoagape, R.font.mapobackpacking, R.font.mapodacapo, R.font.mapodpp,
|
||||
R.font.mapodpp_2, R.font.mapoflowerisland, R.font.mapogoldenpier, R.font.mapomaponaru,
|
||||
R.font.mapopeacefull, R.font.material_symbols, R.font.nnsgc_brhp, R.font.nnsgc_gd_an_gd,
|
||||
R.font.nnsgc_md, R.font.nnsgc_wsjidyp, R.font.nnsgc_yjc, R.font.on_jsuhl, R.font.on_jsuhr,
|
||||
R.font.on_sbsjl, R.font.on_sbsjr, R.font.on_treeususimgul, R.font.on_treeususimgul_r,
|
||||
R.font.on_wibsr, R.font.on_wisbl, R.font.on_ychyuhl, R.font.on_ychyuhr,
|
||||
R.font.ssshinb7, R.font.taebaek_milkyway, R.font.taefont_tsthlml,
|
||||
R.font.tvn_jguiyg_light, R.font.tvn_jguiyg_medium, R.font.wandohoper,
|
||||
R.font.ylee_mortal_heart_immortal_memory
|
||||
)
|
||||
Base64ImageCache.init(this)
|
||||
val dir = try {
|
||||
val externalDir = File("/storage/emulated/0/bums_ob/BUM'S PACED /scraped/logs")
|
||||
|
||||
@@ -1,940 +0,0 @@
|
||||
package bums.lunatic.launcher.wall
|
||||
|
||||
import android.app.ActivityManager
|
||||
import android.app.WallpaperManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.graphics.Canvas
|
||||
import android.graphics.Color
|
||||
import android.graphics.ColorFilter
|
||||
import android.graphics.Paint
|
||||
import android.graphics.Path
|
||||
import android.graphics.PathDashPathEffect
|
||||
import android.graphics.PixelFormat
|
||||
import android.graphics.RadialGradient
|
||||
import android.graphics.Rect
|
||||
import android.graphics.RectF
|
||||
import android.graphics.Shader
|
||||
import android.graphics.Typeface
|
||||
import android.graphics.Typeface.BOLD
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import android.os.BatteryManager
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.service.wallpaper.WallpaperService
|
||||
import android.text.SpannableStringBuilder
|
||||
import android.util.Log
|
||||
import android.view.Gravity
|
||||
import android.view.SurfaceHolder
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.TextView
|
||||
import androidx.core.graphics.alpha
|
||||
import bums.lunatic.launcher.R
|
||||
import bums.lunatic.launcher.model.QuoteItem
|
||||
import bums.lunatic.launcher.model.Translation
|
||||
import bums.lunatic.launcher.model.WallContentGroup
|
||||
import bums.lunatic.launcher.utils.Blog
|
||||
import bums.lunatic.launcher.workers.LocationUpdateService
|
||||
import bums.lunatic.launcher.workers.WorkersDb
|
||||
import com.google.common.reflect.TypeToken
|
||||
import com.google.gson.Gson
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
class MyWallpaperService : WallpaperService() {
|
||||
|
||||
|
||||
|
||||
private val TAG = "MyWallpaperService"
|
||||
|
||||
override fun onCreateEngine(): Engine {
|
||||
Log.d(TAG, "onCreateEngine: New engine instance created.")
|
||||
return NativeRenderEngine()
|
||||
}
|
||||
|
||||
data class BatteryInfo(
|
||||
val percent: Int,
|
||||
val isCharging: Boolean,
|
||||
// val speedText: String,
|
||||
val detailsText: String // "9.0V 1.5A (13.5W)" 같은 상세 정보
|
||||
)
|
||||
|
||||
private fun getBatteryStatus(): BatteryInfo {
|
||||
val intent = registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
|
||||
|
||||
val level = intent?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1
|
||||
val scale = intent?.getIntExtra(BatteryManager.EXTRA_SCALE, -1) ?: -1
|
||||
val status = intent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
|
||||
val plugged = intent?.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) ?: -1
|
||||
|
||||
val batteryPct = (level / scale.toFloat() * 100).toInt()
|
||||
val isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
|
||||
status == BatteryManager.BATTERY_STATUS_FULL
|
||||
|
||||
// var speedText = ""
|
||||
var detailsText = ""
|
||||
|
||||
if (isCharging) {
|
||||
// speedText = when (plugged) {
|
||||
// BatteryManager.BATTERY_PLUGGED_AC -> "고속"
|
||||
// BatteryManager.BATTERY_PLUGGED_USB -> "저속"
|
||||
// BatteryManager.BATTERY_PLUGGED_WIRELESS -> "무선"
|
||||
// else -> ""
|
||||
// }
|
||||
|
||||
// 1. 전압(Voltage) 가져오기: 기본 단위는 밀리볼트(mV)
|
||||
val voltageMv = intent?.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0) ?: 0
|
||||
val voltageV = voltageMv / 1000.0f
|
||||
|
||||
// 2. 전류(Current) 가져오기: BatteryManager를 통해 실시간 값 조회
|
||||
val batteryManager = getSystemService(BATTERY_SERVICE) as BatteryManager
|
||||
// 안드로이드 표준 단위는 마이크로암페어(µA) 입니다.
|
||||
val currentUa = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW)
|
||||
|
||||
// 음수(방전)로 나올 수 있으므로 절대값 처리 후 암페어(A)로 변환
|
||||
val currentA = Math.abs(currentUa) / 1000000.0f
|
||||
|
||||
// 3. 전력(Watt) 계산: W = V * A
|
||||
val wattage = voltageV * currentA
|
||||
|
||||
// 값이 정상적으로 읽혔을 때만 텍스트 생성 (가끔 0으로 떨어지는 기기 방어)
|
||||
if (voltageV > 0f && currentA > 0f) {
|
||||
detailsText = String.format("%.1fV,%.1fA,(%.1fW)", voltageV, currentA, wattage)
|
||||
}
|
||||
}
|
||||
|
||||
return BatteryInfo(batteryPct, isCharging, detailsText)
|
||||
}
|
||||
|
||||
inner class NativeRenderEngine : Engine() {
|
||||
private lateinit var handlerThread: HandlerThread
|
||||
private lateinit var handler: Handler
|
||||
private lateinit var holder: SurfaceHolder
|
||||
private var wasInPreview = false
|
||||
private var nativeRenderer: NativeRenderer? = null
|
||||
private var mediaFiles: MutableList<File> = mutableListOf()
|
||||
private var isVisible = false
|
||||
private var isSurfaceValid = false
|
||||
|
||||
private val frameDelayMs = 1000L / 50L
|
||||
private val syncDelayMs = 250L // 상태 변경을 처리하기 전의 지연 시간
|
||||
private var frameCount = 0
|
||||
private val debugLogCheck = 240
|
||||
// private val renderRunnable = object : Runnable {
|
||||
// override fun run() {
|
||||
// if (!isVisible || !isSurfaceValid) return
|
||||
//
|
||||
// // [수정] nativeRender -> render
|
||||
// nativeRenderer?.render(holder.surface)
|
||||
//
|
||||
// frameCount++
|
||||
// if (frameCount % debugLogCheck == 0) {
|
||||
// frameCount = 0
|
||||
// // [수정] nativeGetDebugInfo -> getDebugInfo
|
||||
// val debugInfo = nativeRenderer?.getDebugInfo() ?: "Kotlin nativeRenderer is null"
|
||||
// Log.d(TAG, debugInfo)
|
||||
// }
|
||||
//
|
||||
// handler.postDelayed(this, frameDelayMs)
|
||||
// }
|
||||
// }
|
||||
private val destroyRenderer = Runnable {
|
||||
nativeRenderer?.destroy()
|
||||
nativeRenderer = null
|
||||
}
|
||||
// --- ⬇️ 렌더링 상태를 동기화하는 Runnable 추가 ⬇️ ---
|
||||
private val syncRenderStateRunnable = Runnable {
|
||||
// 딜레이 이후, 최종 상태를 확인하고 렌더링을 시작할지 중지할지 결정
|
||||
if (isVisible && isSurfaceValid) {
|
||||
startRendering()
|
||||
} else {
|
||||
stopRendering()
|
||||
}
|
||||
}
|
||||
private val nextMediaReceiver = object : android.content.BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent?) {
|
||||
if (intent?.action == "ACTION_NEXT_WALLPAPER") {
|
||||
Log.d(TAG, "Manual next wallpaper requested via Broadcast")
|
||||
// 현재 콜백 객체의 함수를 직접 호출하여 다음 미디어로 넘김
|
||||
nextMediaCallback.onNextMediaRequested()
|
||||
nativeRenderer?.forceNext()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate(surfaceHolder: SurfaceHolder) {
|
||||
super.onCreate(surfaceHolder)
|
||||
this.holder = surfaceHolder
|
||||
Log.d(TAG, "onCreate: Engine created.")
|
||||
wasInPreview = isPreview()
|
||||
Log.d(TAG, "onCreate: Engine created. Initial isPreview = $wasInPreview")
|
||||
val filter = IntentFilter("ACTION_NEXT_WALLPAPER")
|
||||
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
|
||||
registerReceiver(nextMediaReceiver, filter, Context.RECEIVER_NOT_EXPORTED)
|
||||
} else {
|
||||
registerReceiver(nextMediaReceiver, filter)
|
||||
}
|
||||
ensureHandlerThread()
|
||||
}
|
||||
|
||||
private fun ensureHandlerThread() {
|
||||
if (!::handlerThread.isInitialized || !handlerThread.isAlive) {
|
||||
Log.w(TAG, "Handler thread was dead or not initialized. Recreating.")
|
||||
handlerThread = HandlerThread("NativeRenderThread")
|
||||
handlerThread.start()
|
||||
handler = Handler(handlerThread.looper)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onSurfaceCreated(holder: SurfaceHolder) {
|
||||
super.onSurfaceCreated(holder)
|
||||
Log.i(TAG, "onSurfaceCreated: Surface is ready.")
|
||||
this.holder = holder
|
||||
isSurfaceValid = true
|
||||
ensureHandlerThread()
|
||||
initializeRenderer()
|
||||
// --- 수정: 즉시 시작 대신 상태 동기화 요청 ---
|
||||
requestSyncRenderState()
|
||||
}
|
||||
|
||||
override fun onSurfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
|
||||
super.onSurfaceChanged(holder, format, width, height)
|
||||
Log.i(TAG, "onSurfaceChanged: Surface changed.")
|
||||
// this.holder = holder
|
||||
isSurfaceValid = true
|
||||
ensureHandlerThread()
|
||||
if (nativeRenderer == null) {
|
||||
Log.w(TAG, "onSurfaceChanged: Renderer was null. Re-initializing.")
|
||||
initializeRenderer()
|
||||
}
|
||||
|
||||
requestSyncRenderState()
|
||||
}
|
||||
|
||||
override fun onVisibilityChanged(visible: Boolean) {
|
||||
super.onVisibilityChanged(visible)
|
||||
val currentlyInPreview = isPreview()
|
||||
if (wasInPreview && !currentlyInPreview) {
|
||||
// 이 블록이 실행되는 시점이 바로 "배경화면으로 설정"을 누른 직후입니다.
|
||||
Log.i(TAG, ">>>>>>>>>> TRANSITION: Preview -> Live Wallpaper! <<<<<<<<<<")
|
||||
|
||||
// 여기에 실제 배경화면으로 설정되었을 때 딱 한 번만 실행하고 싶은 코드를 넣을 수 있습니다.
|
||||
}
|
||||
Log.i(TAG, "onVisibilityChanged: Visibility changed to -> $visible")
|
||||
isVisible = visible
|
||||
if (isVisible) {
|
||||
handler.removeCallbacks(destroyRenderer)
|
||||
}
|
||||
ensureHandlerThread()
|
||||
if (nativeRenderer == null) {
|
||||
Log.w(TAG, "onVisibilityChanged: Renderer was null. Re-initializing.")
|
||||
initializeRenderer()
|
||||
}
|
||||
requestSyncRenderState()
|
||||
|
||||
if (visible) {
|
||||
// 화면이 켜지면 즉시 업데이트하고 타이머 시작
|
||||
handler.removeCallbacks(updateWeatherRunnable)
|
||||
handler.post(updateWeatherRunnable)
|
||||
} else {
|
||||
// 화면이 꺼지면 타이머 중지
|
||||
handler.removeCallbacks(updateWeatherRunnable)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// --- ⬇️ 상태 동기화를 요청하는 함수 추가 ⬇️ ---
|
||||
private fun requestSyncRenderState() {
|
||||
// 이전에 요청된 동기화 작업이 있다면 취소하고, 새로운 동기화 작업을 딜레이와 함께 예약
|
||||
handler.removeCallbacks(syncRenderStateRunnable)
|
||||
handler.postDelayed(syncRenderStateRunnable, syncDelayMs)
|
||||
}
|
||||
|
||||
override fun onSurfaceDestroyed(holder: SurfaceHolder) {
|
||||
super.onSurfaceDestroyed(holder)
|
||||
Log.e(TAG, "onSurfaceDestroyed: Surface is destroyed.")
|
||||
isSurfaceValid = false
|
||||
// --- 수정: 즉시 중지 대신 상태 동기화 요청 ---
|
||||
requestSyncRenderState()
|
||||
handler.removeCallbacks(destroyRenderer)
|
||||
handler.postDelayed(destroyRenderer, syncDelayMs)
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
Log.e(TAG, "onDestroy: Engine is being destroyed. Quitting thread.")
|
||||
if (::handlerThread.isInitialized) {
|
||||
handlerThread.quitSafely()
|
||||
}
|
||||
try {
|
||||
unregisterReceiver(nextMediaReceiver)
|
||||
} catch (e: Exception) {
|
||||
// 리시버가 등록되지 않았을 경우 예외 방지
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
private fun startRendering() {
|
||||
if (isVisible && isSurfaceValid) {
|
||||
Log.d(TAG, "startRendering: Conditions met. Starting loop. ${handler}")
|
||||
// handler.removeCallbacks(renderRunnable)
|
||||
// handler.post(renderRunnable)
|
||||
nativeRenderer?.startRenderLoop(holder.surface)
|
||||
} else {
|
||||
Log.d(TAG, "startRendering: Conditions not met. Starting loop fail.")
|
||||
}
|
||||
}
|
||||
|
||||
private fun stopRendering() {
|
||||
Log.w(TAG, "stopRendering: Stopping loop.")
|
||||
// 핸들러가 초기화된 경우에만 콜백 제거 시도
|
||||
if (::handler.isInitialized) {
|
||||
nativeRenderer?.stopRenderLoop()
|
||||
} else {
|
||||
Log.w(TAG, "stopRendering: Stopping loop. ${::handler.isInitialized}")
|
||||
}
|
||||
}
|
||||
private fun initializeRenderer() {
|
||||
Log.d(TAG, "Initializing Renderer...")
|
||||
nativeRenderer = NativeRenderer()
|
||||
nativeRenderer?.initialize() // nativeInit() -> initialize()
|
||||
nativeRenderer?.setFadeDuration(3000)
|
||||
nativeRenderer?.setTurnPageDuration(8000)
|
||||
nativeRenderer?.setAnimationMode(NativeRenderer.ANIMATION_MODE_PAN)
|
||||
nativeRenderer?.setTransitionMode(NativeRenderer.TRANSITION_MODE_FADE)
|
||||
nativeRenderer?.setAnimationSpeed(1.0f)
|
||||
nativeRenderer?.setImageRenderFrame(70)
|
||||
NativeRenderer.nativeSetNextMediaCallback(nextMediaCallback)
|
||||
|
||||
|
||||
if (mediaFiles.isEmpty()) {
|
||||
handler.post { loadMediaFiles() }
|
||||
}
|
||||
|
||||
handler.removeCallbacks(updateWeatherRunnable)
|
||||
// 즉시 첫 번째 비트맵 생성 및 전송
|
||||
handler.post(updateWeatherRunnable)
|
||||
|
||||
}
|
||||
|
||||
val requiredSizeRatio = 0.5
|
||||
|
||||
private fun getVideoSize(file: File): Pair<Int, Int>? {
|
||||
val retriever = android.media.MediaMetadataRetriever()
|
||||
return try {
|
||||
retriever.setDataSource(file.absolutePath)
|
||||
val width = retriever.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)?.toInt() ?: 0
|
||||
val height = retriever.extractMetadata(android.media.MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)?.toInt() ?: 0
|
||||
Pair(width, height)
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
} finally {
|
||||
retriever.release()
|
||||
}
|
||||
}
|
||||
|
||||
fun loadFiles() {
|
||||
if (!mediaDir.exists()) mediaDir.mkdirs()
|
||||
|
||||
val allFiles = mediaDir.listFiles()?.filter { supportedExtensions.contains(it.extension.lowercase()) } ?: return
|
||||
val trashFolder = File(mediaDir, "low_res_backup")
|
||||
if (!trashFolder.exists()) trashFolder.mkdirs()
|
||||
|
||||
val wm = WallpaperManager.getInstance(this@MyWallpaperService)
|
||||
val requiredSize = Math.max(wm.desiredMinimumWidth, wm.desiredMinimumHeight) * requiredSizeRatio
|
||||
|
||||
val videoExtensions = listOf("mp4", "mkv", "avi", "mov", "webm", "gif")
|
||||
val imageExtensions = listOf("jpg", "jpeg", "png", "bmp", "webp")
|
||||
|
||||
for (file in allFiles) {
|
||||
val ext = file.extension.lowercase()
|
||||
var width = 0
|
||||
var height = 0
|
||||
var isOk = false
|
||||
when {
|
||||
// 이미지 처리
|
||||
imageExtensions.contains(ext) -> {
|
||||
val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
||||
BitmapFactory.decodeFile(file.absolutePath, options)
|
||||
width = options.outWidth
|
||||
height = options.outHeight
|
||||
// Blog.LOGE("loadFiles imageExtensions width $width height $height")
|
||||
}
|
||||
// 동영상 처리
|
||||
videoExtensions.contains(ext) -> {
|
||||
val size = getVideoSize(file)
|
||||
width = size?.first ?: 0
|
||||
height = size?.second ?: 0
|
||||
isOk = (width >= requiredSize * 0.65 && height >= requiredSize*0.65)
|
||||
// Blog.LOGE("loadFiles videoExtensions requiredSize $requiredSize width $width height $height [$isOk]")
|
||||
}
|
||||
}
|
||||
|
||||
// 사이즈 검사 및 분류
|
||||
if (isOk || (width >= requiredSize && height >= requiredSize)) {
|
||||
if (!mediaFiles.contains(file)) mediaFiles.add(file)
|
||||
} else {
|
||||
// Log.w(TAG, "Low resolution file filtered: ${file.name} (${width}x${height})")
|
||||
file.renameTo(File(trashFolder, file.name))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun getRamUsage(): String {
|
||||
val mi = ActivityManager.MemoryInfo()
|
||||
val activityManager = getSystemService(ACTIVITY_SERVICE) as ActivityManager
|
||||
activityManager.getMemoryInfo(mi)
|
||||
val availableMegs = mi.availMem / 1048576L
|
||||
val totalMegs = mi.totalMem / 1048576L
|
||||
val usedMegs = totalMegs - availableMegs
|
||||
val percent = (usedMegs.toDouble() / totalMegs.toDouble() * 100).toInt()
|
||||
return "RAM: $percent%"
|
||||
}
|
||||
|
||||
// 배터리/기기 온도 가져오기 (Celsius)
|
||||
private fun getDeviceTemperature(): String {
|
||||
val intent = registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
|
||||
val temp = intent?.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0) ?: 0
|
||||
return "Temp: ${temp / 10.0}°C"
|
||||
}
|
||||
|
||||
private fun getSystemTypeface(lang: String): Typeface {
|
||||
return when (lang) {
|
||||
"JA" -> Typeface.create("sans-serif", Typeface.BOLD) // 일본어 한자/가나 대응
|
||||
else -> Typeface.create("sans-serif-medium", Typeface.NORMAL) // 영문/스페인어
|
||||
}
|
||||
}
|
||||
|
||||
private val materialIconFont: Typeface by lazy {
|
||||
resources.getFont(R.font.material_symbols)
|
||||
}
|
||||
|
||||
// 날씨 텍스트를 분석하여 Material Symbol 아이콘 문자열로 변환하는 함수
|
||||
private fun getWeatherIconString(condition: String?): String {
|
||||
if (condition == null) return "thermostat"
|
||||
val lower = condition.lowercase()
|
||||
|
||||
return when {
|
||||
// 1. 천둥/번개 (우선순위 최상: 비나 눈이 와도 번개가 치면 뇌우 아이콘)
|
||||
lower.contains("thunder") -> "thunderstorm"
|
||||
|
||||
// 2. 눈, 우박, 진눈깨비, 빙결 (Snow, Ice pellets, Sleet, Blizzard, Freezing)
|
||||
lower.contains("snow") || lower.contains("blizzard") ||
|
||||
lower.contains("ice") || lower.contains("sleet") ||
|
||||
lower.contains("freezing") -> "snowing"
|
||||
|
||||
// 3. 비, 소나기, 이슬비 (Rain, Drizzle, Shower)
|
||||
lower.contains("rain") || lower.contains("drizzle") ||
|
||||
lower.contains("shower") -> "rainy"
|
||||
|
||||
// 4. 안개 (Fog, Mist)
|
||||
lower.contains("fog") || lower.contains("mist") -> "foggy"
|
||||
|
||||
// 5. 구름 (Overcast, Cloudy, Partly cloudy)
|
||||
lower.contains("partly cloudy") -> "partly_cloudy_day"
|
||||
lower.contains("cloudy") || lower.contains("overcast") -> "cloud"
|
||||
|
||||
// 6. 맑음 (Sunny, Clear)
|
||||
lower.contains("sunny") || lower.contains("clear") -> "sunny"
|
||||
|
||||
// 7. 예외 처리 (매핑되지 않은 기본값)
|
||||
else -> "thermostat"
|
||||
}
|
||||
}
|
||||
|
||||
private fun getKoreanWeatherCondition(condition: String): String {
|
||||
val lower = condition.trim().lowercase()
|
||||
return when {
|
||||
lower == "sunny" || lower == "clear" -> "맑음"
|
||||
lower == "partly cloudy" -> "구름 조금"
|
||||
lower == "cloudy" -> "구름 많음"
|
||||
lower == "overcast" -> "흐림"
|
||||
|
||||
lower.contains("mist") || lower.contains("fog") -> "안개"
|
||||
lower.contains("blizzard") || lower.contains("blowing snow") -> "눈보라"
|
||||
|
||||
// 뇌우(번개) 계열
|
||||
lower.contains("thunder") && lower.contains("snow") -> "천둥/눈"
|
||||
lower.contains("thunder") && lower.contains("rain") -> "천둥/비"
|
||||
lower.contains("thunder") -> "뇌우"
|
||||
|
||||
// 얼음 섞인 비/눈 계열
|
||||
lower.contains("sleet") -> "진눈깨비"
|
||||
lower.contains("ice pellets") -> "싸락눈"
|
||||
|
||||
// 비 계열 (우선순위: 폭우 -> 소나기 -> 강한 비 -> 이슬비 -> 비)
|
||||
lower.contains("torrential") -> "폭우"
|
||||
lower.contains("heavy") && lower.contains("shower") -> "강한 소나기"
|
||||
lower.contains("shower") -> "소나기"
|
||||
lower.contains("heavy rain") -> "강한 비"
|
||||
lower.contains("drizzle") -> "이슬비"
|
||||
lower.contains("rain") -> "비"
|
||||
|
||||
// 눈 계열 (우선순위: 폭설 -> 눈)
|
||||
lower.contains("heavy snow") -> "폭설"
|
||||
lower.contains("snow") -> "눈"
|
||||
|
||||
// 매핑되지 않은 기본값 (혹시 모를 예외 대비)
|
||||
else -> condition
|
||||
}
|
||||
}
|
||||
val fontz = arrayListOf<Int>(
|
||||
R.font.cafe24ohsquareair,
|
||||
R.font.cafe24oneprettynight,
|
||||
R.font.cafe24ssukssukregular,
|
||||
R.font.dovemayo,
|
||||
R.font.ebs_r,
|
||||
R.font.gabia_solmee,
|
||||
R.font.godomaum,
|
||||
R.font.jsarirang_hon,
|
||||
R.font.jsarirang_ppuri,
|
||||
R.font.jsdongkang_regular,
|
||||
R.font.kcc_kimhoon,
|
||||
R.font.kcc_sonkeechung,
|
||||
R.font.kccahnjunggeun,
|
||||
R.font.kotra_bold,
|
||||
R.font.kotra_songeulssi,
|
||||
R.font.kyobo_handwriting_2019,
|
||||
R.font.kyobo_handwriting_2021sjy,
|
||||
R.font.kyobohandwriting2024psw,
|
||||
R.font.mapoagape,
|
||||
R.font.mapobackpacking,
|
||||
R.font.mapodacapo,
|
||||
R.font.mapodpp,
|
||||
R.font.mapodpp_2,
|
||||
R.font.mapoflowerisland,
|
||||
R.font.mapogoldenpier,
|
||||
R.font.mapomaponaru,
|
||||
R.font.mapopeacefull,
|
||||
R.font.material_symbols,
|
||||
R.font.nnsgc_brhp,
|
||||
R.font.nnsgc_gd_an_gd,
|
||||
R.font.nnsgc_md,
|
||||
R.font.nnsgc_wsjidyp,
|
||||
R.font.nnsgc_yjc,
|
||||
R.font.on_jsuhl,
|
||||
R.font.on_jsuhr,
|
||||
R.font.on_sbsjl,
|
||||
R.font.on_sbsjr,
|
||||
R.font.on_treeususimgul,
|
||||
R.font.on_treeususimgul_r,
|
||||
R.font.on_wibsr,
|
||||
R.font.on_wisbl,
|
||||
R.font.on_ychyuhl,
|
||||
R.font.on_ychyuhr,
|
||||
R.font.ssshinb7,
|
||||
R.font.taebaek_milkyway,
|
||||
R.font.taefont_tsthlml,
|
||||
R.font.tvn_jguiyg_light,
|
||||
R.font.tvn_jguiyg_medium,
|
||||
R.font.wandohoper,
|
||||
R.font.ylee_mortal_heart_immortal_memory,
|
||||
)
|
||||
|
||||
var monoBold = resources.getFont(fontz.random())
|
||||
var quote = resources.getFont(fontz.random())
|
||||
var local = resources.getFont(fontz.random())
|
||||
var numbers = resources.getFont(fontz.random())
|
||||
|
||||
private fun drawBitmapFromText(weatherLines: List<String>, isCharging: Boolean = false): Bitmap? {
|
||||
// 💡 1. 원의 크기와 내부 여백 계산
|
||||
val displayMetrics = resources.displayMetrics
|
||||
var sizeRate = 1.1f
|
||||
val circleSize = ((displayMetrics.widthPixels * 0.48f).toInt() * sizeRate).toInt()
|
||||
val padding = 5
|
||||
val maxContentWidth = circleSize - (padding * 2)
|
||||
|
||||
if (circleSize <= 0) return null
|
||||
|
||||
// 💡 2. 텍스트 크기 3단계 변수 정의 (가독성과 감성을 모두 잡은 안정적인 비율)
|
||||
val iconRate = 1.3f
|
||||
val sizeLarge = 24f // 메인 날씨 상태
|
||||
val sizeMedium = 15f // 날짜, 주소, 온도, 명언 본문
|
||||
val sizeSmall = 13f // 시스템 정보, 명언 번역, 작가
|
||||
|
||||
// 3. 데이터 준비
|
||||
val dateFull = SimpleDateFormat("yyyy.MM.dd(E)", Locale.ENGLISH).format(Date())
|
||||
val weatherCondition = if (weatherLines.isNotEmpty()) weatherLines[0] else ""
|
||||
val weatherTemp = if (weatherLines.size > 1) weatherLines[1] else ""
|
||||
val weatherHum = if (weatherLines.size > 2) weatherLines[2] else ""
|
||||
val address = if (weatherLines.size > 3) weatherLines[3] else ""
|
||||
|
||||
val wrapContent = ViewGroup.LayoutParams.WRAP_CONTENT
|
||||
|
||||
|
||||
|
||||
// 4. 뷰 생성 헬퍼
|
||||
fun createTextView(textToSet: CharSequence, textSizeDp: Float, font: Typeface, alphaValue: Float = 1.0f): TextView {
|
||||
return TextView(this@MyWallpaperService).apply {
|
||||
layoutParams = LinearLayout.LayoutParams(wrapContent, wrapContent)
|
||||
maxWidth = maxContentWidth
|
||||
text = textToSet
|
||||
textSize = textSizeDp
|
||||
typeface = font
|
||||
setTextColor(Color.WHITE)
|
||||
alpha = alphaValue
|
||||
gravity = Gravity.CENTER
|
||||
setShadowLayer(6f, 3f, 3f, Color.parseColor("#AA000000"))
|
||||
}
|
||||
}
|
||||
|
||||
fun createHorizontalLayout(): LinearLayout {
|
||||
return LinearLayout(this@MyWallpaperService).apply {
|
||||
layoutParams = LinearLayout.LayoutParams(wrapContent, wrapContent)
|
||||
orientation = LinearLayout.HORIZONTAL
|
||||
gravity = Gravity.CENTER
|
||||
setPadding(1, 1, 1, 1)
|
||||
}
|
||||
}
|
||||
val sysAlpha = 0.9f
|
||||
// 5. 각 줄(Row) 생성
|
||||
val rowsToArrange = mutableListOf<View>()
|
||||
|
||||
// ① 날씨 (아이콘 + 상태)
|
||||
if (weatherCondition.isNotEmpty()) {
|
||||
val weatherRow = createHorizontalLayout()
|
||||
// 아이콘은 Large 텍스트보다 살짝 크게 배율 고정
|
||||
weatherRow.addView(createTextView(getWeatherIconString(weatherCondition), sizeLarge * iconRate, materialIconFont))
|
||||
weatherRow.addView(createTextView(" " + getKoreanWeatherCondition(weatherCondition), sizeLarge, monoBold))
|
||||
rowsToArrange.add(weatherRow)
|
||||
}
|
||||
|
||||
// ② 온도 & 습도
|
||||
if (weatherTemp.isNotEmpty()) {
|
||||
val tempRow = createHorizontalLayout()
|
||||
val tempStr = weatherTemp.trim()
|
||||
val humStr = weatherHum.trim()
|
||||
|
||||
tempRow.addView(createTextView("thermostat", sizeMedium * iconRate, materialIconFont, sysAlpha))
|
||||
tempRow.addView(createTextView(tempStr, sizeMedium, numbers,sysAlpha))
|
||||
|
||||
if (humStr.isNotEmpty()) {
|
||||
tempRow.addView(createTextView("water_drop", sizeMedium * iconRate, materialIconFont, sysAlpha))
|
||||
tempRow.addView(createTextView(humStr, sizeMedium, numbers, sysAlpha))
|
||||
}
|
||||
rowsToArrange.add(tempRow)
|
||||
}
|
||||
|
||||
// ③ 주소
|
||||
if (address.isNotEmpty()) {
|
||||
rowsToArrange.add(createTextView(address, sizeMedium, local, sysAlpha))
|
||||
}
|
||||
|
||||
// ④ 날짜
|
||||
rowsToArrange.add(createTextView(dateFull, sizeMedium, local))
|
||||
|
||||
// ⑤ 시스템 정보
|
||||
val sysInfoRow = createHorizontalLayout()
|
||||
|
||||
|
||||
val ramValue = getRamUsage().replace("RAM: ", "")
|
||||
sysInfoRow.addView(createTextView("memory", sizeSmall * iconRate, materialIconFont, sysAlpha))
|
||||
sysInfoRow.addView(createTextView(ramValue, sizeSmall, numbers, sysAlpha).apply { setPadding(0, 0, 15, 0) })
|
||||
|
||||
val tempValue = getDeviceTemperature().replace("Temp: ", "")
|
||||
sysInfoRow.addView(createTextView("device_thermostat", sizeSmall * iconRate, materialIconFont, sysAlpha))
|
||||
sysInfoRow.addView(createTextView(tempValue, sizeSmall, numbers, sysAlpha).apply { setPadding(0, 0, 15, 0) })
|
||||
|
||||
val batteryInfo = getBatteryStatus()
|
||||
val batteryIcon = if (batteryInfo.isCharging) "battery_charging_full" else "battery_full"
|
||||
val batteryText = "${batteryInfo.percent}%"
|
||||
|
||||
sysInfoRow.addView(createTextView(batteryIcon, sizeSmall * iconRate, materialIconFont, sysAlpha))
|
||||
sysInfoRow.addView(createTextView(batteryText, sizeSmall, numbers, sysAlpha))
|
||||
rowsToArrange.add(sysInfoRow)
|
||||
|
||||
// ⑥ 명언
|
||||
randomQuote?.let { randomQuote ->
|
||||
val builder = SpannableStringBuilder()
|
||||
|
||||
fun appendSpanned(text: String, sizeDp: Float, font: Typeface, alpha: Float) {
|
||||
val start = builder.length
|
||||
builder.append(text)
|
||||
val end = builder.length
|
||||
|
||||
builder.setSpan(android.text.style.AbsoluteSizeSpan(sizeDp.toInt(), true), start, end, android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
|
||||
val alphaInt = (alpha * 255).toInt()
|
||||
val color = Color.argb(alphaInt, 255, 255, 255)
|
||||
builder.setSpan(android.text.style.ForegroundColorSpan(color), start, end, android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
|
||||
builder.setSpan(object : android.text.style.MetricAffectingSpan() {
|
||||
override fun updateDrawState(tp: android.text.TextPaint) { tp.typeface = font }
|
||||
override fun updateMeasureState(tp: android.text.TextPaint) { tp.typeface = font }
|
||||
}, start, end, android.text.Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
|
||||
}
|
||||
|
||||
if (randomQuote.isTranslated) {
|
||||
appendSpanned("\"${randomQuote.textEn}\"", sizeMedium, quote, 1.0f)
|
||||
builder.append("\n")
|
||||
appendSpanned(randomQuote.textKo, sizeSmall, monoBold, sysAlpha)
|
||||
val author = if (randomQuote.authorKo.isNotEmpty()) randomQuote.authorKo else randomQuote.authorEn
|
||||
appendSpanned(" - $author -", sizeSmall, monoBold, sysAlpha)
|
||||
} else {
|
||||
val mainText = if (randomQuote.textKo.isNotEmpty()) randomQuote.textKo else randomQuote.textEn
|
||||
val author = if (randomQuote.authorKo.isNotEmpty()) randomQuote.authorKo else randomQuote.authorEn
|
||||
appendSpanned("\"$mainText\"", sizeMedium, quote, 1.0f)
|
||||
appendSpanned(" - $author -", sizeSmall, monoBold, sysAlpha)
|
||||
}
|
||||
|
||||
val quoteView = createTextView(builder, sizeMedium, quote, 1.0f).apply {
|
||||
// setLineSpacing(0f, 1.2f)
|
||||
}
|
||||
rowsToArrange.add(quoteView)
|
||||
}
|
||||
|
||||
// 💡 6. 정렬 및 다이아몬드 배열
|
||||
val widthSpec = View.MeasureSpec.makeMeasureSpec(maxContentWidth, View.MeasureSpec.AT_MOST)
|
||||
val heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
|
||||
rowsToArrange.forEach { it.measure(widthSpec, heightSpec) }
|
||||
|
||||
val sortedRows = rowsToArrange.sortedBy { it.measuredWidth }
|
||||
val arrangedRows = arrayOfNulls<View>(sortedRows.size)
|
||||
var topIndex = 0
|
||||
var bottomIndex = sortedRows.size - 1
|
||||
|
||||
for (i in sortedRows.indices) {
|
||||
if (i % 2 == 0) arrangedRows[topIndex++] = sortedRows[i]
|
||||
else arrangedRows[bottomIndex--] = sortedRows[i]
|
||||
}
|
||||
|
||||
// 7. 35% 고정 크기 원형 틀 생성
|
||||
val rootLayout = LinearLayout(this@MyWallpaperService).apply {
|
||||
layoutParams = ViewGroup.LayoutParams(circleSize, circleSize)
|
||||
orientation = LinearLayout.VERTICAL
|
||||
gravity = Gravity.CENTER
|
||||
background = WavyOvalDrawable(
|
||||
bgColor = Color.parseColor("#40000000"),
|
||||
strokeColor = Color.parseColor("#09000000"),
|
||||
strokeThick = 40f
|
||||
)
|
||||
}
|
||||
|
||||
arrangedRows.forEach { rowView ->
|
||||
if (rowView != null) {
|
||||
val lp = LinearLayout.LayoutParams(wrapContent, wrapContent).apply {
|
||||
setMargins(0, 2, 0, 2)
|
||||
}
|
||||
rootLayout.addView(rowView, lp)
|
||||
}
|
||||
}
|
||||
|
||||
// 8. 강제 측정, 렌더링 및 캡처
|
||||
val exactSpec = View.MeasureSpec.makeMeasureSpec(circleSize, View.MeasureSpec.EXACTLY)
|
||||
rootLayout.measure(exactSpec, exactSpec)
|
||||
rootLayout.layout(0, 0, circleSize, circleSize)
|
||||
|
||||
val bitmap = Bitmap.createBitmap(circleSize, circleSize, Bitmap.Config.ARGB_8888)
|
||||
val canvas = Canvas(bitmap)
|
||||
rootLayout.draw(canvas)
|
||||
|
||||
return bitmap
|
||||
}
|
||||
|
||||
private val updateWeatherRunnable = object : Runnable {
|
||||
override fun run() {
|
||||
if (!isVisible) return
|
||||
|
||||
val (batteryLevel, isCharging) = getBatteryStatus()
|
||||
|
||||
// --- ⬇️ 제안하신 조건별 로직 적용 ⬇️ ---
|
||||
var nextDelay = 30000L // 기본 20초
|
||||
|
||||
if (isCharging) {
|
||||
nextDelay = 5000L // 충전 중이거나 70% 이상이면 10초
|
||||
nativeRenderer?.setImageRenderFrame(45)
|
||||
} else if (batteryLevel >= 80) {
|
||||
nativeRenderer?.setImageRenderFrame(70)
|
||||
} else {
|
||||
handler.removeCallbacks(this)
|
||||
return
|
||||
}
|
||||
|
||||
// 비트맵 생성 및 전달
|
||||
val weather = LocationUpdateService.lastWeather
|
||||
val bitmap = drawBitmapFromText(weather,isCharging)
|
||||
bitmap?.let {
|
||||
nativeRenderer?.setWeatherBitmap(it)
|
||||
}
|
||||
|
||||
handler.postDelayed(this, nextDelay)
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadMediaFiles() {
|
||||
loadFiles()
|
||||
if (mediaFiles.isNotEmpty()) {
|
||||
val initialFile = mediaFiles.random()
|
||||
Log.d(TAG, "Attempting to load initial random media via preloader: ${initialFile.absolutePath}")
|
||||
getFdFromPath(initialFile.absolutePath)?.let { fd ->
|
||||
nativeRenderer?.startNextPreload(fd)
|
||||
} ?: run {
|
||||
Log.e(TAG, "Failed to get fd for initial media: ${initialFile.absolutePath}")
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
val mediaDir = File(File(this@MyWallpaperService.getExternalFilesDir(null), "completed_torrents"), "Images")
|
||||
val supportedExtensions = listOf("mp4", "mkv", "avi", "mov","webm", "jpg", "jpeg", "png", "bmp", "webp", "gif")
|
||||
var randomQuote : QuoteItem? = null
|
||||
private val nextMediaCallback = object : NativeRenderer.NextMediaCallback {
|
||||
override fun onNextMediaRequested() {
|
||||
loadFiles()
|
||||
val nextFile = mediaFiles.random()
|
||||
Log.d(TAG, "Callback: Preloading next random media: ${nextFile.absolutePath}")
|
||||
// ⑥ 명언 (DB 랜덤 추출)
|
||||
val realm = WorkersDb.getRealm()
|
||||
val quotes = realm.query<QuoteItem>(QuoteItem::class).find().shuffled()
|
||||
randomQuote = if (quotes.isNotEmpty()) quotes.random() else null
|
||||
monoBold = resources.getFont(fontz.random())
|
||||
quote = resources.getFont(fontz.random())
|
||||
local = resources.getFont(fontz.random())
|
||||
numbers = resources.getFont(fontz.random())
|
||||
|
||||
getFdFromPath(nextFile.absolutePath)?.let { fd ->
|
||||
nativeRenderer?.startNextPreload(fd)
|
||||
} ?: run {
|
||||
Log.e(TAG, "Callback: Failed to get fd for ${nextFile.absolutePath}")
|
||||
}
|
||||
|
||||
val (batteryLevel, isCharging) = getBatteryStatus()
|
||||
|
||||
if (batteryLevel >= 70 || isCharging) {
|
||||
val bitmap = drawBitmapFromText(LocationUpdateService.lastWeather)
|
||||
bitmap?.let { nativeRenderer?.setWeatherBitmap(it) }
|
||||
nativeRenderer?.setImageRenderFrame(55)
|
||||
Log.d(TAG, "Battery Low: Weather updated only on media change.")
|
||||
} else {
|
||||
nativeRenderer?.setImageRenderFrame(99)
|
||||
nativeRenderer?.setWeatherBitmap(null)
|
||||
}
|
||||
if (isCharging || batteryLevel > 90) {
|
||||
// handler.post(updateWeatherRunnable)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun getFdFromPath(filePath: String): Int? {
|
||||
// val uri = MediaStore.Files.getContentUri("external")
|
||||
// val projection = arrayOf(MediaStore.Files.FileColumns._ID)
|
||||
// val selection = "${MediaStore.Files.FileColumns.DATA} = ?"
|
||||
// val selectionArgs = arrayOf(path)
|
||||
|
||||
return try {
|
||||
val file = File(filePath)
|
||||
if (file.exists() && file.canRead()) {
|
||||
// 읽기 전용으로 ParcelFileDescriptor 열기
|
||||
val pfd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
|
||||
// int형 fd 번호만 추출
|
||||
val fd = pfd.detachFd()
|
||||
|
||||
// C++로 전달
|
||||
fd
|
||||
} else {
|
||||
Log.e(TAG, "File does not exist or is not readable: $filePath")
|
||||
null
|
||||
}
|
||||
// contentResolver.query(uri, projection, selection, selectionArgs, null)?.use { cursor ->
|
||||
// if (cursor.moveToFirst()) {
|
||||
// val id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID))
|
||||
// val fileUri = ContentUris.withAppendedId(uri, id)
|
||||
// contentResolver.openFileDescriptor(fileUri, "r")?.use { pfd ->
|
||||
// pfd.detachFd()
|
||||
// }
|
||||
// } else null
|
||||
// }
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error getting FD for path: $filePath", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class WavyOvalDrawable(
|
||||
private val bgColor: Int,
|
||||
private val strokeColor: Int,
|
||||
private val strokeThick: Float
|
||||
) : Drawable() {
|
||||
|
||||
private val waveLength = 40f
|
||||
private val amplitude = 6f
|
||||
|
||||
private val bgPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
// 단일 색상이 아닌 Shader(그라데이션)를 사용할 것이므로 style만 지정
|
||||
style = Paint.Style.FILL
|
||||
}
|
||||
|
||||
private val strokePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = strokeColor
|
||||
style = Paint.Style.STROKE
|
||||
strokeWidth = 100f
|
||||
strokeCap = Paint.Cap.ROUND
|
||||
strokeJoin = Paint.Join.ROUND
|
||||
|
||||
val wavePath = Path().apply {
|
||||
moveTo(0f, 0f)
|
||||
quadTo(waveLength / 4, amplitude, waveLength / 2, 0f)
|
||||
quadTo(waveLength * 3 / 4, -amplitude, waveLength, 0f)
|
||||
}
|
||||
pathEffect = PathDashPathEffect(wavePath, waveLength, 0f, PathDashPathEffect.Style.MORPH)
|
||||
}
|
||||
|
||||
// 💡 뷰의 크기(Bounds)가 결정되거나 변경될 때 호출됩니다.
|
||||
// 여기서 크기에 맞는 그라데이션을 계산하여 페인트에 입힙니다.
|
||||
override fun onBoundsChange(bounds: Rect) {
|
||||
super.onBoundsChange(bounds)
|
||||
|
||||
val centerX = bounds.exactCenterX()
|
||||
val centerY = bounds.exactCenterY()
|
||||
val radius = Math.max(bounds.width(), bounds.height()) / 2f
|
||||
|
||||
if (radius > 0) {
|
||||
// 바깥쪽 색상: 입력받은 bgColor에서 투명도(Alpha)만 0으로 날려버린 색
|
||||
// 이렇게 해야 검은색->흰색으로 깨지는 현상 없이 자연스럽게 투명해집니다.
|
||||
val transparentColor = bgColor and 0x10FFFFFF
|
||||
|
||||
bgPaint.shader = RadialGradient(
|
||||
centerX,
|
||||
centerY,
|
||||
radius,
|
||||
intArrayOf(bgColor, transparentColor), // 중앙 -> 바깥 색상 배열
|
||||
floatArrayOf(0.4f, 1.1f), // 중심에서 40% 지점부터 투명해지기 시작
|
||||
Shader.TileMode.CLAMP
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override fun draw(canvas: Canvas) {
|
||||
val rectF = RectF(bounds)
|
||||
|
||||
|
||||
|
||||
// 2. 선 잘림 방지용 여백 계산
|
||||
val inset = 8f
|
||||
rectF.inset(inset, inset)
|
||||
|
||||
// 3. 물결 테두리 선 그리기
|
||||
canvas.drawOval(rectF, strokePaint)
|
||||
|
||||
// 1. 방사형 그라데이션 배경 채우기
|
||||
canvas.drawOval(rectF, bgPaint)
|
||||
}
|
||||
|
||||
override fun setAlpha(alpha: Int) {
|
||||
bgPaint.alpha = alpha
|
||||
strokePaint.alpha = alpha
|
||||
}
|
||||
|
||||
override fun setColorFilter(colorFilter: ColorFilter?) {}
|
||||
@Deprecated("Deprecated in Java")
|
||||
override fun getOpacity(): Int = PixelFormat.TRANSLUCENT
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
package bums.lunatic.launcher.wall
|
||||
|
||||
import android.graphics.Bitmap
|
||||
import android.util.Log
|
||||
import android.view.Surface
|
||||
|
||||
open class NativeRenderer {
|
||||
|
||||
interface NextMediaCallback {
|
||||
fun onNextMediaRequested()
|
||||
}
|
||||
|
||||
// 네이티브 핸들을 저장할 멤버 변수. 0은 유효하지 않은 핸들
|
||||
private var nativeHandle: Long = 0
|
||||
|
||||
// --- Public API ---
|
||||
|
||||
fun initialize(): Boolean {
|
||||
if (nativeHandle != 0L) {
|
||||
Log.w("NativeRenderer", "Already initialized.")
|
||||
return true
|
||||
}
|
||||
nativeHandle = nativeInit()
|
||||
return nativeHandle != 0L
|
||||
}
|
||||
|
||||
fun destroy() {
|
||||
if (nativeHandle != 0L) {
|
||||
nativeDestroy(nativeHandle)
|
||||
nativeHandle = 0L
|
||||
}
|
||||
}
|
||||
fun setWeatherBitmap(bitmap: Bitmap?) {
|
||||
if (nativeHandle != 0L) {
|
||||
nativeSetWeatherBitmap(nativeHandle, bitmap)
|
||||
}
|
||||
}
|
||||
fun render(surface: Surface) {
|
||||
if (nativeHandle != 0L) {
|
||||
nativeRender(nativeHandle, surface)
|
||||
}
|
||||
}
|
||||
|
||||
fun forceNext() {
|
||||
if (nativeHandle != 0L) {
|
||||
nativeForceNext(nativeHandle)
|
||||
}
|
||||
}
|
||||
|
||||
fun startNextPreload(fd: Int) {
|
||||
if (nativeHandle != 0L) {
|
||||
nativeStartNextPreload(nativeHandle, fd)
|
||||
}
|
||||
}
|
||||
|
||||
fun setAnimationSpeed(speed: Float) {
|
||||
if (nativeHandle != 0L) {
|
||||
nativeSetAnimationSpeed(nativeHandle, speed)
|
||||
}
|
||||
}
|
||||
|
||||
fun setAnimationMode(mode: Int) {
|
||||
if (nativeHandle != 0L) {
|
||||
nativeSetAnimationMode(nativeHandle, mode)
|
||||
}
|
||||
}
|
||||
|
||||
fun setFadeDuration(durationMs: Int) {
|
||||
if (nativeHandle != 0L) {
|
||||
nativeSetFadeDuration(nativeHandle, durationMs)
|
||||
}
|
||||
}
|
||||
|
||||
fun setTurnPageDuration(durationMs: Int) {
|
||||
if (nativeHandle != 0L) {
|
||||
nativeSetPageTurnDelay(nativeHandle, durationMs)
|
||||
}
|
||||
}
|
||||
|
||||
fun setTransitionMode(mode: Int) {
|
||||
if (nativeHandle != 0L) {
|
||||
nativeSetTransitionMode(nativeHandle, mode)
|
||||
}
|
||||
}
|
||||
|
||||
fun getDebugInfo(): String {
|
||||
return if (nativeHandle != 0L) {
|
||||
nativeGetDebugInfo(nativeHandle)
|
||||
} else {
|
||||
"Kotlin Wrapper: Native handle is null."
|
||||
}
|
||||
}
|
||||
|
||||
fun startRenderLoop(surface: Surface) {
|
||||
if (nativeHandle != 0L) {
|
||||
nativeStartRenderLoop(nativeHandle, surface)
|
||||
} else {
|
||||
"Kotlin Wrapper: Native handle is null."
|
||||
}
|
||||
}
|
||||
|
||||
fun stopRenderLoop() {
|
||||
if (nativeHandle != 0L) {
|
||||
nativeStopRenderLoop(nativeHandle)
|
||||
} else {
|
||||
"Kotlin Wrapper: Native handle is null."
|
||||
}
|
||||
}
|
||||
|
||||
fun setImageRenderFrame(frame:Int) {
|
||||
if (nativeHandle != 0L) {
|
||||
nativeSetImageRenderFrame(nativeHandle, frame)
|
||||
} else {
|
||||
"Kotlin Wrapper: Native handle is null."
|
||||
}
|
||||
}
|
||||
|
||||
// --- Private JNI declarations ---
|
||||
private external fun nativeStartRenderLoop(nativeHandle: Long, surface: Surface)
|
||||
private external fun nativeStopRenderLoop(nativeHandle: Long)
|
||||
private external fun nativeInit(): Long
|
||||
private external fun nativeDestroy(nativeHandle: Long)
|
||||
private external fun nativeRender(nativeHandle: Long, surface: Surface)
|
||||
private external fun nativeSetWeatherBitmap(nativeHandle: Long, bitmap: Bitmap?)
|
||||
private external fun nativeStartNextPreload(nativeHandle: Long, fd: Int)
|
||||
private external fun nativeSetImageRenderFrame(nativeHandle: Long, frame: Int)
|
||||
private external fun nativeSetAnimationSpeed(nativeHandle: Long, speed: Float)
|
||||
private external fun nativeSetAnimationMode(nativeHandle: Long, mode: Int)
|
||||
private external fun nativeSetFadeDuration(nativeHandle: Long, duration: Int)
|
||||
private external fun nativeGetDebugInfo(nativeHandle: Long): String
|
||||
private external fun nativeSetPageTurnDelay(nativeHandle: Long, duration: Int)
|
||||
private external fun nativeSetTransitionMode(nativeHandle: Long, mode: Int)
|
||||
private external fun nativeForceNext(nativeHandle: Long)
|
||||
// --- Companion Object ---
|
||||
|
||||
companion object {
|
||||
init {
|
||||
System.loadLibrary("native_renderer")
|
||||
}
|
||||
// --- ⬇️ 애니메이션 모드 상수 추가 ⬇️ ---
|
||||
const val ANIMATION_MODE_PAN = 0
|
||||
const val ANIMATION_MODE_ZOOM = 1
|
||||
const val ANIMATION_MODE_NONE = 2
|
||||
const val ANIMATION_MODE_RANDOM = 3
|
||||
const val ANIMATION_MODE_PAN_ONE_WAY = 4
|
||||
const val ANIMATION_MODE_PAGE_TURN = 5 // <-- 새로운 상수 추가
|
||||
|
||||
|
||||
const val TRANSITION_MODE_FADE = 0
|
||||
const val TRANSITION_MODE_SLIDE = 1
|
||||
const val TRANSITION_MODE_RANDOM = 2
|
||||
const val TRANSITION_MODE_MOSAIC = 3
|
||||
|
||||
// 이 콜백은 전역이라 일단 public external로 유지
|
||||
@JvmStatic
|
||||
external fun nativeSetNextMediaCallback(callback: NextMediaCallback)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user