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
2 changes: 1 addition & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ RegistrateLib is a maintained fork of Registrate for the `com.modularmc.registra
- 可执行的运行时检查 / Executable runtime checks

- `com.modularmc.registrate.test.meta`
- 用于生成的桥接方法和受保护 API 快照的维护工具 / Maintenance tooling for generated bridge methods and protected API snapshots
- 维护生成的桥接方法和受保护的 API 清单 / Maintains generated bridge methods and protected API listings

## 公开 API 边界 / Public API Boundary

Expand Down
41 changes: 40 additions & 1 deletion docs/localization.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,46 @@ var title = registrate.addLocalization(new TranslationKey(MOD_ID, "gui.mymod.vol

`addLocalization` 返回可用于 GUI 的翻译组件。进度标题等跨侧文本可在模组构造期间声明,在服务端 DataGen 的进度回调中引用组件。`addLang`、`addRawLang` 和 `ProviderType.LANG` 回调都使用同一个源 Locale。

在 `registrate.localizationCatalog()` 中登记 `Domain`、`GlossaryTerm` 和 `Unit`。Builder 的 `.profile(profile)` 可复用领域、文本类型和术语。条目的显式参数覆盖 Profile 的相应字段。
在 `registrate.terminology()` 中登记 `Domain`、`GlossaryTerm` 和 `MeasurementUnit`。Builder 的 `.defaults(defaults)` 可复用领域、文本类型和术语。条目的显式参数覆盖对应的默认值。

### 按语境选取术语

词表按声明所属的模组查询。完整源文本与词条匹配时,优先使用 `.glossaryIds("electric_potential")` 或 `.glossary(term)` 指定的术语。其余候选按 `Domain` 和 `TextType` 筛选,匹配程度相同的词条会报告声明位置与术语 ID。词表的首选译名可以补充缺少的译文。条目已有译文时,解析保留显式值,并提示禁用译名或词表未收录的写法。

通过 `registrate.terminology().register(glossary)` 接入项目自己的 `Glossary` 实现。接口通过 `find(id)` 查单条定义,通过 `findBySource(normalizedSource)` 返回完整标签的所有词义。源文本查询使用与 Locale 无关的小写形式。同一模组内的词条 ID 对应唯一的定义。

词条可登记缩写和别名、用 `TermRelation` 指定与其他词条的关系,以及关联已登记的单位 ID。单位通过 `MeasurementUnit.format(value, locale)` 格式化数值和符号。`UnitFormat` 配置 `DecimalFormat` 模式、小数分隔符和数值与符号之间的间距。

`DeclarationDefaults.Builder` 依次应用基础默认值、继承值和组合值,对应 `defaults`、`inherits` 和 `include`。同层的集合值可合并,冲突的文本类型或同 ID 词条会报错。声明可用 `.units("ohm")`、`.glossaryIds(...)` 等显式字段覆盖对应的默认值。

### 语言转换与回退

`registrate.deriveLocale(new LocaleDerivation(EN_US, EN_GB, converter))` 为模组注册转换规则。转换器处理未受保护的文本片段,可读取语言、Key 和声明。`LocaleDerivation.fallback(EN_GB, EN_AU)` 在缺少目标译文时使用已解析的输入语言。规则允许组成多步路径,循环会在 DataGen 收集时报告。已有译文优先于转换和回退。

转换会保留 Minecraft 参数、样式标记、URL、换行和已声明的单位符号。默认的 `en_us → en_ud` 同样遵循这些规则,并用显式索引保持倒置后的参数含义。

### 导入人工译文

在模组初始化时用 `importTranslation` 登记已读入的译文。提供译者审核时对应的源文本修订,以及可以定位到文件或平台条目的来源。

```java
import com.modularmc.registrate.localization.ImportedTranslation;
import com.modularmc.registrate.localization.MinecraftLocale;
import com.modularmc.registrate.localization.SourceRevision;
import com.modularmc.registrate.localization.TranslationKey;
import com.modularmc.registrate.localization.TranslationStatus;

