당직근무 0.10.0 소스와 위젯 꾸미기 및 제작 매뉴얼 공개
위젯별 투명도와 밝은·어두운 색상 및 글자 크기와 표시 항목을 추가했다. 모든 위젯에 함께 적용하는 기본값과 개별 설정을 구분하고 크기에 따라 배치를 바꾼다. 포럼에 APK와 전체 소스 및 사용법과 제작 매뉴얼을 함께 배포한다. 앱 단위 검사 34개와 서버 검사 63개 및 웹 날짜·업데이트 검사 통과. 공개 소스에서 APK 빌드와 정적 검사 오류 0개 확인. 경고는 69개다. Android 16 가상 기기에서 기존 앱 위에 설치하고 투명 위젯과 큰 글자 및 RemoteViews 검사를 확인했다. 실제 휴대폰과 다른 홈 화면 앱의 절전·크기 동작은 별도 확인이 필요하다. 회원 DB와 인증 정보 및 배포 서명 키와 내부 운영 기록은 공개 자료에 포함하지 않았다.
This commit is contained in:
commit
8112721fa8
96 files changed
+7495
No files matched your search
@@ -0,0 +1,431 @@
|
||||
package kr.co.itosm.dutycalendar
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.app.DatePickerDialog
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.content.ComponentName
|
||||
import android.graphics.Typeface
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import android.os.Bundle
|
||||
import android.view.Gravity
|
||||
import android.view.View
|
||||
import android.widget.*
|
||||
import java.time.LocalDate
|
||||
import java.time.YearMonth
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* 오늘의 근무와 월간 달력 및 반복 설정을 한 화면에서 제공한다.
|
||||
* 저장된 근무표를 읽어 화면을 다시 그리며 월 이동만으로 저장된 기준일을 바꾸지 않는다.
|
||||
* 위젯과 계산식을 따로 만들지 않고 Schedule과 Holidays를 공유해 표시 결과를 맞춘다.
|
||||
*/
|
||||
class MainActivity : Activity() {
|
||||
private var month = YearMonth.now()
|
||||
private var selectedDate = LocalDate.now()
|
||||
private val planner by lazy { PlannerDialogs(this) { render() } }
|
||||
private val peopleEditor by lazy { PeopleDialogs(this) { render() } }
|
||||
private val anniversaries by lazy { AnniversaryDialogs(this) { render() } }
|
||||
private val deviceCalendar by lazy { DeviceCalendar(this) { render() } }
|
||||
private lateinit var content: LinearLayout
|
||||
private var scrollOffset = 0
|
||||
private var restoringScroll = false
|
||||
private var renderGeneration = 0
|
||||
private val ink = 0xFF26364D.toInt()
|
||||
private val muted = 0xFF626976.toInt()
|
||||
private val accent = 0xFF26364D.toInt()
|
||||
private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt()
|
||||
private fun background(color: Int, radius: Int = 5, border: Int? = null) = GradientDrawable().apply {
|
||||
setColor(color); cornerRadius = dp(radius).toFloat()
|
||||
border?.let { setStroke(dp(1), it) }
|
||||
}
|
||||
private fun label(value: String, size: Float = 15f, color: Int = ink, bold: Boolean = false) = TextView(this).apply {
|
||||
text = value; textSize = size; setTextColor(color)
|
||||
if (bold) setTypeface(typeface, Typeface.BOLD)
|
||||
}
|
||||
private fun column() = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
|
||||
private fun row() = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL }
|
||||
private fun button(title: String, filled: Boolean = false, action: () -> Unit) = Button(this).apply {
|
||||
text = title; isAllCaps = false; textSize = 14f
|
||||
minHeight = dp(48); minimumHeight = dp(48)
|
||||
setTextColor(if (filled) 0xFFFFFFFF.toInt() else accent)
|
||||
background = background(if (filled) accent else 0xFFEBEDF2.toInt(), 5)
|
||||
setPadding(dp(12), dp(8), dp(12), dp(8))
|
||||
setOnClickListener { action() }
|
||||
}
|
||||
private fun space(parent: LinearLayout, height: Int) { parent.addView(View(this), LinearLayout.LayoutParams(1, dp(height))) }
|
||||
private fun card(parent: LinearLayout, color: Int = 0xFFFFFFFF.toInt()): LinearLayout {
|
||||
return column().apply {
|
||||
background = background(color, 5, 0xFFDEDED8.toInt())
|
||||
setPadding(dp(16), dp(16), dp(16), dp(16))
|
||||
parent.addView(this, LinearLayout.LayoutParams(-1, -2))
|
||||
}
|
||||
}
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
savedInstanceState?.getString("month")?.let { month = YearMonth.parse(it) }
|
||||
savedInstanceState?.getString("selectedDate")?.let { selectedDate = LocalDate.parse(it) }
|
||||
if (savedInstanceState == null) intent.getStringExtra("selectedDate")?.let { value -> runCatching { selectedDate = LocalDate.parse(value); month = YearMonth.from(selectedDate) } }
|
||||
PlannerStore.migrate(this)
|
||||
render()
|
||||
if(savedInstanceState==null&&intent.hasExtra("widgetStyleId"))window.decorView.post { WidgetStyleDialog.show(this,intent.getIntExtra("widgetStyleId",-1)) }
|
||||
}
|
||||
override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState); outState.putString("month", month.toString()); outState.putString("selectedDate", selectedDate.toString()) }
|
||||
override fun onResume() {
|
||||
super.onResume(); render(); DutyWidget.updateAll(this); Reminders.reschedule(this)
|
||||
Holidays.schedule(this)
|
||||
Holidays.refresh(this) { success -> if (success) runOnUiThread { if (!isFinishing && !isDestroyed) render() } }
|
||||
SyncClient.schedule(this)
|
||||
SyncClient.foreground(this) { runOnUiThread { if (!isFinishing && !isDestroyed) render() } }
|
||||
UpdateChecker.check(this, fresh = true)
|
||||
}
|
||||
override fun onPause() { SyncClient.background(); super.onPause() }
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
// 첫 실행에서는 onResume보다 창 표시가 늦을 수 있다. 저장된 새 버전도 창이 준비된 뒤 안내한다.
|
||||
// 확인 간격과 나중에 알림 설정은 UpdateChecker가 유지하므로 초점 변경마다 통신하지 않는다.
|
||||
if (hasFocus) UpdateChecker.check(this)
|
||||
}
|
||||
|
||||
internal fun render() {
|
||||
// 다른 기기의 변경을 받더라도 사용자가 읽고 있던 위치를 유지한다.
|
||||
// 연결 확인과 공휴일 갱신이 연달아 끝나면 앞선 화면의 위치 복원이 아직 대기 중일 수 있다.
|
||||
// 이때 새 화면의 임시 0 위치를 읽으면 아래쪽 메뉴가 갑자기 맨 위로 돌아가므로 저장한 위치를 유지한다.
|
||||
if (!restoringScroll && ::content.isInitialized) scrollOffset = (content.parent as? ScrollView)?.scrollY ?: scrollOffset
|
||||
restoringScroll = true
|
||||
val generation = ++renderGeneration
|
||||
val schedule = ScheduleStore.load(this)
|
||||
val configured = ScheduleStore.isConfigured(this)
|
||||
val today = LocalDate.now()
|
||||
val people = People.all(this)
|
||||
val scroll = ScrollView(this).apply {
|
||||
isFillViewport = true; setBackgroundColor(0xFFF4F1EA.toInt())
|
||||
setOnScrollChangeListener { _, _, y, _, _ -> if (!restoringScroll && generation == renderGeneration) scrollOffset = y }
|
||||
}
|
||||
content = column().apply { setPadding(dp(16), dp(18), dp(16), dp(24)) }
|
||||
scroll.addView(content)
|
||||
// 최신 안드로이드의 화면 가장자리 표시에서도 상태 표시줄과 탐색 버튼에 내용이 가리지 않게 한다.
|
||||
// 구형 기기는 기존 여백 API를 사용한다. 앱의 최소 지원 버전에서도 같은 내용을 볼 수 있어야 한다.
|
||||
scroll.setOnApplyWindowInsetsListener { view, insets ->
|
||||
if (android.os.Build.VERSION.SDK_INT >= 30) {
|
||||
val bars = insets.getInsets(android.view.WindowInsets.Type.systemBars() or android.view.WindowInsets.Type.displayCutout())
|
||||
view.setPadding(bars.left, bars.top, bars.right, bars.bottom)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
view.setPadding(insets.systemWindowInsetLeft, insets.systemWindowInsetTop, insets.systemWindowInsetRight, insets.systemWindowInsetBottom)
|
||||
}
|
||||
insets
|
||||
}
|
||||
setContentView(scroll)
|
||||
val brand = row()
|
||||
brand.addView(ImageView(this).apply { setImageResource(R.drawable.ic_calendar); contentDescription = null }, LinearLayout.LayoutParams(dp(32), dp(36)).apply { marginEnd = dp(10) })
|
||||
brand.addView(label("당직근무", 23f, ink, true), LinearLayout.LayoutParams(0, -2, 1f))
|
||||
brand.addView(button("옵션") { showOptions() }, LinearLayout.LayoutParams(-2, dp(44)))
|
||||
content.addView(brand)
|
||||
space(content, 8)
|
||||
content.addView(label(if (SyncClient.connected(this)) SyncClient.message else "나의 근무 기록 · 이 기기에 저장", 12f, muted))
|
||||
space(content, 20)
|
||||
val todayCard = card(content, 0xFFFFFEFA.toInt())
|
||||
todayCard.addView(label(today.format(DateTimeFormatter.ofPattern("M월 d일 EEEE", Locale.KOREAN)), 12f, muted))
|
||||
space(todayCard, 6)
|
||||
todayCard.addView(label(if (configured) "오늘은 ${schedule.shiftOn(today).title}" else "근무표를 설정해 주세요", 22f, if (configured) schedule.shiftColor(today) else ink, true))
|
||||
space(todayCard, 6)
|
||||
todayCard.addView(label(if (configured) "${schedule.pattern.size}일 반복 · 다음 날 ${schedule.shiftOn(today.plusDays(1)).title}" else "여기를 눌러 근무표를 설정하세요. 아래는 예시입니다.", 13f, muted))
|
||||
if (!configured) {
|
||||
todayCard.isFocusable = true
|
||||
todayCard.setOnClickListener { showSettings() }
|
||||
}
|
||||
space(content, 16)
|
||||
// 자주 쓰는 일정과 근무 설정을 달력 바로 앞에 둔다. 연결 관리가 날짜 확인을 밀어내지 않도록 한다.
|
||||
val quickActions = row()
|
||||
quickActions.addView(button("일정 추가", true) { planner.event(selectedDate) }, LinearLayout.LayoutParams(0, dp(48), 1f).apply { marginEnd = dp(8) })
|
||||
quickActions.addView(button("당직 기초 설정") { showSettings() }, LinearLayout.LayoutParams(0, dp(48), 1f))
|
||||
content.addView(quickActions)
|
||||
space(content, 14)
|
||||
val calendar = card(content, 0xFFFFFEFA.toInt())
|
||||
val navigation = row()
|
||||
navigation.addView(label("${month.year}. ${month.monthValue.toString().padStart(2, '0')}", 24f, ink, true), LinearLayout.LayoutParams(0, -2, 1f))
|
||||
navigation.addView(button("오늘") { month = YearMonth.now(); render() }, LinearLayout.LayoutParams(dp(62), dp(44)))
|
||||
calendar.addView(navigation)
|
||||
space(calendar, 12)
|
||||
val week = row()
|
||||
listOf("일", "월", "화", "수", "목", "금", "토").forEachIndexed { i, text ->
|
||||
week.addView(label(text, 13f, if (i == 0) 0xFFBD5163.toInt() else if (i == 6) schedule.saturdayColor else muted, true).apply { gravity = Gravity.CENTER }, LinearLayout.LayoutParams(0, dp(32), 1f))
|
||||
}
|
||||
calendar.addView(week)
|
||||
// 한 주를 7칸으로 나누고 같은 너비를 배정한다. 공휴일은 날짜 색상과 이름으로 함께 구분한다.
|
||||
// 앞뒤 달의 근무도 계산하지만 투명도를 낮춰 현재 보고 있는 달과 혼동하지 않게 한다.
|
||||
calendarDays(month).chunked(7).forEach { dates ->
|
||||
val cells = row()
|
||||
dates.forEach { date ->
|
||||
val shift = schedule.shiftOn(date)
|
||||
val holiday = Holidays.name(this, date)
|
||||
val lunar = if (schedule.showLunar) LunarDates.label(this, date) else null
|
||||
val events = PlannerStore.eventsOn(this, date)
|
||||
val personalDays = Anniversaries.on(this, date)
|
||||
val colleagues = People.onDuty(people, date)
|
||||
val inside = YearMonth.from(date) == month
|
||||
val cell = column().apply {
|
||||
gravity = Gravity.TOP or Gravity.CENTER_HORIZONTAL
|
||||
setPadding(0, dp(6), 0, 0)
|
||||
if (date == today) background = background(0xFFE8ECF3.toInt(), 3, accent)
|
||||
alpha = if (inside) 1f else 0.55f
|
||||
val dateColor = schedule.dateColor(date, holiday != null)
|
||||
addView(label(date.dayOfMonth.toString(), 18f, dateColor, true).apply { gravity = Gravity.CENTER })
|
||||
if (lunar != null) addView(label(lunar, 9f, muted).apply { gravity = Gravity.CENTER; maxLines = 1 })
|
||||
addView(label(shift.shortTitle, 12f, schedule.shiftColor(date), true).apply {
|
||||
gravity = Gravity.CENTER
|
||||
setPadding(dp(4), dp(2), dp(4), dp(2))
|
||||
background = background(schedule.shiftPale(date), 3)
|
||||
}, LinearLayout.LayoutParams(-2, -2).apply { topMargin = dp(3) })
|
||||
if (holiday != null) addView(label(if (holiday.contains("대체공휴일")) "대체휴일" else holiday.replace("기독탄신일", "성탄절").replace("1월 1일", "신정"), 10f, 0xFFBD5163.toInt(), true).apply {
|
||||
gravity = Gravity.CENTER; maxLines = 1; ellipsize = android.text.TextUtils.TruncateAt.END
|
||||
})
|
||||
if (events.isNotEmpty()) addView(label("일정 ${events.size}", 10f, 0xFF8B653C.toInt(), true).apply { gravity = Gravity.CENTER })
|
||||
if (personalDays.isNotEmpty()) addView(label(personalDays.first().getJSONObject("data").getString("title"), 10f, 0xFF896238.toInt(), true).apply { gravity = Gravity.CENTER; maxLines = 1; ellipsize = android.text.TextUtils.TruncateAt.END })
|
||||
colleagues.take(2).forEach { person -> addView(label(person.name, 10f, person.color, true).apply { gravity = Gravity.CENTER; maxLines = 1; ellipsize = android.text.TextUtils.TruncateAt.END }) }
|
||||
if (colleagues.size > 2) addView(label("외 ${colleagues.size - 2}명", 9f, muted).apply { gravity = Gravity.CENTER })
|
||||
// 좁은 칸에서 공휴일 이름이 생략돼도 날짜를 누르면 전체 이름을 확인할 수 있다.
|
||||
// 화면 읽기 기능에도 날짜와 전체 근무 이름 및 공휴일을 함께 전달한다.
|
||||
contentDescription = "${date.monthValue}월 ${date.dayOfMonth}일 ${shift.title} ${lunar.orEmpty()} ${holiday.orEmpty()} 일정 ${events.size}개. 기념일: ${personalDays.joinToString { it.getJSONObject("data").getString("title") }}. 함께 당직: ${colleagues.joinToString { it.name }}"
|
||||
isFocusable = true
|
||||
setOnClickListener {
|
||||
selectedDate = date
|
||||
render()
|
||||
val titles = (events.map { it.getJSONObject("data").getString("title") } + personalDays.map { "기념일 · " + it.getJSONObject("data").getString("title") }).toTypedArray()
|
||||
AlertDialog.Builder(this@MainActivity).setTitle("${date.monthValue}월 ${date.dayOfMonth}일 ${shift.title}")
|
||||
.setItems(titles) { _, index -> if (index < events.size) planner.event(date, events[index]) else anniversaries.edit(personalDays[index - events.size]) }
|
||||
.setPositiveButton("일정 추가") { _, _ -> planner.event(date) }
|
||||
.setNeutralButton("날짜 상세") { _, _ ->
|
||||
AlertDialog.Builder(this@MainActivity).setTitle(date.toString()).setMessage("나: ${shift.title}\n${holiday ?: "공휴일이 아닙니다."}\n일정 ${events.size}개\n\n" + people.joinToString("\n") { "${it.name}: ${it.schedule.shiftOn(date).title}" }).setPositiveButton("확인", null).show()
|
||||
}.setNegativeButton("닫기", null).show()
|
||||
}
|
||||
}
|
||||
cells.addView(cell, LinearLayout.LayoutParams(0, dp((if (people.isEmpty()) 103 else 148) + if (schedule.showLunar) 14 else 0), 1f))
|
||||
}
|
||||
calendar.addView(View(this).apply { setBackgroundColor(0xFFE6E4DC.toInt()) }, LinearLayout.LayoutParams(-1, dp(1)))
|
||||
calendar.addView(cells)
|
||||
}
|
||||
space(calendar, 12)
|
||||
val monthButtons = row()
|
||||
monthButtons.addView(button("이전 달") { month = month.minusMonths(1); render() }, LinearLayout.LayoutParams(0, dp(44), 1f).apply { marginEnd = dp(8) })
|
||||
monthButtons.addView(button("다음 달") { month = month.plusMonths(1); render() }, LinearLayout.LayoutParams(0, dp(44), 1f))
|
||||
calendar.addView(monthButtons)
|
||||
space(calendar, 14)
|
||||
calendar.addView(label("당직 · 일반 · 주간 · 오후 · 야간 · 비번 · 휴무", 11f, muted).apply { gravity = Gravity.CENTER })
|
||||
space(content, 16)
|
||||
val connection = card(content, 0xFFFFFEFA.toInt())
|
||||
connection.addView(label("웹과 연결", 16f, ink, true))
|
||||
if (SyncClient.connected(this)) {
|
||||
val tools = row()
|
||||
tools.addView(button("새로 불러오기") { SyncClient.sync(this, force = true) }, LinearLayout.LayoutParams(0, dp(48), 1f))
|
||||
tools.addView(button("소속 회사") { planner.openWebsite() }, LinearLayout.LayoutParams(0, dp(48), 1f))
|
||||
connection.addView(tools)
|
||||
PlannerStore.company(this)?.let { company -> connection.addView(label("소속 · ${company.getString("name")} · 근무표 공유", 12f, muted)) }
|
||||
connection.addView(label("저장된 자료 사용 · 월 1회 또는 변경 시 갱신", 11f, muted))
|
||||
}
|
||||
connection.addView(Switch(this).apply {
|
||||
text = "웹 연동 (선택)"; textSize = 14f; minHeight = dp(48); isChecked = SyncClient.enabled(this@MainActivity)
|
||||
setOnCheckedChangeListener { _, checked ->
|
||||
if (checked && !SyncClient.enabled(this@MainActivity)) { isChecked = false; planner.connection() }
|
||||
else if (!checked && SyncClient.enabled(this@MainActivity)) { SyncClient.disable(this@MainActivity); render() }
|
||||
}
|
||||
})
|
||||
space(content, 16)
|
||||
if (SyncClient.connected(this)) {
|
||||
val peopleCard = card(content)
|
||||
peopleCard.addView(label("함께 보는 근무표", 18f, ink, true))
|
||||
space(peopleCard, 6)
|
||||
peopleCard.addView(label("${selectedDate.monthValue}월 ${selectedDate.dayOfMonth}일 · 직접 등록한 근무표는 이름을 눌러 수정합니다.", 12f, muted))
|
||||
space(peopleCard, 8)
|
||||
people.forEach { person ->
|
||||
peopleCard.addView(button("${person.name} · ${person.schedule.shiftOn(selectedDate).title} (${person.schedule.pattern.size}일 반복${if (person.shared) " · 소속" else ""})") { if (person.shared) Toast.makeText(this, "소속 회원의 근무표는 본인만 수정할 수 있습니다.", Toast.LENGTH_LONG).show() else peopleEditor.edit(person) }.apply { setTextColor(person.color) }, LinearLayout.LayoutParams(-1, -2))
|
||||
}
|
||||
if (people.isEmpty()) peopleCard.addView(label("이름과 반복 근무를 등록하면 날짜별 당직을 함께 볼 수 있습니다.", 13f, muted))
|
||||
peopleCard.addView(button("함께 볼 사람 추가") { peopleEditor.edit() }, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
space(content, 16)
|
||||
} else {
|
||||
val memberInfo = card(content)
|
||||
memberInfo.addView(label("함께 보는 근무표 · 회원 전용", 18f, ink, true))
|
||||
space(memberInfo, 8)
|
||||
memberInfo.addView(label("로그인하면 다른 사람의 근무표와 소속 근무표를 함께 볼 수 있습니다.", 13f, muted))
|
||||
space(memberInfo, 10)
|
||||
memberInfo.addView(button("로그인하고 함께 보기") { planner.connection() }, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
space(content, 16)
|
||||
}
|
||||
val agenda = card(content)
|
||||
agenda.addView(label("${selectedDate.monthValue}월 ${selectedDate.dayOfMonth}일 일정", 18f, ink, true))
|
||||
space(agenda, 10)
|
||||
val selectedEvents = PlannerStore.eventsOn(this, selectedDate)
|
||||
val selectedDays = Anniversaries.on(this, selectedDate)
|
||||
if (selectedEvents.isEmpty() && selectedDays.isEmpty()) agenda.addView(label("등록된 일정이 없습니다. 날짜를 눌러 새 일정을 추가하세요.", 13f, muted))
|
||||
selectedDays.forEach { item ->
|
||||
val data = item.getJSONObject("data")
|
||||
agenda.addView(button("${data.getString("title")}\n${Anniversaries.description(data)}") { anniversaries.edit(item) }, LinearLayout.LayoutParams(-1, -2))
|
||||
}
|
||||
if (SyncClient.connected(this)) {
|
||||
agenda.addView(button("내 생일·기념일 관리") { anniversaries.list() }, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
agenda.addView(label("내 계정에 보관 · 같은 계정으로 재로그인하면 복원", 12f, muted))
|
||||
}
|
||||
agenda.addView(button("알바·시간근무 추가") { planner.event(selectedDate, partTime = true) }, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
selectedEvents.forEach { item ->
|
||||
val data = item.getJSONObject("data")
|
||||
val time = PlannerStore.timeSummary(data)
|
||||
agenda.addView(button("${data.getString("title")}\n$time") { planner.event(selectedDate, item) }, LinearLayout.LayoutParams(-1, dp(64)).apply { bottomMargin = dp(8) })
|
||||
}
|
||||
if (PlannerStore.conflictCount(this) > 0) {
|
||||
space(agenda, 12)
|
||||
agenda.addView(button("동시에 수정된 내용 확인", true) { planner.conflict() }, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
}
|
||||
space(content, 16)
|
||||
val settings = card(content)
|
||||
settings.addView(label("나의 반복 근무", 18f, ink, true))
|
||||
space(settings, 8)
|
||||
settings.addView(label("주${schedule.workWeek}일제 · 토요일 ${if (schedule.workWeek == 5) "당직 외 휴무" else "기존 근무"}", 12f, muted))
|
||||
settings.addView(label(schedule.pattern.joinToString(" → ") { it.title }, 14f, muted))
|
||||
space(settings, 4)
|
||||
settings.addView(label(if (configured) "첫째 날: ${schedule.anchor}" else "시작 날짜를 저장하면 위젯에도 반영됩니다.", 12f, muted))
|
||||
space(settings, 14)
|
||||
settings.addView(button("당직 기초 설정", true) { showSettings() }, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
space(settings, 8)
|
||||
settings.addView(button("옵션 · 날짜 색상과 음력") { showOptions() }, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
space(content, 12)
|
||||
content.addView(button("위젯 꾸미기 · 투명도와 크기") { WidgetStyleDialog.show(this) }, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
content.addView(button("홈 화면에 달력 추가") { pinWidget() }, LinearLayout.LayoutParams(-1, dp(52)))
|
||||
space(content, 10)
|
||||
content.addView(label("위젯은 앱을 닫아도 홈 화면에 표시됩니다.\n홈 화면을 길게 누른 뒤 ‘위젯’에서도 추가할 수 있습니다.", 12f, muted).apply { gravity = Gravity.CENTER })
|
||||
space(content, 20)
|
||||
val holidayInfo = card(content)
|
||||
holidayInfo.addView(label("대한민국 공휴일", 17f, ink, true))
|
||||
space(holidayInfo, 6)
|
||||
val updateTime = Holidays.updatedAt(this)
|
||||
val updated = if (updateTime == 0L) "기본 공휴일 자료를 사용 중입니다." else "최근 갱신: " + java.text.SimpleDateFormat("yyyy.MM.dd HH:mm", Locale.KOREAN).format(java.util.Date(updateTime))
|
||||
holidayInfo.addView(label(if (month.year in Holidays.years(this)) "공휴일과 대체공휴일을 자동으로 갱신합니다.\n$updated" + if (Holidays.usesSaved(this)) "\n서버에 보관된 정상 자료를 사용합니다." else "" else "${month.year}년 자료가 아직 제공되지 않았습니다.\n공휴일이 없는 것으로 판단하지 마세요.", 12f, muted))
|
||||
space(holidayInfo, 10)
|
||||
holidayInfo.addView(button("공휴일 새로고침") {
|
||||
Holidays.refresh(this, force = true) { success -> runOnUiThread {
|
||||
if (!isFinishing && !isDestroyed) {
|
||||
render()
|
||||
Toast.makeText(this, if (success) { if (Holidays.usesSaved(this)) "제공처 확인이 지연되어 저장된 공휴일을 표시합니다." else "공휴일을 갱신했습니다." } else "연결을 확인해 주세요. 저장된 공휴일을 계속 표시합니다.", Toast.LENGTH_LONG).show()
|
||||
}
|
||||
} }
|
||||
}, LinearLayout.LayoutParams(-1, dp(44)))
|
||||
space(holidayInfo, 8)
|
||||
holidayInfo.addView(label("음력 표시: 1900~2050년 · 한국 음력 기준", 11f, muted).apply {
|
||||
setOnClickListener { AlertDialog.Builder(this@MainActivity).setTitle("음력 자료 이용 조건").setMessage(assets.open("lunar-LICENSE.txt").bufferedReader().use { it.readText() }).setPositiveButton("확인", null).show() }
|
||||
})
|
||||
holidayInfo.addView(label("월력요항 기반 공개 자료 · holidays-kr\n공휴일에도 설정한 근무 순서는 유지됩니다.", 11f, muted).apply {
|
||||
setOnClickListener {
|
||||
val license = assets.open("holidays-LICENSE.txt").bufferedReader().use { it.readText() }
|
||||
AlertDialog.Builder(this@MainActivity).setTitle("공휴일 자료 출처")
|
||||
.setMessage("https://github.com/hyunbinseo/holidays-kr\n\n월력요항을 기반으로 관리되는 공개 자료입니다. 임시공휴일은 제공 자료가 갱신된 뒤 반영됩니다.\n\n$license")
|
||||
.setPositiveButton("확인", null).show()
|
||||
}
|
||||
})
|
||||
space(content, 24)
|
||||
content.addView(button("앱 업데이트 확인") { UpdateChecker.check(this, force = true) }, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
space(content, 12)
|
||||
content.addView(label("제작자 블리어 (이창현)", 13f, muted).apply { gravity = Gravity.CENTER })
|
||||
space(content, 4)
|
||||
content.addView(label("당직근무 " + packageManager.getPackageInfo(packageName, 0).versionName, 11f, muted).apply { gravity = Gravity.CENTER })
|
||||
scroll.post {
|
||||
if (generation == renderGeneration) {
|
||||
scroll.scrollTo(0, scrollOffset)
|
||||
restoringScroll = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 기준일을 저장한 뒤 홈 화면에 위젯 추가를 요청한다. 최종 배치와 크기는 홈 화면 앱이 관리한다.
|
||||
* 바로 추가하는 기능을 지원하지 않는 홈 화면에서는 위젯 목록으로 추가하는 방법을 안내한다.
|
||||
* 별도 오버레이 권한을 요구하지 않으며 일반적인 안드로이드 위젯으로 동작한다.
|
||||
*/
|
||||
private fun pinWidget() {
|
||||
if (!ScheduleStore.isConfigured(this)) { showSettings(); return }
|
||||
val manager = getSystemService(AppWidgetManager::class.java)
|
||||
if (manager.isRequestPinAppWidgetSupported) {
|
||||
manager.requestPinAppWidget(ComponentName(this, DutyWidget::class.java), null, null)
|
||||
} else {
|
||||
AlertDialog.Builder(this).setTitle("홈 화면에 추가하기").setMessage("홈 화면의 빈 곳을 길게 누른 뒤 위젯 목록에서 ‘당직근무’를 선택해 주세요.").setPositiveButton("확인", null).show()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 설정 창에서는 저장값을 복사한 임시 목록만 바꾼다. 취소하면 기존 근무표에 영향을 주지 않는다.
|
||||
* 반복 일수가 늘어나면 추가된 날은 일반근무로 채운다. 줄어들면 뒤쪽 날을 잘라낸다.
|
||||
* 저장을 누를 때만 기준일과 전체 순서를 함께 반영하고 모든 홈 위젯을 갱신한다.
|
||||
*/
|
||||
private fun showSettings() {
|
||||
val current = ScheduleStore.load(this)
|
||||
var anchor = current.anchor
|
||||
val form = column().apply { setPadding(dp(20), dp(8), dp(20), dp(8)) }
|
||||
form.addView(label("근무 방식과 반복 순서 및 기준일을 정합니다.\n날짜 색상과 음력은 옵션에서 바꿀 수 있습니다.", 12f, muted))
|
||||
val patternEditor = ShiftPatternEditor(this, current.pattern, current.workWeek)
|
||||
form.addView(patternEditor)
|
||||
space(form, 12)
|
||||
form.addView(label("1일째에 해당하는 날짜", 14f, ink, true))
|
||||
lateinit var dateButton: Button
|
||||
dateButton = button(anchor.toString()) {
|
||||
DatePickerDialog(this, { _, year, monthIndex, day ->
|
||||
anchor = LocalDate.of(year, monthIndex + 1, day)
|
||||
dateButton.text = anchor.toString()
|
||||
}, anchor.year, anchor.monthValue - 1, anchor.dayOfMonth).show()
|
||||
}
|
||||
space(form, 8)
|
||||
form.addView(dateButton, LinearLayout.LayoutParams(-1, dp(48)))
|
||||
space(form, 10)
|
||||
form.addView(label("선택한 날짜부터 위 순서가 반복됩니다.\n비번과 휴일을 포함해 날짜 단위로 계산합니다.", 12f, muted))
|
||||
val scroll = ScrollView(this).apply { addView(form) }
|
||||
val dialog = AlertDialog.Builder(this).setTitle("당직 기초 설정").setView(scroll)
|
||||
.setNegativeButton("취소", null).setPositiveButton("저장", null).create()
|
||||
dialog.setOnShowListener {
|
||||
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
|
||||
// 기초 설정에서 표시 옵션을 저장하지 않는다. 창을 연 뒤 들어온 최신 표시 선택도 보존한다.
|
||||
runCatching { ScheduleStore.save(this, ScheduleStore.load(this).copy(anchor = anchor, pattern = patternEditor.pattern(), workWeek = patternEditor.workWeek())) }
|
||||
.onSuccess { render(); dialog.dismiss(); Toast.makeText(this, "근무표와 위젯을 갱신했습니다.", Toast.LENGTH_SHORT).show() }
|
||||
.onFailure { Toast.makeText(this, it.message ?: "입력 내용을 확인해 주세요.", Toast.LENGTH_LONG).show() }
|
||||
}
|
||||
}
|
||||
dialog.show()
|
||||
}
|
||||
|
||||
/** 계산 기준과 표시 선택을 분리한다. 취소는 저장하지 않으며 옵션 저장도 근무 순서를 바꾸지 않는다. */
|
||||
private fun showOptions() {
|
||||
val current = ScheduleStore.load(this)
|
||||
val form = column().apply { setPadding(dp(20), dp(8), dp(20), dp(16)) }
|
||||
form.addView(label("달력 표시", 16f, ink, true))
|
||||
form.addView(label(if (SyncClient.connected(this)) "${SyncClient.memberName(this)} 계정에 개인 설정을 보관합니다." else "현재 기기에 저장합니다. 회원 로그인 후 서버에 보관할 수 있습니다.", 12f, muted))
|
||||
form.addView(button("위젯 꾸미기 · 투명도와 크기") { WidgetStyleDialog.show(this) }, LinearLayout.LayoutParams(-1,dp(48)))
|
||||
form.addView(button("휴대폰 달력 연동") { deviceCalendar.open() }, LinearLayout.LayoutParams(-1,dp(48)))
|
||||
form.addView(label("앱과 홈 위젯에 함께 적용합니다.\n근무 순서와 기준일은 바뀌지 않습니다.", 12f, muted))
|
||||
fun choice(title: String, description: String, checked: Boolean): CheckBox {
|
||||
val option = CheckBox(this).apply { text = title; textSize = 14f; isChecked = checked; minHeight = dp(48) }
|
||||
space(form, 8); form.addView(option); form.addView(label(description, 12f, muted))
|
||||
return option
|
||||
}
|
||||
val weekday = choice("당직일은 평일색으로 표시", "주말·공휴일에도 당직 날짜는 평일색으로 표시합니다.", current.dutyAsWeekday)
|
||||
val off = choice("비번을 빨간색으로 표시", "비번 날짜와 비번 글씨를 빨간색으로 표시합니다.", current.offAsHoliday)
|
||||
val lunar = choice("음력 날짜 함께 보기", "양력 아래에 작은 글씨로 표시합니다. 윤달은 윤으로 구분합니다.", current.showLunar)
|
||||
val dialog = AlertDialog.Builder(this).setTitle("옵션").setView(ScrollView(this).apply { addView(form) })
|
||||
.setNegativeButton("취소", null).setPositiveButton("저장", null).create()
|
||||
dialog.setOnShowListener {
|
||||
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
|
||||
runCatching { ScheduleStore.saveDisplay(this, weekday.isChecked, lunar.isChecked, off.isChecked) }
|
||||
.onSuccess { render(); dialog.dismiss(); Toast.makeText(this, "표시 옵션을 저장했습니다.", Toast.LENGTH_SHORT).show() }
|
||||
.onFailure { Toast.makeText(this, it.message ?: "저장 공간을 확인해 주세요.", Toast.LENGTH_LONG).show() }
|
||||
}
|
||||
}
|
||||
dialog.show()
|
||||
}
|
||||
|
||||
override fun onRequestPermissionsResult(requestCode:Int,permissions:Array<out String>,grantResults:IntArray) {
|
||||
super.onRequestPermissionsResult(requestCode,permissions,grantResults)
|
||||
deviceCalendar.permissionResult(requestCode,grantResults)
|
||||
if(requestCode==Reminders.REQUEST_NOTIFY) {
|
||||
Reminders.reschedule(this)
|
||||
Toast.makeText(this,if(grantResults.firstOrNull()==android.content.pm.PackageManager.PERMISSION_GRANTED)"일정 알림을 켰습니다." else "알림을 허용하면 저장한 일정의 알림을 받을 수 있습니다.",Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user