replace Enum.values() to Enum.entries

This commit is contained in:
tateisu 2024-01-04 14:41:40 +09:00
parent 18f9aa1c15
commit 9cf5a36ff4
18 changed files with 161 additions and 98 deletions

View File

@ -175,7 +175,7 @@ class ActAppSetting : AppCompatActivity(), ColorPickerDialogListener, View.OnCli
if (savedInstanceState != null) { if (savedInstanceState != null) {
try { try {
savedInstanceState.getString(STATE_CHOOSE_INTENT_TARGET)?.let { target -> savedInstanceState.getString(STATE_CHOOSE_INTENT_TARGET)?.let { target ->
customShareTarget = CustomShareTarget.values().firstOrNull { it.name == target } customShareTarget = CustomShareTarget.entries.find { it.name == target }
} }
} catch (ex: Throwable) { } catch (ex: Throwable) {
log.e(ex, "can't restore customShareTarget.") log.e(ex, "can't restore customShareTarget.")

View File

@ -20,8 +20,24 @@ import android.widget.ListView
import android.widget.TextView import android.widget.TextView
import androidx.core.view.GravityCompat import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout import androidx.drawerlayout.widget.DrawerLayout
import jp.juggler.subwaytooter.* import jp.juggler.subwaytooter.ActAbout
import jp.juggler.subwaytooter.action.* import jp.juggler.subwaytooter.ActAppSetting
import jp.juggler.subwaytooter.ActFavMute
import jp.juggler.subwaytooter.ActHighlightWordList
import jp.juggler.subwaytooter.ActMain
import jp.juggler.subwaytooter.ActMutedApp
import jp.juggler.subwaytooter.ActMutedPseudoAccount
import jp.juggler.subwaytooter.ActMutedWord
import jp.juggler.subwaytooter.ActOSSLicense
import jp.juggler.subwaytooter.ActPushMessageList
import jp.juggler.subwaytooter.App1
import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.action.accountAdd
import jp.juggler.subwaytooter.action.accountOpenSetting
import jp.juggler.subwaytooter.action.openColumnFromUrl
import jp.juggler.subwaytooter.action.openColumnList
import jp.juggler.subwaytooter.action.serverProfileDirectoryFromSideMenu
import jp.juggler.subwaytooter.action.timeline
import jp.juggler.subwaytooter.api.entity.TootStatus import jp.juggler.subwaytooter.api.entity.TootStatus
import jp.juggler.subwaytooter.column.ColumnType import jp.juggler.subwaytooter.column.ColumnType
import jp.juggler.subwaytooter.dialog.pickAccount import jp.juggler.subwaytooter.dialog.pickAccount
@ -50,7 +66,7 @@ import jp.juggler.util.ui.createColoredDrawable
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import org.jetbrains.anko.backgroundColor import org.jetbrains.anko.backgroundColor
import java.lang.ref.WeakReference import java.lang.ref.WeakReference
import java.util.* import java.util.TimeZone
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import kotlin.math.abs import kotlin.math.abs
@ -71,7 +87,7 @@ class SideMenuAdapter(
private const val urlOlderDevices = private const val urlOlderDevices =
"https://github.com/tateisu/SubwayTooter/discussions/192" "https://github.com/tateisu/SubwayTooter/discussions/192"
private val itemTypeCount = ItemType.values().size private val itemTypeCount = ItemType.entries.size
private var lastVersionView: WeakReference<TextView>? = null private var lastVersionView: WeakReference<TextView>? = null
@ -487,10 +503,12 @@ class SideMenuAdapter(
when (itemType) { when (itemType) {
ItemType.IT_DIVIDER -> ItemType.IT_DIVIDER ->
viewOrInflate(view, parent, R.layout.lv_sidemenu_separator) viewOrInflate(view, parent, R.layout.lv_sidemenu_separator)
ItemType.IT_GROUP_HEADER -> ItemType.IT_GROUP_HEADER ->
viewOrInflate<TextView>(view, parent, R.layout.lv_sidemenu_group).apply { viewOrInflate<TextView>(view, parent, R.layout.lv_sidemenu_group).apply {
text = actMain.getString(title) text = actMain.getString(title)
} }
ItemType.IT_NORMAL -> ItemType.IT_NORMAL ->
viewOrInflate<TextView>(view, parent, R.layout.lv_sidemenu_item).apply { viewOrInflate<TextView>(view, parent, R.layout.lv_sidemenu_item).apply {
isAllCaps = false isAllCaps = false
@ -522,6 +540,7 @@ class SideMenuAdapter(
background = null background = null
text = versionText text = versionText
} }
ItemType.IT_TIMEZONE -> ItemType.IT_TIMEZONE ->
viewOrInflate<TextView>(view, parent, R.layout.lv_sidemenu_item).apply { viewOrInflate<TextView>(view, parent, R.layout.lv_sidemenu_item).apply {
textSize = 14f textSize = 14f
@ -529,6 +548,7 @@ class SideMenuAdapter(
background = null background = null
text = getTimeZoneString(context) text = getTimeZoneString(context)
} }
ItemType.IT_NOTIFICATION_PERMISSION -> ItemType.IT_NOTIFICATION_PERMISSION ->
viewOrInflate<TextView>(view, parent, R.layout.lv_sidemenu_item).apply { viewOrInflate<TextView>(view, parent, R.layout.lv_sidemenu_item).apply {
isAllCaps = false isAllCaps = false
@ -599,6 +619,7 @@ class SideMenuAdapter(
Pair(R.string.notification_push_distributor_disabled) { Pair(R.string.notification_push_distributor_disabled) {
actMain.selectPushDistributor() actMain.selectPushDistributor()
} }
else -> null else -> null
} }
@ -616,6 +637,7 @@ class SideMenuAdapter(
else -> true else -> true
} }
else -> true else -> true
} }
} }

View File

@ -98,7 +98,7 @@ class TootAttachment private constructor(
private val ext_audio = arrayOf(".mpga", ".mp3", ".aac", ".ogg") private val ext_audio = arrayOf(".mpga", ".mp3", ".aac", ".ogg")
private fun parseType(src: String?) = private fun parseType(src: String?) =
TootAttachmentType.values().find { it.id == src } TootAttachmentType.entries.find { it.id == src }
private fun guessMediaTypeByUrl(src: String?): TootAttachmentType? { private fun guessMediaTypeByUrl(src: String?): TootAttachmentType? {
val uri = src.mayUri() ?: return null val uri = src.mayUri() ?: return null

View File

@ -23,13 +23,12 @@ enum class TootFilterContext(
companion object { companion object {
private val log = LogCategory("TootFilterContext") private val log = LogCategory("TootFilterContext")
private val valuesCache = values() private val apiNameMap = entries.associateBy { it.apiName }
private val apiNameMap = valuesCache.associateBy { it.apiName }
fun parseBits(src: JsonArray?): Int = fun parseBits(src: JsonArray?): Int =
src?.stringList()?.mapNotNull { apiNameMap[it]?.bit }?.sum() ?: 0 src?.stringList()?.mapNotNull { apiNameMap[it]?.bit }?.sum() ?: 0
fun bitsToNames(mask: Int) = fun bitsToNames(mask: Int) =
valuesCache.filter { it.bit.and(mask) != 0 }.map { it.caption_id } entries.filter { it.bit.and(mask) != 0 }.map { it.caption_id }
} }
} }

View File

@ -68,6 +68,7 @@ enum class TootVisibility(
LocalPublic, LocalHome -> true LocalPublic, LocalHome -> true
else -> false else -> false
} }
else -> when (this) { else -> when (this) {
Public, UnlistedHome -> true Public, UnlistedHome -> true
else -> false else -> false
@ -109,47 +110,35 @@ enum class TootVisibility(
companion object { companion object {
private val log = LogCategory("TootVisivbility") private val log = LogCategory("TootVisivbility")
fun parseMastodon(a: String?): TootVisibility? { fun parseMastodon(a: String?) =
for (v in values()) { entries.find { it.strMastodon == a }
if (v.strMastodon == a) return v
}
return null
}
fun parseMisskey(a: String?, localOnly: Boolean = false): TootVisibility? { fun parseMisskey(a: String?, localOnly: Boolean = false): TootVisibility? {
for (v in values()) { entries.find { it.strMisskey == a }?.let { v ->
if (v.strMisskey == a) { if (localOnly) {
if (localOnly) { when (v) {
when (v) { Public -> return LocalPublic
Public -> return LocalPublic UnlistedHome -> return LocalHome
UnlistedHome -> return LocalHome PrivateFollowers -> return LocalFollowers
PrivateFollowers -> return LocalFollowers
else -> { else -> Unit
}
}
} }
return v
} }
return v
} }
return null return null
} }
fun fromId(id: Int): TootVisibility? { fun fromId(id: Int) = entries.find { it.id == id }
for (v in values()) {
if (v.id == id) return v
}
return null
}
fun parseSavedVisibility(sv: String?): TootVisibility? { fun parseSavedVisibility(sv: String?): TootVisibility? {
sv ?: return null sv ?: return null
// 新しい方式ではenumのidの文字列表現 // 新しい方式ではenumのidの文字列表現
values().find { it.id.toString() == sv }?.let { return it } entries.find { it.id.toString() == sv }?.let { return it }
// 古い方式ではマストドンの公開範囲文字列かweb_setting // 古い方式ではマストドンの公開範囲文字列かweb_setting
values().find { it.strMastodon == sv }?.let { return it } entries.find { it.strMastodon == sv }?.let { return it }
return null return null
} }

View File

@ -70,7 +70,7 @@ enum class SettingType(val id: Int) {
; ;
companion object { companion object {
val map = values().associateBy { it.id } val map = entries.associateBy { it.id }
} }
} }
@ -367,7 +367,7 @@ val appSettingRoot = AppSettingItem(null, SettingType.Section, R.string.app_sett
spinnerSimple( spinnerSimple(
PrefI.ipAdditionalButtonsPosition, PrefI.ipAdditionalButtonsPosition,
R.string.additional_buttons_position, R.string.additional_buttons_position,
*(AdditionalButtonsPosition.values().sortedBy { it.idx }.map { it.captionId } *(AdditionalButtonsPosition.entries.sortedBy { it.idx }.map { it.captionId }
.toIntArray()) .toIntArray())
) )
@ -380,7 +380,7 @@ val appSettingRoot = AppSettingItem(null, SettingType.Section, R.string.app_sett
} }
section(R.string.translate_or_custom_share) { section(R.string.translate_or_custom_share) {
CustomShareTarget.values().forEach { target -> for (target in CustomShareTarget.entries) {
item( item(
SettingType.TextWithSelector, SettingType.TextWithSelector,
target.pref, target.pref,
@ -498,7 +498,7 @@ val appSettingRoot = AppSettingItem(null, SettingType.Section, R.string.app_sett
sw(PrefB.bpUseInternalMediaViewer, R.string.use_internal_media_viewer) sw(PrefB.bpUseInternalMediaViewer, R.string.use_internal_media_viewer)
spinner(PrefI.ipMediaBackground, R.string.background_pattern) { spinner(PrefI.ipMediaBackground, R.string.background_pattern) {
MediaBackgroundDrawable.Kind.values() MediaBackgroundDrawable.Kind.entries
.filter { it.isMediaBackground } .filter { it.isMediaBackground }
.map { it.name } .map { it.name }
} }

View File

@ -326,7 +326,7 @@ object ColumnEncoder {
-> { -> {
profileId = EntityId.mayNull(src.string(KEY_PROFILE_ID)) profileId = EntityId.mayNull(src.string(KEY_PROFILE_ID))
val tabId = src.optInt(KEY_PROFILE_TAB) val tabId = src.optInt(KEY_PROFILE_TAB)
profileTab = ProfileTab.values().find { it.id == tabId } ?: ProfileTab.Status profileTab = ProfileTab.entries.find { it.id == tabId } ?: ProfileTab.Status
} }
ColumnType.LIST_MEMBER, ColumnType.LIST_MEMBER,

View File

@ -6,9 +6,22 @@ import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.api.ApiPath import jp.juggler.subwaytooter.api.ApiPath
import jp.juggler.subwaytooter.api.TootApiClient import jp.juggler.subwaytooter.api.TootApiClient
import jp.juggler.subwaytooter.api.TootApiResult import jp.juggler.subwaytooter.api.TootApiResult
import jp.juggler.subwaytooter.api.entity.* import jp.juggler.subwaytooter.api.entity.Acct
import jp.juggler.subwaytooter.api.entity.Host
import jp.juggler.subwaytooter.api.entity.TimelineItem
import jp.juggler.subwaytooter.api.entity.TootAccountRef.Companion.tootAccountRef import jp.juggler.subwaytooter.api.entity.TootAccountRef.Companion.tootAccountRef
import jp.juggler.subwaytooter.api.finder.* import jp.juggler.subwaytooter.api.entity.TootInstance
import jp.juggler.subwaytooter.api.entity.TootMessageHolder
import jp.juggler.subwaytooter.api.entity.TootNotification
import jp.juggler.subwaytooter.api.entity.TootStatus
import jp.juggler.subwaytooter.api.finder.mastodonFollowSuggestion2ListParser
import jp.juggler.subwaytooter.api.finder.misskey11FollowersParser
import jp.juggler.subwaytooter.api.finder.misskey11FollowingParser
import jp.juggler.subwaytooter.api.finder.misskeyArrayFinderUsers
import jp.juggler.subwaytooter.api.finder.misskeyCustomParserBlocks
import jp.juggler.subwaytooter.api.finder.misskeyCustomParserFavorites
import jp.juggler.subwaytooter.api.finder.misskeyCustomParserFollowRequest
import jp.juggler.subwaytooter.api.finder.misskeyCustomParserMutes
import jp.juggler.subwaytooter.search.MspHelper.loadingMSP import jp.juggler.subwaytooter.search.MspHelper.loadingMSP
import jp.juggler.subwaytooter.search.MspHelper.refreshMSP import jp.juggler.subwaytooter.search.MspHelper.refreshMSP
import jp.juggler.subwaytooter.search.NotestockHelper.loadingNotestock import jp.juggler.subwaytooter.search.NotestockHelper.loadingNotestock
@ -17,10 +30,16 @@ import jp.juggler.subwaytooter.search.TootsearchHelper.loadingTootsearch
import jp.juggler.subwaytooter.search.TootsearchHelper.refreshTootsearch import jp.juggler.subwaytooter.search.TootsearchHelper.refreshTootsearch
import jp.juggler.subwaytooter.streaming.StreamSpec import jp.juggler.subwaytooter.streaming.StreamSpec
import jp.juggler.subwaytooter.table.daoAcctColor import jp.juggler.subwaytooter.table.daoAcctColor
import jp.juggler.util.* import jp.juggler.util.data.JsonArray
import jp.juggler.util.data.* import jp.juggler.util.data.JsonObject
import jp.juggler.util.data.appendIf
import jp.juggler.util.data.ellipsizeDot3
import jp.juggler.util.data.jsonArrayOf
import jp.juggler.util.data.jsonObjectOf
import jp.juggler.util.data.notEmpty
import jp.juggler.util.data.toJsonArray
import jp.juggler.util.log.LogCategory import jp.juggler.util.log.LogCategory
import java.util.* import java.util.Locale
import kotlin.math.max import kotlin.math.max
import kotlin.math.min import kotlin.math.min
@ -1128,6 +1147,7 @@ enum class ColumnType(
arrayFinder = misskeyArrayFinderUsers, arrayFinder = misskeyArrayFinderUsers,
listParser = misskeyCustomParserMutes listParser = misskeyCustomParserMutes
) )
else -> getAccountList(client, ApiPath.PATH_MUTES) else -> getAccountList(client, ApiPath.PATH_MUTES)
} }
}, },
@ -1142,6 +1162,7 @@ enum class ColumnType(
arrayFinder = misskeyArrayFinderUsers, arrayFinder = misskeyArrayFinderUsers,
listParser = misskeyCustomParserMutes listParser = misskeyCustomParserMutes
) )
else -> getAccountList( else -> getAccountList(
client, client,
ApiPath.PATH_MUTES, ApiPath.PATH_MUTES,
@ -1750,6 +1771,7 @@ enum class ColumnType(
ApiPath.PATH_FOLLOW_SUGGESTION2, ApiPath.PATH_FOLLOW_SUGGESTION2,
listParser = mastodonFollowSuggestion2ListParser, listParser = mastodonFollowSuggestion2ListParser,
) )
else -> else ->
getAccountList(client, ApiPath.PATH_FOLLOW_SUGGESTION) getAccountList(client, ApiPath.PATH_FOLLOW_SUGGESTION)
} }
@ -1773,6 +1795,7 @@ enum class ColumnType(
ApiPath.PATH_FOLLOW_SUGGESTION2, ApiPath.PATH_FOLLOW_SUGGESTION2,
listParser = mastodonFollowSuggestion2ListParser, listParser = mastodonFollowSuggestion2ListParser,
) )
else -> else ->
getAccountList(client, ApiPath.PATH_FOLLOW_SUGGESTION) getAccountList(client, ApiPath.PATH_FOLLOW_SUGGESTION)
} }
@ -1798,6 +1821,7 @@ enum class ColumnType(
listParser = mastodonFollowSuggestion2ListParser, listParser = mastodonFollowSuggestion2ListParser,
mastodonFilterByIdRange = false mastodonFilterByIdRange = false
) )
else -> else ->
getAccountList( getAccountList(
client, client,
@ -2088,7 +2112,7 @@ enum class ColumnType(
fun dump() { fun dump() {
var min = Int.MAX_VALUE var min = Int.MAX_VALUE
var max = Int.MIN_VALUE var max = Int.MIN_VALUE
values().forEach { for (it in entries) {
val id = it.id val id = it.id
min = min(min, id) min = min(min, id)
max = max(max, id) max = max(max, id)

View File

@ -3,7 +3,9 @@ package jp.juggler.subwaytooter.dialog
import android.app.Dialog import android.app.Dialog
import android.view.WindowManager import android.view.WindowManager
import android.view.inputmethod.EditorInfo import android.view.inputmethod.EditorInfo
import android.widget.* import android.widget.ArrayAdapter
import android.widget.Filter
import android.widget.TextView
import androidx.annotation.StringRes import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.addTextChangedListener import androidx.core.widget.addTextChangedListener
@ -21,15 +23,23 @@ import jp.juggler.util.coroutine.launchAndShowError
import jp.juggler.util.coroutine.launchMain import jp.juggler.util.coroutine.launchMain
import jp.juggler.util.data.notBlank import jp.juggler.util.data.notBlank
import jp.juggler.util.data.notEmpty import jp.juggler.util.data.notEmpty
import jp.juggler.util.log.* import jp.juggler.util.log.LogCategory
import jp.juggler.util.ui.* import jp.juggler.util.log.showToast
import jp.juggler.util.ui.ProgressDialogEx
import jp.juggler.util.ui.attrColor
import jp.juggler.util.ui.dismissSafe
import jp.juggler.util.ui.hideKeyboard
import jp.juggler.util.ui.invisible
import jp.juggler.util.ui.isEnabledAlpha
import jp.juggler.util.ui.vg
import jp.juggler.util.ui.visible
import jp.juggler.util.ui.visibleOrInvisible
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import org.jetbrains.anko.textColor import org.jetbrains.anko.textColor
import org.jetbrains.anko.textResource import org.jetbrains.anko.textResource
import java.io.BufferedReader import java.io.BufferedReader
import java.io.InputStreamReader import java.io.InputStreamReader
import java.net.IDN import java.net.IDN
import java.util.*
class LoginForm( class LoginForm(
val activity: AppCompatActivity, val activity: AppCompatActivity,
@ -62,7 +72,8 @@ class LoginForm(
) { ) {
Login(R.string.existing_account, R.string.existing_account_desc), Login(R.string.existing_account, R.string.existing_account_desc),
Pseudo(R.string.pseudo_account, R.string.pseudo_account_desc), Pseudo(R.string.pseudo_account, R.string.pseudo_account_desc),
// Create(2, R.string.create_account, R.string.create_account_desc),
// Create(2, R.string.create_account, R.string.create_account_desc),
Token(R.string.input_access_token, R.string.input_access_token_desc), Token(R.string.input_access_token, R.string.input_access_token_desc),
} }
@ -76,7 +87,7 @@ class LoginForm(
private var targetServerInfo: TootInstance? = null private var targetServerInfo: TootInstance? = null
init { init {
for (a in Action.values()) { for (a in Action.entries) {
val subViews = val subViews =
LvAuthTypeBinding.inflate(activity.layoutInflater, views.llPageAuthType, true) LvAuthTypeBinding.inflate(activity.layoutInflater, views.llPageAuthType, true)
subViews.btnAuthType.textResource = a.idName subViews.btnAuthType.textResource = a.idName

View File

@ -1,10 +1,15 @@
package jp.juggler.subwaytooter.drawable package jp.juggler.subwaytooter.drawable
import android.content.Context import android.content.Context
import android.graphics.* import android.graphics.Canvas
import android.graphics.Color
import android.graphics.ColorFilter
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.Rect
import android.graphics.drawable.Drawable import android.graphics.drawable.Drawable
import jp.juggler.subwaytooter.R import jp.juggler.subwaytooter.R
import jp.juggler.util.ui.* import jp.juggler.util.ui.attrColor
import kotlin.math.min import kotlin.math.min
class MediaBackgroundDrawable( class MediaBackgroundDrawable(
@ -33,10 +38,10 @@ class MediaBackgroundDrawable(
; ;
fun toIndex() = values().indexOf(this) fun toIndex() = entries.indexOf(this)
companion object { companion object {
fun fromIndex(idx: Int) = values().elementAtOrNull(idx) ?: BlackTile fun fromIndex(idx: Int) = entries.elementAtOrNull(idx) ?: BlackTile
} }
} }

View File

@ -20,9 +20,7 @@ class EmojiMapLoader(
private val assetsSet = appContext.assets.list("")!!.toSet() private val assetsSet = appContext.assets.list("")!!.toSet()
private val resources = appContext.resources!! private val resources = appContext.resources!!
private val categoryNameMap = HashMap<String, EmojiCategory>().apply { private val categoryNameMap = EmojiCategory.entries.associateBy { it.name }
EmojiCategory.values().forEach { put(it.name, it) }
}
private var lastEmoji: UnicodeEmoji? = null private var lastEmoji: UnicodeEmoji? = null
private var lastCategory: EmojiCategory? = null private var lastCategory: EmojiCategory? = null
@ -60,28 +58,34 @@ class EmojiMapLoader(
if (!assetsSet.contains(line)) error("missing assets.") if (!assetsSet.contains(line)) error("missing assets.")
lastEmoji = UnicodeEmoji(assetsName = line) lastEmoji = UnicodeEmoji(assetsName = line)
} }
"drawable" -> { "drawable" -> {
val drawableId = getDrawableId(line) ?: error("missing drawable.") val drawableId = getDrawableId(line) ?: error("missing drawable.")
lastEmoji = UnicodeEmoji(drawableId = drawableId) lastEmoji = UnicodeEmoji(drawableId = drawableId)
} }
"un" -> { "un" -> {
val emoji = lastEmoji ?: error("missing lastEmoji.") val emoji = lastEmoji ?: error("missing lastEmoji.")
addCode(emoji, line) addCode(emoji, line)
emoji.unifiedCode = line emoji.unifiedCode = line
} }
"u" -> { "u" -> {
val emoji = lastEmoji ?: error("missing lastEmoji.") val emoji = lastEmoji ?: error("missing lastEmoji.")
addCode(emoji, line) addCode(emoji, line)
} }
"sn" -> { "sn" -> {
val emoji = lastEmoji ?: error("missing lastEmoji.") val emoji = lastEmoji ?: error("missing lastEmoji.")
addName(emoji, line) addName(emoji, line)
emoji.unifiedName = line emoji.unifiedName = line
} }
"s" -> { "s" -> {
val emoji = lastEmoji ?: error("missing lastEmoji.") val emoji = lastEmoji ?: error("missing lastEmoji.")
addName(emoji, line) addName(emoji, line)
} }
"t" -> { "t" -> {
val cols = line.split(",", limit = 3) val cols = line.split(",", limit = 3)
if (cols.size != 3) error("invalid tone spec. line=$lno $line") if (cols.size != 3) error("invalid tone spec. line=$lno $line")
@ -99,6 +103,7 @@ class EmojiMapLoader(
lastCategory = categoryNameMap[line] lastCategory = categoryNameMap[line]
?: error("missing category name.") ?: error("missing category name.")
} }
"c" -> { "c" -> {
val category = lastCategory val category = lastCategory
?: error("missing lastCategory.") ?: error("missing lastCategory.")
@ -110,6 +115,7 @@ class EmojiMapLoader(
category.emojiList.add(emoji) category.emojiList.add(emoji)
} }
} }
else -> error("unknown header $head") else -> error("unknown header $head")
} }
} catch (ex: Throwable) { } catch (ex: Throwable) {

View File

@ -76,7 +76,7 @@ enum class AdditionalButtonsPosition(
; ;
companion object { companion object {
fun fromIndex(i: Int) = values().find { it.idx == i } ?: Top fun fromIndex(i: Int) = entries.find { it.idx == i } ?: Top
} }
} }
@ -821,7 +821,7 @@ class StatusButtonsViewHolder(
} }
private fun AnkoFlexboxLayout.additionalButtons() { private fun AnkoFlexboxLayout.additionalButtons() {
btnCustomShares = CustomShareTarget.values().map { target -> btnCustomShares = CustomShareTarget.entries.map { target ->
imageButton { imageButton {
background = ContextCompat.getDrawable( background = ContextCompat.getDrawable(
context, context,

View File

@ -256,10 +256,9 @@ class NotificationChannelsInitializer : Initializer<Boolean> {
override fun create(context: Context): Boolean { override fun create(context: Context): Boolean {
context.run { context.run {
val list = NotificationChannels.values()
log.i("createNotificationChannel(s) size=${list.size}")
val notificationManager = NotificationManagerCompat.from(this) val notificationManager = NotificationManagerCompat.from(this)
for (nc in list) { log.i("createNotificationChannel(s) size=${NotificationChannels.entries.size}")
for (nc in NotificationChannels.entries) {
val channel = NotificationChannel( val channel = NotificationChannel(
nc.id, nc.id,
getString(nc.titleId), getString(nc.titleId),

View File

@ -11,8 +11,4 @@ enum class PollingState(val desc: String) {
CheckPushSubscription("check push subscription"), CheckPushSubscription("check push subscription"),
CheckNotifications("check notifications"), CheckNotifications("check notifications"),
; ;
companion object {
val valuesCache = values()
}
} }

View File

@ -4,7 +4,17 @@ import android.app.ActivityManager
import android.app.PendingIntent import android.app.PendingIntent
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import androidx.work.* import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.Data
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.ForegroundInfo
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequest
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import androidx.work.await
import jp.juggler.subwaytooter.ActMain import jp.juggler.subwaytooter.ActMain
import jp.juggler.subwaytooter.App1 import jp.juggler.subwaytooter.App1
import jp.juggler.subwaytooter.R import jp.juggler.subwaytooter.R
@ -114,7 +124,7 @@ class PollingWorker2(
private fun stateMapToString(map: Map<PollingState, List<String>>) = private fun stateMapToString(map: Map<PollingState, List<String>>) =
StringBuilder().apply { StringBuilder().apply {
for (state in PollingState.valuesCache) { for (state in PollingState.entries) {
val list = map[state] ?: continue val list = map[state] ?: continue
if (isNotEmpty()) append(" |") if (isNotEmpty()) append(" |")
append(state.desc) append(state.desc)

View File

@ -9,7 +9,6 @@ enum class TrackingType(
NotReply("notReply", PullNotification.TRACKING_NAME_DEFAULT); NotReply("notReply", PullNotification.TRACKING_NAME_DEFAULT);
companion object { companion object {
private val valuesCache = values() fun parseStr(str: String?) = entries.firstOrNull { it.str == str } ?: All
fun parseStr(str: String?) = valuesCache.firstOrNull { it.str == str } ?: All
} }
} }

View File

@ -7,99 +7,102 @@ import jp.juggler.subwaytooter.api.entity.TootNotification
import jp.juggler.subwaytooter.table.PushMessage import jp.juggler.subwaytooter.table.PushMessage
import jp.juggler.util.log.LogCategory import jp.juggler.util.log.LogCategory
private val log = LogCategory("NotificationIconAndColor") private val log = LogCategory("PushMessageIconColor")
enum class PushMessageIconColor( enum class PushMessageIconColor(
@ColorRes val colorRes: Int, @ColorRes val colorRes: Int,
@DrawableRes val iconId: Int, @DrawableRes val iconId: Int,
val keys: Array<String>, val keys: Set<String>,
) { ) {
Favourite( Favourite(
0, 0,
R.drawable.ic_star_outline, R.drawable.ic_star_outline,
arrayOf("favourite"), setOf("favourite"),
), ),
Mention( Mention(
0, 0,
R.drawable.outline_alternate_email_24, R.drawable.outline_alternate_email_24,
arrayOf("mention"), setOf("mention"),
), ),
Reply( Reply(
0, 0,
R.drawable.ic_reply, R.drawable.ic_reply,
arrayOf("reply") setOf("reply")
), ),
Reblog( Reblog(
0, 0,
R.drawable.ic_repeat, R.drawable.ic_repeat,
arrayOf("reblog", "renote"), setOf("reblog", "renote"),
), ),
Quote( Quote(
0, 0,
R.drawable.ic_quote, R.drawable.ic_quote,
arrayOf("quote"), setOf("quote"),
), ),
Follow( Follow(
0, 0,
R.drawable.ic_person_add, R.drawable.ic_person_add,
arrayOf("follow", "followRequestAccepted") setOf("follow", "followRequestAccepted")
), ),
Unfollow( Unfollow(
0, 0,
R.drawable.ic_follow_cross, R.drawable.ic_follow_cross,
arrayOf("unfollow") setOf("unfollow")
), ),
Reaction( Reaction(
0, 0,
R.drawable.outline_add_reaction_24, R.drawable.outline_add_reaction_24,
arrayOf("reaction", "emoji_reaction", "pleroma:emoji_reaction") setOf("reaction", "emoji_reaction", "pleroma:emoji_reaction")
), ),
FollowRequest( FollowRequest(
R.color.colorNotificationAccentFollowRequest, R.color.colorNotificationAccentFollowRequest,
R.drawable.ic_follow_wait, R.drawable.ic_follow_wait,
arrayOf("follow_request", "receiveFollowRequest"), setOf("follow_request", "receiveFollowRequest"),
), ),
Poll( Poll(
0, 0,
R.drawable.outline_poll_24, R.drawable.outline_poll_24,
arrayOf("pollVote", "poll_vote", "poll"), setOf("pollVote", "poll_vote", "poll"),
), ),
Status( Status(
0, 0,
R.drawable.ic_edit, R.drawable.ic_edit,
arrayOf("status", "update", "status_reference") setOf("status", "update", "status_reference")
), ),
AdminSignUp( AdminSignUp(
0, 0,
R.drawable.outline_group_add_24, R.drawable.outline_group_add_24,
arrayOf(TootNotification.TYPE_ADMIN_SIGNUP), setOf(TootNotification.TYPE_ADMIN_SIGNUP),
), ),
AdminReport( AdminReport(
R.color.colorNotificationAccentAdminReport, R.color.colorNotificationAccentAdminReport,
R.drawable.ic_error, R.drawable.ic_error,
arrayOf(TootNotification.TYPE_ADMIN_REPORT), setOf(TootNotification.TYPE_ADMIN_REPORT),
), ),
Unknown( Unknown(
R.color.colorNotificationAccentUnknown, R.color.colorNotificationAccentUnknown,
R.drawable.ic_question, R.drawable.ic_question,
arrayOf("unknown"), setOf("unknown"),
) )
; ;
companion object { companion object {
val map = buildMap { val map = PushMessageIconColor.entries.map { it.keys }.flatten().toSet()
values().forEach { .associateWith { key ->
for (k in it.keys) { val colors = PushMessageIconColor.entries
val old: PushMessageIconColor? = get(k) .filter { it.keys.contains(key) }
if (old != null) { when {
error("NotificationIconAndColor: $k is duplicate: ${it.name} and ${old.name}") colors.isEmpty() -> error("missing color fot key=$key")
} else { colors.size > 1 -> error(
put(k, it) "NotificationIconAndColor: duplicate key $key to ${
} colors.joinToString(", ") { it.name }
}"
)
else -> colors.first()
} }
} }
}
} }
} }

View File

@ -208,7 +208,7 @@ object CustomShare {
fun getCache(target: CustomShareTarget) = cache[target] fun getCache(target: CustomShareTarget) = cache[target]
fun reloadCache(context: Context) { fun reloadCache(context: Context) {
CustomShareTarget.values().forEach { target -> for (target in CustomShareTarget.entries) {
val cn = target.customShareComponentName val cn = target.customShareComponentName
val pair = getInfo(context, cn) val pair = getInfo(context, cn)
cache[target] = pair cache[target] = pair