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) {
try {
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) {
log.e(ex, "can't restore customShareTarget.")

View File

@ -20,8 +20,24 @@ import android.widget.ListView
import android.widget.TextView
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import jp.juggler.subwaytooter.*
import jp.juggler.subwaytooter.action.*
import jp.juggler.subwaytooter.ActAbout
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.column.ColumnType
import jp.juggler.subwaytooter.dialog.pickAccount
@ -50,7 +66,7 @@ import jp.juggler.util.ui.createColoredDrawable
import kotlinx.coroutines.withContext
import org.jetbrains.anko.backgroundColor
import java.lang.ref.WeakReference
import java.util.*
import java.util.TimeZone
import java.util.concurrent.TimeUnit
import kotlin.math.abs
@ -71,7 +87,7 @@ class SideMenuAdapter(
private const val urlOlderDevices =
"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
@ -487,10 +503,12 @@ class SideMenuAdapter(
when (itemType) {
ItemType.IT_DIVIDER ->
viewOrInflate(view, parent, R.layout.lv_sidemenu_separator)
ItemType.IT_GROUP_HEADER ->
viewOrInflate<TextView>(view, parent, R.layout.lv_sidemenu_group).apply {
text = actMain.getString(title)
}
ItemType.IT_NORMAL ->
viewOrInflate<TextView>(view, parent, R.layout.lv_sidemenu_item).apply {
isAllCaps = false
@ -522,6 +540,7 @@ class SideMenuAdapter(
background = null
text = versionText
}
ItemType.IT_TIMEZONE ->
viewOrInflate<TextView>(view, parent, R.layout.lv_sidemenu_item).apply {
textSize = 14f
@ -529,6 +548,7 @@ class SideMenuAdapter(
background = null
text = getTimeZoneString(context)
}
ItemType.IT_NOTIFICATION_PERMISSION ->
viewOrInflate<TextView>(view, parent, R.layout.lv_sidemenu_item).apply {
isAllCaps = false
@ -599,6 +619,7 @@ class SideMenuAdapter(
Pair(R.string.notification_push_distributor_disabled) {
actMain.selectPushDistributor()
}
else -> null
}
@ -616,6 +637,7 @@ class SideMenuAdapter(
else -> true
}
else -> true
}
}

View File

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

View File

@ -23,13 +23,12 @@ enum class TootFilterContext(
companion object {
private val log = LogCategory("TootFilterContext")
private val valuesCache = values()
private val apiNameMap = valuesCache.associateBy { it.apiName }
private val apiNameMap = entries.associateBy { it.apiName }
fun parseBits(src: JsonArray?): Int =
src?.stringList()?.mapNotNull { apiNameMap[it]?.bit }?.sum() ?: 0
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
else -> false
}
else -> when (this) {
Public, UnlistedHome -> true
else -> false
@ -109,47 +110,35 @@ enum class TootVisibility(
companion object {
private val log = LogCategory("TootVisivbility")
fun parseMastodon(a: String?): TootVisibility? {
for (v in values()) {
if (v.strMastodon == a) return v
}
return null
}
fun parseMastodon(a: String?) =
entries.find { it.strMastodon == a }
fun parseMisskey(a: String?, localOnly: Boolean = false): TootVisibility? {
for (v in values()) {
if (v.strMisskey == a) {
if (localOnly) {
when (v) {
Public -> return LocalPublic
UnlistedHome -> return LocalHome
PrivateFollowers -> return LocalFollowers
entries.find { it.strMisskey == a }?.let { v ->
if (localOnly) {
when (v) {
Public -> return LocalPublic
UnlistedHome -> return LocalHome
PrivateFollowers -> return LocalFollowers
else -> {
}
}
else -> Unit
}
return v
}
return v
}
return null
}
fun fromId(id: Int): TootVisibility? {
for (v in values()) {
if (v.id == id) return v
}
return null
}
fun fromId(id: Int) = entries.find { it.id == id }
fun parseSavedVisibility(sv: String?): TootVisibility? {
sv ?: return null
// 新しい方式ではenumのidの文字列表現
values().find { it.id.toString() == sv }?.let { return it }
entries.find { it.id.toString() == sv }?.let { return it }
// 古い方式ではマストドンの公開範囲文字列かweb_setting
values().find { it.strMastodon == sv }?.let { return it }
entries.find { it.strMastodon == sv }?.let { return it }
return null
}

View File

@ -70,7 +70,7 @@ enum class SettingType(val id: Int) {
;
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(
PrefI.ipAdditionalButtonsPosition,
R.string.additional_buttons_position,
*(AdditionalButtonsPosition.values().sortedBy { it.idx }.map { it.captionId }
*(AdditionalButtonsPosition.entries.sortedBy { it.idx }.map { it.captionId }
.toIntArray())
)
@ -380,7 +380,7 @@ val appSettingRoot = AppSettingItem(null, SettingType.Section, R.string.app_sett
}
section(R.string.translate_or_custom_share) {
CustomShareTarget.values().forEach { target ->
for (target in CustomShareTarget.entries) {
item(
SettingType.TextWithSelector,
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)
spinner(PrefI.ipMediaBackground, R.string.background_pattern) {
MediaBackgroundDrawable.Kind.values()
MediaBackgroundDrawable.Kind.entries
.filter { it.isMediaBackground }
.map { it.name }
}

View File

@ -326,7 +326,7 @@ object ColumnEncoder {
-> {
profileId = EntityId.mayNull(src.string(KEY_PROFILE_ID))
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,

View File

@ -6,9 +6,22 @@ import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.api.ApiPath
import jp.juggler.subwaytooter.api.TootApiClient
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.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.refreshMSP
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.streaming.StreamSpec
import jp.juggler.subwaytooter.table.daoAcctColor
import jp.juggler.util.*
import jp.juggler.util.data.*
import jp.juggler.util.data.JsonArray
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 java.util.*
import java.util.Locale
import kotlin.math.max
import kotlin.math.min
@ -1128,6 +1147,7 @@ enum class ColumnType(
arrayFinder = misskeyArrayFinderUsers,
listParser = misskeyCustomParserMutes
)
else -> getAccountList(client, ApiPath.PATH_MUTES)
}
},
@ -1142,6 +1162,7 @@ enum class ColumnType(
arrayFinder = misskeyArrayFinderUsers,
listParser = misskeyCustomParserMutes
)
else -> getAccountList(
client,
ApiPath.PATH_MUTES,
@ -1750,6 +1771,7 @@ enum class ColumnType(
ApiPath.PATH_FOLLOW_SUGGESTION2,
listParser = mastodonFollowSuggestion2ListParser,
)
else ->
getAccountList(client, ApiPath.PATH_FOLLOW_SUGGESTION)
}
@ -1773,6 +1795,7 @@ enum class ColumnType(
ApiPath.PATH_FOLLOW_SUGGESTION2,
listParser = mastodonFollowSuggestion2ListParser,
)
else ->
getAccountList(client, ApiPath.PATH_FOLLOW_SUGGESTION)
}
@ -1798,6 +1821,7 @@ enum class ColumnType(
listParser = mastodonFollowSuggestion2ListParser,
mastodonFilterByIdRange = false
)
else ->
getAccountList(
client,
@ -2088,7 +2112,7 @@ enum class ColumnType(
fun dump() {
var min = Int.MAX_VALUE
var max = Int.MIN_VALUE
values().forEach {
for (it in entries) {
val id = it.id
min = min(min, id)
max = max(max, id)

View File

@ -3,7 +3,9 @@ package jp.juggler.subwaytooter.dialog
import android.app.Dialog
import android.view.WindowManager
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.appcompat.app.AppCompatActivity
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.data.notBlank
import jp.juggler.util.data.notEmpty
import jp.juggler.util.log.*
import jp.juggler.util.ui.*
import jp.juggler.util.log.LogCategory
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 org.jetbrains.anko.textColor
import org.jetbrains.anko.textResource
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.IDN
import java.util.*
class LoginForm(
val activity: AppCompatActivity,
@ -62,7 +72,8 @@ class LoginForm(
) {
Login(R.string.existing_account, R.string.existing_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),
}
@ -76,7 +87,7 @@ class LoginForm(
private var targetServerInfo: TootInstance? = null
init {
for (a in Action.values()) {
for (a in Action.entries) {
val subViews =
LvAuthTypeBinding.inflate(activity.layoutInflater, views.llPageAuthType, true)
subViews.btnAuthType.textResource = a.idName

View File

@ -1,10 +1,15 @@
package jp.juggler.subwaytooter.drawable
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 jp.juggler.subwaytooter.R
import jp.juggler.util.ui.*
import jp.juggler.util.ui.attrColor
import kotlin.math.min
class MediaBackgroundDrawable(
@ -33,10 +38,10 @@ class MediaBackgroundDrawable(
;
fun toIndex() = values().indexOf(this)
fun toIndex() = entries.indexOf(this)
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 resources = appContext.resources!!
private val categoryNameMap = HashMap<String, EmojiCategory>().apply {
EmojiCategory.values().forEach { put(it.name, it) }
}
private val categoryNameMap = EmojiCategory.entries.associateBy { it.name }
private var lastEmoji: UnicodeEmoji? = null
private var lastCategory: EmojiCategory? = null
@ -60,28 +58,34 @@ class EmojiMapLoader(
if (!assetsSet.contains(line)) error("missing assets.")
lastEmoji = UnicodeEmoji(assetsName = line)
}
"drawable" -> {
val drawableId = getDrawableId(line) ?: error("missing drawable.")
lastEmoji = UnicodeEmoji(drawableId = drawableId)
}
"un" -> {
val emoji = lastEmoji ?: error("missing lastEmoji.")
addCode(emoji, line)
emoji.unifiedCode = line
}
"u" -> {
val emoji = lastEmoji ?: error("missing lastEmoji.")
addCode(emoji, line)
}
"sn" -> {
val emoji = lastEmoji ?: error("missing lastEmoji.")
addName(emoji, line)
emoji.unifiedName = line
}
"s" -> {
val emoji = lastEmoji ?: error("missing lastEmoji.")
addName(emoji, line)
}
"t" -> {
val cols = line.split(",", limit = 3)
if (cols.size != 3) error("invalid tone spec. line=$lno $line")
@ -99,6 +103,7 @@ class EmojiMapLoader(
lastCategory = categoryNameMap[line]
?: error("missing category name.")
}
"c" -> {
val category = lastCategory
?: error("missing lastCategory.")
@ -110,6 +115,7 @@ class EmojiMapLoader(
category.emojiList.add(emoji)
}
}
else -> error("unknown header $head")
}
} catch (ex: Throwable) {

View File

@ -76,7 +76,7 @@ enum class AdditionalButtonsPosition(
;
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() {
btnCustomShares = CustomShareTarget.values().map { target ->
btnCustomShares = CustomShareTarget.entries.map { target ->
imageButton {
background = ContextCompat.getDrawable(
context,

View File

@ -256,10 +256,9 @@ class NotificationChannelsInitializer : Initializer<Boolean> {
override fun create(context: Context): Boolean {
context.run {
val list = NotificationChannels.values()
log.i("createNotificationChannel(s) size=${list.size}")
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(
nc.id,
getString(nc.titleId),

View File

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

View File

@ -4,7 +4,17 @@ import android.app.ActivityManager
import android.app.PendingIntent
import android.content.Context
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.App1
import jp.juggler.subwaytooter.R
@ -114,7 +124,7 @@ class PollingWorker2(
private fun stateMapToString(map: Map<PollingState, List<String>>) =
StringBuilder().apply {
for (state in PollingState.valuesCache) {
for (state in PollingState.entries) {
val list = map[state] ?: continue
if (isNotEmpty()) append(" |")
append(state.desc)

View File

@ -9,7 +9,6 @@ enum class TrackingType(
NotReply("notReply", PullNotification.TRACKING_NAME_DEFAULT);
companion object {
private val valuesCache = values()
fun parseStr(str: String?) = valuesCache.firstOrNull { it.str == str } ?: All
fun parseStr(str: String?) = entries.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.util.log.LogCategory
private val log = LogCategory("NotificationIconAndColor")
private val log = LogCategory("PushMessageIconColor")
enum class PushMessageIconColor(
@ColorRes val colorRes: Int,
@DrawableRes val iconId: Int,
val keys: Array<String>,
val keys: Set<String>,
) {
Favourite(
0,
R.drawable.ic_star_outline,
arrayOf("favourite"),
setOf("favourite"),
),
Mention(
0,
R.drawable.outline_alternate_email_24,
arrayOf("mention"),
setOf("mention"),
),
Reply(
0,
R.drawable.ic_reply,
arrayOf("reply")
setOf("reply")
),
Reblog(
0,
R.drawable.ic_repeat,
arrayOf("reblog", "renote"),
setOf("reblog", "renote"),
),
Quote(
0,
R.drawable.ic_quote,
arrayOf("quote"),
setOf("quote"),
),
Follow(
0,
R.drawable.ic_person_add,
arrayOf("follow", "followRequestAccepted")
setOf("follow", "followRequestAccepted")
),
Unfollow(
0,
R.drawable.ic_follow_cross,
arrayOf("unfollow")
setOf("unfollow")
),
Reaction(
0,
R.drawable.outline_add_reaction_24,
arrayOf("reaction", "emoji_reaction", "pleroma:emoji_reaction")
setOf("reaction", "emoji_reaction", "pleroma:emoji_reaction")
),
FollowRequest(
R.color.colorNotificationAccentFollowRequest,
R.drawable.ic_follow_wait,
arrayOf("follow_request", "receiveFollowRequest"),
setOf("follow_request", "receiveFollowRequest"),
),
Poll(
0,
R.drawable.outline_poll_24,
arrayOf("pollVote", "poll_vote", "poll"),
setOf("pollVote", "poll_vote", "poll"),
),
Status(
0,
R.drawable.ic_edit,
arrayOf("status", "update", "status_reference")
setOf("status", "update", "status_reference")
),
AdminSignUp(
0,
R.drawable.outline_group_add_24,
arrayOf(TootNotification.TYPE_ADMIN_SIGNUP),
setOf(TootNotification.TYPE_ADMIN_SIGNUP),
),
AdminReport(
R.color.colorNotificationAccentAdminReport,
R.drawable.ic_error,
arrayOf(TootNotification.TYPE_ADMIN_REPORT),
setOf(TootNotification.TYPE_ADMIN_REPORT),
),
Unknown(
R.color.colorNotificationAccentUnknown,
R.drawable.ic_question,
arrayOf("unknown"),
setOf("unknown"),
)
;
companion object {
val map = buildMap {
values().forEach {
for (k in it.keys) {
val old: PushMessageIconColor? = get(k)
if (old != null) {
error("NotificationIconAndColor: $k is duplicate: ${it.name} and ${old.name}")
} else {
put(k, it)
}
val map = PushMessageIconColor.entries.map { it.keys }.flatten().toSet()
.associateWith { key ->
val colors = PushMessageIconColor.entries
.filter { it.keys.contains(key) }
when {
colors.isEmpty() -> error("missing color fot key=$key")
colors.size > 1 -> error(
"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 reloadCache(context: Context) {
CustomShareTarget.values().forEach { target ->
for (target in CustomShareTarget.entries) {
val cn = target.customShareComponentName
val pair = getInfo(context, cn)
cache[target] = pair