Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,16 @@ repository does not keep a copy.
cannot be updated by a release APK and point to the website instead.
- Phones show one pane at a time; tablets and unfolded foldables show the
shelf beside the note. Light and dark themes follow the system.
- **Languages**: 简体中文 and English, as on the web (`core/…/Strings.kt`,
one interface, so a string missing from a language does not compile).
The language follows the system (the first supported one in its list,
English otherwise) until one is picked under 语言 · Language (library
menu, libraries list, account sheet); the choice is remembered. Signed in
to a synced library, the account's language (`User.language`) comes first;
choosing there also saves it to the account (`PATCH /me {language}`, kept
as pending and sent later when offline; "follow the system" clears it).
A new account is registered with the language in use (`language` in
`POST /auth/register`). See guide §界面语言 and `LanguageSettings`.

## Layout

Expand Down
126 changes: 63 additions & 63 deletions app/src/main/assets/editor/main.js

Large diffs are not rendered by default.

40 changes: 40 additions & 0 deletions app/src/main/kotlin/app/ivynote/android/IvyApp.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package app.ivynote.android

import android.app.Application
import android.content.res.Configuration
import android.os.Build
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
Expand All @@ -9,6 +10,8 @@ import app.ivynote.android.platform.KeystoreCredentialStore
import app.ivynote.android.platform.SharedPrefsStore
import app.ivynote.android.update.Updater
import app.ivynote.core.IvyHttp
import app.ivynote.core.Language
import app.ivynote.core.LanguageSettings
import app.ivynote.core.LibraryCatalog
import app.ivynote.core.OfficialRegions
import app.ivynote.core.newEntityId
Expand All @@ -18,7 +21,9 @@ import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.io.File
import java.util.Locale

/**
* Holds what outlives screens: the library catalog and the open library
Expand All @@ -29,6 +34,12 @@ class IvyApp : Application() {
private set
lateinit var catalog: LibraryCatalog
private set
lateinit var language: LanguageSettings
private set

/** The system's locale (or this app's, set in the system settings), before ours replaces the default. */
var systemLocale: Locale = Locale.getDefault()
private set