registrate.importTranslation(new ImportedTranslation(
new TranslationKey(MOD_ID, "item.mymod.copper_ingot"),
MinecraftLocale.ZH_CN,
"铜锭",
SourceRevision.of("Copper Ingot"),
TranslationStatus.APPROVED,
false,
"translations/zh_cn.json"));
```

DataGen 用模组当前选中的源文本核对修订。源文本变化会将译文标为 `STALE`。锁定译文仍可参与选择,未锁定的过期译文仅用于诊断,此时配置的术语、转换和回退规则可以继续解析目标 Locale。开发者显式声明优先,其次是锁定的导入译文和当前修订的普通导入译文。同一层级中,已批准、审核中和草稿依次参与选择。

## 接入注解处理器

Expand Down
49 changes: 38 additions & 11 deletions src/main/java/com/modularmc/registrate/AbstractRegistrate.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,15 @@ import com.modularmc.registrate.internal.util.RegistrateLogger.core
import com.modularmc.registrate.internal.util.RegistrateLogger.datagen
import com.modularmc.registrate.internal.util.RegistrateLogger.modMessage
import com.modularmc.registrate.localization.EntryLocalization
import com.modularmc.registrate.localization.ImportedTranslation
import com.modularmc.registrate.localization.LocalizationDeclaration
import com.modularmc.registrate.localization.LocalizationDeclaration.Companion.sourceText
import com.modularmc.registrate.localization.MinecraftLocale
import com.modularmc.registrate.localization.TranslationKey
import com.modularmc.registrate.localization.TranslationSource
import com.modularmc.registrate.localization.locale.LocaleDerivation
import com.modularmc.registrate.localization.resolution.TranslationRegistry
import com.modularmc.registrate.localization.terminology.LocalizationCatalog
import com.modularmc.registrate.localization.terminology.Terminology
import com.modularmc.registrate.providers.RegistrateLangProvider.Companion.toEnglishName
import com.modularmc.registrate.providers.core.DataProviderInitializer
import com.modularmc.registrate.providers.core.GeneratorType
Expand Down Expand Up @@ -89,9 +91,11 @@ import net.neoforged.neoforge.registries.RegistryBuilder
import com.google.common.collect.ArrayListMultimap
import com.google.common.collect.HashBasedTable
import com.mojang.serialization.Codec
import it.unimi.dsi.fastutil.objects.ObjectArrayList
import org.apache.commons.lang3.tuple.Pair
import org.apache.logging.log4j.Level

import java.util.EnumMap
import java.util.Optional
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.function.BiConsumer
Expand Down Expand Up @@ -280,7 +284,7 @@ abstract class AbstractRegistrate<S : AbstractRegistrate<S>> protected construct

/**
* Allows retrieval of a previously created entry, of the current name (from the last invocation of
* [object]. Useful to retrieve a different entry than the final state of your
* [object]). Useful to retrieve a different entry than the final state of your
* chain may produce, e.g.
*
* ```java
Expand Down Expand Up @@ -551,8 +555,10 @@ abstract class AbstractRegistrate<S : AbstractRegistrate<S>> protected construct

private val extraLang = ArrayList<RawTranslation>()
private val generatedLang = ConcurrentLinkedQueue<RawTranslation>()
private val importedTranslations = ObjectArrayList<ImportedTranslation>()
private var sourceLocale: MinecraftLocale? = null
private val localizationCatalog = LocalizationCatalog()
private val terminology = Terminology()
private val localeDerivations = EnumMap<MinecraftLocale, LocaleDerivation>(MinecraftLocale::class.java)

/** Configures the source locale for this mod before data generation. */
open fun sourceLocale(locale: MinecraftLocale): S {
Expand All @@ -567,7 +573,28 @@ abstract class AbstractRegistrate<S : AbstractRegistrate<S>> protected construct
return locale
}

open fun localizationCatalog(): LocalizationCatalog = localizationCatalog
open fun terminology(): Terminology = terminology

/** Registers an imported target translation during mod setup for subsequent client DataGen runs. */
open fun importTranslation(translation: ImportedTranslation): S {
importedTranslations.add(translation)
return self()
}

internal fun collectImportedTranslations(registry: TranslationRegistry, locale: MinecraftLocale) {
val terminology = terminology()
for (translation in importedTranslations) registry.addImported(locale, translation, terminology)
}

/** Configures how DataGen fills a missing locale for this mod. The rule for a target can be replaced during setup. */
open fun deriveLocale(derivation: LocaleDerivation): S {
localeDerivations[derivation.output] = derivation
return self()
}

internal fun configureLocaleDerivations(registry: TranslationRegistry) {
if (localeDerivations.isNotEmpty()) registry.configureDerivations(terminology(), modid, localeDerivations.values)
}

open fun collectRawTranslations(registry: TranslationRegistry, locale: MinecraftLocale) {
for (translation in extraLang) {
Expand All @@ -581,7 +608,7 @@ abstract class AbstractRegistrate<S : AbstractRegistrate<S>> protected construct

private fun collectRawTranslation(registry: TranslationRegistry, locale: MinecraftLocale, translation: RawTranslation) {
if (translation.source.kind != TranslationSource.Kind.AUTOMATIC || locale == MinecraftLocale.EN_US) {
registry.add(translation.key, locale, translation.declaration, translation.source)
registry.add(translation.key, locale, translation.declaration, translation.source, terminology())
}
}

Expand Down Expand Up @@ -668,9 +695,9 @@ abstract class AbstractRegistrate<S : AbstractRegistrate<S>> protected construct
val key = TranslationKey(modid, localization.key.get())
val source = TranslationSource(
localization.kind,
"Builder ${entry.id} in ${entry.key!!.registry()}",
"Builder ${entry.id} in ${entry.key.registry()}",
)
registry.add(key, locale, localization.declaration.get(), source)
registry.add(key, locale, localization.declaration.get(), source, terminology())
}
}

