package com.focusbox.app.ui import android.content.Intent import android.graphics.Typeface import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.Gravity import android.widget.FrameLayout import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import android.widget.Toast import androidx.activity.OnBackPressedCallback import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import com.focusbox.app.R import com.focusbox.app.data.Store import com.focusbox.app.model.Task import com.focusbox.app.service.TimerCore import com.focusbox.app.service.TimerService import com.focusbox.app.ui.focus.FocusFragment import com.focusbox.app.ui.projects.ProjectsFragment import com.focusbox.app.ui.settings.SettingsFragment import com.focusbox.app.ui.stats.StatsFragment import com.focusbox.app.ui.tasks.TasksFragment import com.focusbox.app.util.col import com.focusbox.app.util.dpi import com.focusbox.app.util.tint /** * 单 Activity + 五个常驻 Fragment。 * * 用 show/hide 而不是 replace:切回"任务"时滚动位置与筛选状态都还在, * 这对一个随手要记一笔的工具来说比省内存重要。 * * 注意:切换主题会把 Activity 重建,FragmentManager 会恢复出全部片段。 * 因此这里必须把"当前页"存进 savedInstanceState,并在 [showTab] 里显式隐藏 * 其余所有片段——只隐藏"上一次的 current"在重建后是 null,会造成两页重叠。 */ class MainActivity : AppCompatActivity() { companion object { const val EXTRA_TAB = "extra_tab" const val TAB_FOCUS = 0 const val TAB_TASKS = 1 const val TAB_PROJECTS = 2 const val TAB_STATS = 3 const val TAB_SETTINGS = 4 private const val KEY_TAB = "current_tab" private const val TAB_COUNT = 5 } private lateinit var container: FrameLayout private lateinit var navBar: LinearLayout private val fragments = arrayOfNulls(TAB_COUNT) private val navIcons = ArrayList() private val navLabels = ArrayList() private var current = -1 private val tabLabels = intArrayOf( R.string.nav_focus, R.string.nav_tasks, R.string.nav_projects, R.string.nav_stats, R.string.nav_settings, ) private val tabIcons = intArrayOf( R.drawable.ic_focus, R.drawable.ic_task, R.drawable.ic_project, R.drawable.ic_stats, R.drawable.ic_settings, ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) container = findViewById(R.id.container) navBar = findViewById(R.id.navBar) buildNav() // 返回键:非首页时回到首页,首页时退出(onBackPressed 已废弃,走 Dispatcher) onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { if (current != TAB_FOCUS) showTab(TAB_FOCUS) else finish() } }) val restored = savedInstanceState?.getInt(KEY_TAB, -1) ?: -1 val fromIntent = intent?.getIntExtra(EXTRA_TAB, -1) ?: -1 val start = when { restored in 0 until TAB_COUNT -> restored fromIntent in 0 until TAB_COUNT -> fromIntent else -> TAB_FOCUS } showTab(start, force = true) } override fun onStart() { super.onStart() // 进程曾被系统回收时,前台服务也随之消失;回到前台补一次拉起, // 否则计时状态还在走,却没有常驻通知也拿不到到点提醒。 if (TimerCore.running) TimerService.ensureRunning(this) } override fun onSaveInstanceState(outState: Bundle) { outState.putInt(KEY_TAB, current) super.onSaveInstanceState(outState) } /** 前台每 60 秒检查一次跨零点,重复任务在 0 点后自动生成当日实例 */ private val rollHandler = Handler(Looper.getMainLooper()) private val rollRunner = object : Runnable { override fun run() { if (runCatching { Store.rollRepeatingTasks() }.getOrDefault(0) > 0) { (fragments[TAB_TASKS] as? TasksFragment)?.reload() (fragments[TAB_PROJECTS] as? ProjectsFragment)?.reload() } rollHandler.postDelayed(this, 60_000L) } } override fun onResume() { // 进程常驻时跨天不会重走 App.onCreate,回到前台再滚一次重复任务。 // 放在 super 之前:片段 onResume 里的 reload 读到的就是推进后的日期。 runCatching { Store.rollRepeatingTasks() } // 打开/回到前台默认停在专注页;休息正在计时时不打断 if (!TimerCore.running && TimerCore.mode != TimerCore.MODE_FOCUS) { runCatching { TimerCore.setMode(TimerCore.MODE_FOCUS) } } super.onResume() rollHandler.removeCallbacks(rollRunner) rollHandler.postDelayed(rollRunner, 60_000L) } override fun onPause() { rollHandler.removeCallbacks(rollRunner) super.onPause() } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) val tab = intent?.getIntExtra(EXTRA_TAB, -1) ?: -1 if (tab in 0 until TAB_COUNT) showTab(tab, force = true) } private fun buildNav() { for (i in 0 until TAB_COUNT) { val item = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL gravity = Gravity.CENTER layoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1f) } val icon = ImageView(this).apply { setImageResource(tabIcons[i]) layoutParams = LinearLayout.LayoutParams(dpi(21f), dpi(21f)) } val label = TextView(this).apply { text = getString(tabLabels[i]) textSize = 10f includeFontPadding = false gravity = Gravity.CENTER val lp = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, ) lp.topMargin = dpi(3f) layoutParams = lp } item.addView(icon) item.addView(label) item.setOnClickListener { showTab(i) } navBar.addView(item) navIcons.add(icon) navLabels.add(label) } } private fun createFragment(index: Int): Fragment = when (index) { 0 -> FocusFragment() 1 -> TasksFragment() 2 -> ProjectsFragment() 3 -> StatsFragment() else -> SettingsFragment() } fun showTab(index: Int) { showTab(index, force = false) } /** * @param force 忽略"已在当前页"判断。重建、通知跳转时必须强制走一遍, * 否则恢复出来的其他片段不会被隐藏。 */ private fun showTab(index: Int, force: Boolean) { if (index !in 0 until TAB_COUNT) return if (!force && index == current && fragments[index] != null) return val fm = supportFragmentManager val tx = fm.beginTransaction() for (i in 0 until TAB_COUNT) { val tag = "tab$i" var f = fragments[i] if (f != null && f.isRemoving) f = null if (f == null) f = fm.findFragmentByTag(tag) if (i == index) { if (f == null) { f = createFragment(i) tx.add(R.id.container, f, tag) } else { tx.show(f) } fragments[i] = f } else if (f != null) { fragments[i] = f tx.hide(f) } } tx.commitNowAllowingStateLoss() current = index updateNav() } private fun updateNav() { navIcons.forEachIndexed { i, icon -> val selected = i == current icon.tint(col(if (selected) R.color.brand else R.color.text_tertiary)) navLabels[i].setTextColor(col(if (selected) R.color.brand else R.color.text_tertiary)) navLabels[i].typeface = if (selected) Typeface.DEFAULT_BOLD else Typeface.DEFAULT icon.alpha = if (selected) 1f else 0.85f } } /** 项目页点进去看任务:切到任务页并套用该项目的筛选 */ fun openProjectTasks(projectId: Long) { showTab(TAB_TASKS, force = true) (fragments[TAB_TASKS] as? TasksFragment)?.applyProjectFilter(projectId) } /** 任务行的播放键:把该任务设为当前任务并回到首页,圆环套用任务时长并直接开始 */ fun startFocusOn(task: Task) { if (TimerCore.running) { // 计时中换任务会把本轮记录归到新任务头上(起点还是旧轮的),必须禁止 Toast.makeText(this, R.string.timer_busy, Toast.LENGTH_SHORT).show() showTab(TAB_FOCUS) return } TimerCore.setCountUp(false) TimerCore.setTask(task.id, task.projectId, task.focusMinutes) if (TimerCore.mode != TimerCore.MODE_FOCUS) { TimerCore.setMode(TimerCore.MODE_FOCUS) } // 空闲时自动开跑,不用回到专注页再点一次「开始专注」 if (TimerCore.elapsedNow() <= 0) { TimerCore.start() } showTab(TAB_FOCUS) } /** 设置改动后(清空数据、改主题)统一刷新其余页面 */ fun refreshAll() { for (f in fragments) { when (f) { is TasksFragment -> f.reload() is ProjectsFragment -> f.reload() is StatsFragment -> f.reload() } } } }