/** New versions from the website: checks, the update dialog, downloads, install. */
lateinit var updater: Updater
Expand All @@ -45,6 +56,10 @@ class IvyApp : Application() {
instance = this
IvyHttp.userAgent = "Ivynote-Android/${BuildConfig.VERSION_NAME} (Android ${Build.VERSION.RELEASE})"
prefs = SharedPrefsStore(this)
systemLocale = systemLocales(resources.configuration).firstOrNull() ?: Locale.getDefault()
language = LanguageSettings(prefs, systemLocales(resources.configuration).map { it.toLanguageTag() })
applyLocale(language.current.value)
appScope.launch { language.current.collect { applyLocale(it) } }
// Official node addresses: the website's last answer, else the built-in ones.
OfficialRegions.install(prefs)
catalog = LibraryCatalog(
Expand All @@ -60,6 +75,31 @@ class IvyApp : Application() {
updater.start()
}

override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
// The system language changed: the framework has reset the default locale.
systemLocale = systemLocales(newConfig).firstOrNull() ?: systemLocale
language.systemChanged(systemLocales(newConfig).map { it.toLanguageTag() })
applyLocale(language.current.value)
}

/**
* Dates, relative times and number formats follow the interface
* language. The region stays the system's (it picks the sync node).
*/
private fun applyLocale(lang: Language) {
// The system's own English (en-GB dates); Chinese is always the simplified script.
val base = if (lang == Language.EN && systemLocale.language == "en") systemLocale else null
val locale = base ?: Locale.Builder().setLanguage(lang.tag).setRegion(systemLocale.country.takeIf { it.length == 2 } ?: "")
.apply { if (lang == Language.ZH) setScript("Hans") }.build()
Locale.setDefault(locale)
}

private fun systemLocales(config: Configuration): List<Locale> {
val list = config.locales
return (0 until list.size()).map { list[it] }
}

/** This install's HLC node and `device` name, e.g. `android-a1b2c3d4` (guide 6.2). */
val deviceId: String
get() {
Expand Down
3 changes: 2 additions & 1 deletion app/src/main/kotlin/app/ivynote/android/LibrarySession.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import app.ivynote.android.editor.AttachmentLoader
import app.ivynote.android.editor.EditorHost
import app.ivynote.android.platform.SqliteDocumentStore
import app.ivynote.android.platform.networkAvailable
import app.ivynote.core.L10n
import app.ivynote.core.AddedFile
import app.ivynote.core.ApiClient
import app.ivynote.core.ApiError
Expand Down Expand Up @@ -89,7 +90,7 @@ class LibrarySession private constructor(
val type = resolver.getType(uri)
?: name?.substringAfterLast('.', "")?.lowercase()?.let { MimeTypeMap.getSingleton().getMimeTypeFromExtension(it) }
?: "application/octet-stream"
(resolver.openInputStream(uri) ?: throw java.io.IOException("无法读取文件")).use { input ->
(resolver.openInputStream(uri) ?: throw java.io.IOException(L10n.s.cannotReadFile)).use { input ->
tmp.outputStream().use { input.copyTo(it) }
}
(name ?: fallbackName ?: defaultName(type)) to type
Expand Down
3 changes: 2 additions & 1 deletion app/src/main/kotlin/app/ivynote/android/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import app.ivynote.android.ui.IvyTheme
import app.ivynote.android.ui.ProvideStrings
import app.ivynote.android.ui.RootScreen

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContent {
IvyTheme { RootScreen() }
ProvideStrings { IvyTheme { RootScreen() } }
}
}
}
12 changes: 12 additions & 0 deletions app/src/main/kotlin/app/ivynote/android/editor/EditorHost.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ import androidx.webkit.WebViewFeature
import app.ivynote.android.BuildConfig
import app.ivynote.android.IvyApp
import app.ivynote.android.LibrarySession
import app.ivynote.core.L10n
import app.ivynote.core.Language
import app.ivynote.core.Attachment
import app.ivynote.core.IvyJson
import app.ivynote.core.Note
Expand Down Expand Up @@ -121,6 +123,7 @@ class EditorHost(appContext: Context, private val session: LibrarySession) {
sendTitles()
refreshKinds()
call("ivy.setTheme($dark)")
setLanguage(L10n.language)
val payload = buildJsonObject {
put("id", note.id)
put("body", note.body)
Expand Down Expand Up @@ -175,6 +178,14 @@ class EditorHost(appContext: Context, private val session: LibrarySession) {

fun setReadonly(ro: Boolean) = call("ivy.setReadonly($ro)")

/** The placeholder and the words formatting wraps around an empty selection. */
fun setLanguage(language: Language) {
if (language == sentLanguage) return
sentLanguage = language
call("ivy.setLanguage(${JsonPrimitive(language.tag)})")
}
private var sentLanguage: Language? = null

fun setTheme(dark: Boolean) {
this.dark = dark
call("ivy.setTheme($dark)")
Expand Down Expand Up @@ -302,6 +313,7 @@ class EditorHost(appContext: Context, private val session: LibrarySession) {
view.destroy()
queued.clear()
sentKinds = ""
sentLanguage = null
_webView.value = create()
val id = noteId
val note = id?.let { engine.notes[it] }
Expand Down
47 changes: 28 additions & 19 deletions app/src/main/kotlin/app/ivynote/android/ui/AccountSheet.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package app.ivynote.android.ui

import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
Expand Down Expand Up @@ -52,54 +53,62 @@ fun AccountSheet(lib: LibrarySession, session: SessionStore, onDismiss: () -> Un
val revision by engine.revision.collectAsState()
var confirmSignOut by remember { mutableStateOf(false) }
var signingOut by remember { mutableStateOf(false) }
var choosingLanguage by remember { mutableStateOf(false) }
val s = LocalStrings.current

ModalBottomSheet(onDismissRequest = onDismiss, sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), containerColor = c.canvas) {
Column(
Modifier.verticalScroll(rememberScrollState()).padding(horizontal = 20.dp).navigationBarsPadding().padding(bottom = 24.dp),
verticalArrangement = Arrangement.spacedBy(14.dp),
) {
Text("账户", style = SerifTitle, fontSize = 20.sp, color = c.ink)
Text(s.account, style = SerifTitle, fontSize = 20.sp, color = c.ink)
Card {
Field("名称", account.user.name)
Field("用户名", account.user.username)
if (account.user.email.isNotEmpty()) Field("邮箱", account.user.email)
Field("角色", if (account.user.isAdmin) "管理员" else "用户")
Field(s.name, account.user.name)
Field(s.username, account.user.username)
if (account.user.email.isNotEmpty()) Field(s.email, account.user.email)
Field(s.role, if (account.user.isAdmin) s.admin else s.user)
// The account's language: kept by the server, on all its devices.
Field(s.language, choiceLabel(IvyApp.instance.language.selected.collectAsState().value, s), onClick = { choosingLanguage = true })
}
Caption("同步 · ${lib.ref.name}")
Caption(s.syncSection(lib.ref.name))
Card {
Field("服务器", account.server.toString())
Field(s.server, account.server.toString())
Row(Modifier.fillMaxWidth().padding(vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) {
Text("状态", color = c.ink2, fontSize = 15.sp, modifier = Modifier.width(88.dp))
Text(s.status, color = c.ink2, fontSize = 15.sp, modifier = Modifier.width(88.dp))
SyncStatusLine(engine, state)
}
Field("笔记", remember(revision) { engine.liveNotes.size.toString() })
Field("本设备", engine.device)
Field(s.notes, remember(revision) { engine.liveNotes.size.toString() })
Field(s.thisDevice, engine.device)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedButton(onClick = { lib.engine.let { e -> app.appScope.launch { e.sync() } } }, enabled = state.status != SyncState.Status.SYNCING) {
Text("立即同步")
Text(s.syncNow)
}
if (account.user.isAdmin) {
OutlinedButton(onClick = {
runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(account.server.base + "/admin"))) }
}) { Text("打开管理后台") }
}) { Text(s.openAdmin) }
}
}
}
Surface(shape = RoundedCornerShape(16.dp), color = c.surface, modifier = Modifier.fillMaxWidth()) {
TextButton(onClick = { confirmSignOut = true }, enabled = !signingOut, modifier = Modifier.padding(4.dp)) {
Text(if (signingOut) "正在退出…" else "退出登录", color = c.danger, fontWeight = FontWeight.Medium)
Text(if (signingOut) s.signingOut else s.signOut, color = c.danger, fontWeight = FontWeight.Medium)
}
}
Text("退出后,本设备上这个笔记库的副本会被删除;服务器上的数据不受影响。重新登录后会再次下载。", fontSize = 12.5.sp, color = c.muted)
Text(s.signOutHint, fontSize = 12.5.sp, color = c.muted)
}
}

if (choosingLanguage) {
LanguageDialog(onDismiss = { choosingLanguage = false })
}

if (confirmSignOut) {
val unsynced = state.pending + state.blocked
ConfirmDialog(
title = "退出登录?",
message = if (unsynced > 0) "还有 $unsynced 条更改没有同步到服务器,退出后会丢失。" else "这台设备的登录令牌会被撤销,本地数据会被删除。",
confirm = "退出登录",
title = s.signOutTitle,
message = if (unsynced > 0) s.signOutUnsynced(unsynced) else s.signOutMessage,
confirm = s.signOut,
onDismiss = { confirmSignOut = false },
) {
// Sync, revoke the token, then delete the local copy (guide 6.10).
Expand All @@ -121,9 +130,9 @@ private fun Card(content: @Composable () -> Unit) {
}

@Composable
private fun Field(label: String, value: String) {
private fun Field(label: String, value: String, onClick: (() -> Unit)? = null) {
val c = Ivy.colors
Row(Modifier.fillMaxWidth().padding(vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) {
Row(Modifier.fillMaxWidth().then(if (onClick != null) Modifier.clickable(onClick = onClick) else Modifier).padding(vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) {
Text(label, color = c.ink2, fontSize = 15.sp, modifier = Modifier.width(88.dp))
Spacer(Modifier.width(4.dp))
Text(value, color = c.ink, fontSize = 15.sp, maxLines = 2, overflow = TextOverflow.Ellipsis)
Expand Down
39 changes: 21 additions & 18 deletions app/src/main/kotlin/app/ivynote/android/ui/Common.kt
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import app.ivynote.android.R
import app.ivynote.core.L10n
import app.ivynote.core.LibraryRef
import app.ivynote.core.SyncEngine
import app.ivynote.core.SyncState
Expand All @@ -66,8 +67,8 @@ import kotlinx.coroutines.delay
fun TextInputDialog(
title: String,
initial: String = "",
placeholder: String = "名称",
confirm: String = "保存",
placeholder: String = L10n.s.name,
confirm: String = L10n.s.save,
message: String? = null,
onDismiss: () -> Unit,
onConfirm: (String) -> Unit,
Expand All @@ -92,7 +93,7 @@ fun TextInputDialog(
}
},
confirmButton = { TextButton(onClick = { onConfirm(value.text); onDismiss() }) { Text(confirm) } },
dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } },
dismissButton = { TextButton(onClick = onDismiss) { Text(LocalStrings.current.cancel) } },
)
LaunchedEffect(Unit) {
delay(100)
Expand All @@ -118,7 +119,7 @@ fun ConfirmDialog(
Text(confirm, color = if (destructive) Ivy.colors.danger else Ivy.colors.ivy)
}
},
dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } },
dismissButton = { TextButton(onClick = onDismiss) { Text(LocalStrings.current.cancel) } },
)
}

Expand Down Expand Up @@ -181,17 +182,18 @@ fun SyncStatusLine(engine: SyncEngine, state: SyncState, modifier: Modifier = Mo
tick++
}
}
val s = LocalStrings.current
Column(modifier) {
Row(verticalAlignment = Alignment.CenterVertically) {
val (icon: ImageVector?, text: String, tint: Color) = when {
engine.isLocal -> Triple(Icons.Outlined.CloudOff, "仅保存在本机 · 未同步", c.muted)
state.status == SyncState.Status.SYNCING -> Triple(null, if (state.initial) "正在下载笔记…" else "同步中…", c.muted)
engine.isLocal -> Triple(Icons.Outlined.CloudOff, s.localUnsynced, c.muted)
state.status == SyncState.Status.SYNCING -> Triple(null, if (state.initial) s.downloadingNotes else s.syncing, c.muted)
state.status == SyncState.Status.OFFLINE ->
Triple(Icons.Outlined.WifiOff, if (state.pending > 0) "离线 · ${state.pending} 条待同步" else "离线", c.warn)
state.status == SyncState.Status.ERROR -> Triple(Icons.Outlined.Warning, "同步出错", c.danger)
state.pending > 0 -> Triple(Icons.Outlined.Sync, "${state.pending} 条待同步", c.muted)
state.lastSyncAt > 0 -> Triple(Icons.Outlined.CloudDone, "已同步 · ${relative(state.lastSyncAt, tick)}", c.muted)
else -> Triple(null, "尚未同步", c.muted)
Triple(Icons.Outlined.WifiOff, if (state.pending > 0) s.offlinePending(state.pending) else s.offline, c.warn)
state.status == SyncState.Status.ERROR -> Triple(Icons.Outlined.Warning, s.syncError, c.danger)
state.pending > 0 -> Triple(Icons.Outlined.Sync, s.pending(state.pending), c.muted)
state.lastSyncAt > 0 -> Triple(Icons.Outlined.CloudDone, s.synced(relative(state.lastSyncAt, tick)), c.muted)
else -> Triple(null, s.neverSynced, c.muted)
}
if (state.status == SyncState.Status.SYNCING && !engine.isLocal) {
CircularProgressIndicator(Modifier.size(11.dp), strokeWidth = 1.5.dp, color = c.muted)
Expand All @@ -203,31 +205,32 @@ fun SyncStatusLine(engine: SyncEngine, state: SyncState, modifier: Modifier = Mo
Text(text, fontSize = 12.5.sp, color = c.muted, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
if (state.blocked > 0) {
Text("${state.blocked} 条更改被服务器拒绝", fontSize = 12.5.sp, color = c.warn)
Text(s.blocked(state.blocked), fontSize = 12.5.sp, color = c.warn)
}
}
}

@Suppress("UNUSED_PARAMETER")
fun relative(at: Long, tick: Long = 0): String {
val now = System.currentTimeMillis()
if (now - at < 60_000) return "刚刚"
if (now - at < 60_000) return L10n.s.justNow
return DateUtils.getRelativeTimeSpanString(at, now, DateUtils.MINUTE_IN_MILLIS).toString()
}

/** 今天 16:20、昨天、周几、10月29日、2025年3月1日 (guide 11.7). */
/** 今天 16:20、昨天、周几、10月29日、2025年3月1日 (guide 11.7), in the interface language. */
fun shortDate(at: Long): String {
val s = L10n.s
val now = java.util.Calendar.getInstance()
val then = java.util.Calendar.getInstance().apply { timeInMillis = at }
val days = ((startOfDay(now) - startOfDay(then)) / 86_400_000L).toInt()
val time = String.format(java.util.Locale.ROOT, "%02d:%02d", then.get(java.util.Calendar.HOUR_OF_DAY), then.get(java.util.Calendar.MINUTE))
return when {
days <= 0 -> time
days == 1 -> "昨天 $time"
days < 7 -> arrayOf("周日", "周一", "周二", "周三", "周四", "周五", "周六")[then.get(java.util.Calendar.DAY_OF_WEEK) - 1]
days == 1 -> s.yesterday(time)
days < 7 -> s.weekday(then.get(java.util.Calendar.DAY_OF_WEEK))
then.get(java.util.Calendar.YEAR) == now.get(java.util.Calendar.YEAR) ->
"${then.get(java.util.Calendar.MONTH) + 1}月${then.get(java.util.Calendar.DAY_OF_MONTH)}日"
else -> "${then.get(java.util.Calendar.YEAR)}年${then.get(java.util.Calendar.MONTH) + 1}月${then.get(java.util.Calendar.DAY_OF_MONTH)}日"
s.monthDay(then.get(java.util.Calendar.MONTH) + 1, then.get(java.util.Calendar.DAY_OF_MONTH))
else -> s.yearMonthDay(then.get(java.util.Calendar.YEAR), then.get(java.util.Calendar.MONTH) + 1, then.get(java.util.Calendar.DAY_OF_MONTH))
}
}

Expand Down
Loading
Loading