Expand Down Expand Up @@ -944,7 +971,7 @@ abstract class AbstractRegistrate<S : AbstractRegistrate<S>> protected construct
addModListener(
this,
NewRegistryEvent::class.java,
Consumer { e: NewRegistryEvent -> e.register<R>(builder.apply(registryId).create()) },
Consumer { e: NewRegistryEvent -> e.register(builder.apply(registryId).create()) },
)
return registryId
}
Expand Down Expand Up @@ -988,7 +1015,7 @@ abstract class AbstractRegistrate<S : AbstractRegistrate<S>> protected construct
addModListener(
this,
NewRegistry::class.java,
Consumer { event: NewRegistry -> event.dataPackRegistry<R>(registryId, codec, networkCodec) },
Consumer { event: NewRegistry -> event.dataPackRegistry(registryId, codec, networkCodec) },
)
return registryId
}
Expand Down Expand Up @@ -1359,14 +1386,14 @@ abstract class AbstractRegistrate<S : AbstractRegistrate<S>> protected construct
Registries.CREATIVE_MODE_TAB,
Identifier.fromNamespaceAndPath(this.modid, name),
)
return this.generic<CreativeModeTab, CreativeModeTab, P>(
return this.generic(
parent,
name,
Registries.CREATIVE_MODE_TAB,
) {
val builder = CreativeModeTab.builder()
.icon {
getAll<Item, Item>(Registries.ITEM).firstOrNull()?.get()?.let(::ItemStack) ?: ItemStack.EMPTY
getAll(Registries.ITEM).firstOrNull()?.get()?.let(::ItemStack) ?: ItemStack.EMPTY
}
.title(
addRawLang(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.modularmc.registrate.localization

import com.modularmc.registrate.localization.terminology.Domain
import com.modularmc.registrate.localization.terminology.Terminology.GlossaryTerm

import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap
import it.unimi.dsi.fastutil.objects.ObjectArrayList
import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet

/** Reusable domain, text type and glossary defaults for a localization declaration. */
@JvmRecord
data class DeclarationDefaults @JvmOverloads constructor(
val domains: List<Domain>,
val type: TextType?,
val glossary: List<GlossaryTerm>,
val glossaryIds: List<String> = emptyList(),
val unitIds: List<String> = emptyList(),
) {
/** Combines existing defaults so that included values take precedence over inherited defaults. */
class Builder {
private var defaults = EMPTY
private var parent = EMPTY
private val included = ObjectArrayList<DeclarationDefaults>()

fun defaults(defaults: DeclarationDefaults) = apply { this.defaults = defaults }

fun inherits(parent: DeclarationDefaults) = apply { this.parent = parent }

fun include(vararg defaults: DeclarationDefaults) = apply { included.addAll(defaults.asList()) }

fun build(): DeclarationDefaults {
val domains = ObjectLinkedOpenHashSet<Domain>()
val glossary = Object2ObjectLinkedOpenHashMap<String, GlossaryTerm>()
val glossaryIds = ObjectLinkedOpenHashSet<String>()
val units = ObjectLinkedOpenHashSet<String>()
var type: TextType? = null
for (defaults in included) {
domains.addAll(defaults.domains)
glossaryIds.addAll(defaults.glossaryIds)
units.addAll(defaults.unitIds)
for (term in defaults.glossary) {
val existing = glossary.putIfAbsent(term.id, term)
require(existing == null || existing == term) { "Included defaults disagree on glossary term '${term.id}'" }
}
defaults.type?.let { candidate ->
require(type == null || type == candidate) { "Included defaults disagree on text type: $type and $candidate" }
type = candidate
}
}
val glossaryParent = if (parent.glossary.isEmpty() && parent.glossaryIds.isEmpty()) defaults else parent
val useIncludedGlossary = glossary.isNotEmpty() || glossaryIds.isNotEmpty()
return DeclarationDefaults(
if (domains.isEmpty()) parent.domains.ifEmpty { defaults.domains } else ObjectArrayList(domains),
type ?: parent.type ?: defaults.type,
if (useIncludedGlossary) ObjectArrayList(glossary.values) else glossaryParent.glossary,
if (useIncludedGlossary) ObjectArrayList(glossaryIds) else glossaryParent.glossaryIds,
if (units.isEmpty()) parent.unitIds.ifEmpty { defaults.unitIds } else ObjectArrayList(units),
)
}
}

companion object {
internal val EMPTY = DeclarationDefaults(emptyList(), null, emptyList())
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.modularmc.registrate.localization

import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.util.HexFormat

/** Identifies the source text against which a translation was reviewed. */
@JvmRecord
data class SourceRevision(val value: String) {
companion object {
private val digest = ThreadLocal.withInitial { MessageDigest.getInstance("SHA-256") }
private val hex = HexFormat.of()

/** Computes the SHA-256 of the UTF-8 source text. */
@JvmStatic
fun of(source: String): SourceRevision = SourceRevision(hex.formatHex(digest.get().digest(source.toByteArray(StandardCharsets.UTF_8))))
}
}

/** Review state attached to a translation imported from another source. */
enum class TranslationStatus(private val priority: Int) {
STALE(0),
DRAFT(1),
IN_REVIEW(2),
APPROVED(3),
;

internal fun priority(locked: Boolean): Int = priority + if (locked) entries.size else 0
}

/** A translation received from another source. [location] identifies its origin in DataGen diagnostics. */
@JvmRecord
data class ImportedTranslation(
val key: TranslationKey,
val locale: MinecraftLocale,
val text: String,
val sourceRevision: SourceRevision,
val status: TranslationStatus,
val locked: Boolean,
val location: String,
) {
internal fun forRevision(revision: SourceRevision): ImportedTranslation = if (sourceRevision == revision || status == TranslationStatus.STALE) this else copy(status = TranslationStatus.STALE)
}
Original file line number Diff line number Diff line change
@@ -1,26 +1,36 @@
package com.modularmc.registrate.localization

import com.modularmc.registrate.localization.terminology.Domain
import com.modularmc.registrate.localization.terminology.LocalizationCatalog.GlossaryTerm
import com.modularmc.registrate.localization.terminology.Terminology.GlossaryTerm

import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap

/** A source declaration and its explicit translations, resolved against the owning mod's source locale. */
@JvmRecord
data class LocalizationDeclaration(val source: String, val translations: Map<MinecraftLocale, String>, val domains: List<Domain>, val type: TextType?, val glossary: List<GlossaryTerm>) {
data class LocalizationDeclaration @JvmOverloads constructor(
val source: String,
val translations: Map<MinecraftLocale, String>,
val domains: List<Domain>,
val type: TextType?,
val glossary: List<GlossaryTerm>,
val glossaryIds: List<String> = emptyList(),
val unitIds: List<String> = emptyList(),
) {
class Builder {
private lateinit var source: String
private var translations: Object2ObjectOpenHashMap<MinecraftLocale, String>? = null
private var domains: List<Domain>? = null
private var type: TextType? = null
private var glossary: List<GlossaryTerm>? = null
private var profile = LocalizationProfile.EMPTY
private var glossaryIds: List<String>? = null
private var unitIds: List<String>? = null
private var defaults = DeclarationDefaults.EMPTY

fun source(source: String) = apply { this.source = source }

fun type(type: TextType?) = apply { this.type = type }

fun profile(profile: LocalizationProfile) = apply { this.profile = profile }
fun defaults(defaults: DeclarationDefaults) = apply { this.defaults = defaults }

fun translation(locale: MinecraftLocale, text: String) = apply {
val texts = translations ?: Object2ObjectOpenHashMap<MinecraftLocale, String>(2).also { translations = it }
Expand All @@ -29,14 +39,26 @@ data class LocalizationDeclaration(val source: String, val translations: Map<Min

fun domain(vararg domains: Domain) = apply { this.domains = domains.toList() }

fun glossary(vararg terms: GlossaryTerm) = apply { glossary = terms.toList() }
fun glossary(vararg terms: GlossaryTerm) = apply {
glossary = terms.asList()
glossaryIds = emptyList()
}

fun glossaryIds(vararg ids: String) = apply {
glossary = emptyList()
glossaryIds = ids.asList()
}

fun units(vararg ids: String) = apply { unitIds = ids.asList() }

fun build() = LocalizationDeclaration(
source,
translations?.toMap() ?: emptyMap(),
domains ?: profile.domains,
type ?: profile.type,
glossary ?: profile.glossary,
domains ?: defaults.domains,
type ?: defaults.type,
glossary ?: defaults.glossary,
glossaryIds ?: defaults.glossaryIds,
unitIds ?: defaults.unitIds,
)
}

Expand Down

This file was deleted.

Loading
Loading