1
0
mirror of https://github.com/TwidereProject/Twidere-Android synced 2025-02-17 04:00:48 +01:00

moar syntactic sugar!!

This commit is contained in:
Mariotaku Lee 2017-04-14 17:34:36 +08:00
parent 5caa3986c3
commit b3090b93f5
No known key found for this signature in database
GPG Key ID: 15C10F89D7C33535
19 changed files with 58 additions and 30 deletions

View File

@ -13,15 +13,19 @@ fun Array<*>?.isNullOrEmpty(): Boolean {
return this == null || this.isEmpty()
}
fun <T : Any> Array<T>.toNulls(): Array<T?> {
fun <T> Array<T>.toNulls(): Array<T?> {
@Suppress("UNCHECKED_CAST")
return this as Array<T?>
}
fun <T : Any> Array<T>.toStringArray(): Array<String> {
fun <T> Array<T>.toStringArray(): Array<String> {
return Array(size) { this[it].toString() }
}
inline fun <T : Any, reified R : Any> Array<T>.mapToArray(transform: (T) -> R): Array<R> {
return map(transform).toTypedArray()
inline fun <T, reified R> Array<T>.mapToArray(transform: (T) -> R): Array<R> {
return Array(size) { transform(this[it]) }
}
inline fun <reified R> LongArray.mapToArray(transform: (Long) -> R): Array<R> {
return Array(size) { transform(this[it]) }
}

View File

@ -47,4 +47,12 @@ inline fun <reified T> List<T>.subArray(range: IntRange): Array<T> {
fun <T> T.addTo(collection: MutableCollection<T>): Boolean {
return collection.add(this)
}
inline fun <T : Any, reified R : Any> Collection<T>.mapToArray(transform: (T) -> R): Array<R> {
return map(transform).toTypedArray()
}
inline fun <T : Any, reified R : Any> List<T>.mapToArray(transform: (T) -> R): Array<R> {
return Array(size) { transform(this[it]) }
}

View File

@ -230,7 +230,7 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
return
}
val accountDetails = AccountUtils.getAllAccountDetails(am, accounts, true)
val defaultAccountKeys = accountDetails.map(AccountDetails::key).toTypedArray()
val defaultAccountKeys = accountDetails.mapToArray(AccountDetails::key)
menuBar.setOnMenuItemClickListener(this)
setupEditText()
accountSelectorButton.setOnClickListener(this)
@ -1467,7 +1467,7 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
}
update.text = replyText
update.extended_reply_mode = true
update.excluded_reply_user_ids = excludedMentions.map { it.key.id }.toTypedArray()
update.excluded_reply_user_ids = excludedMentions.mapToArray { it.key.id }
val replyToSelf = accounts.singleOrNull()?.key == inReplyTo.user_key
// Fix status to at least make mentioned user know what status it is
if (!replyToOriginalUser && !replyToSelf) {

View File

@ -14,6 +14,7 @@ import org.apache.james.mime4j.stream.BodyDescriptor
import org.apache.james.mime4j.stream.MimeConfig
import org.apache.james.mime4j.stream.RawField
import org.apache.james.mime4j.util.MimeUtil
import org.mariotaku.ktextension.mapToArray
import org.mariotaku.ktextension.toIntOr
import org.mariotaku.ktextension.toString
import org.mariotaku.twidere.R
@ -130,7 +131,7 @@ fun Draft.getActionName(context: Context): String? {
fun Draft.applyUpdateStatus(statusUpdate: ParcelableStatusUpdate) {
this.unique_id = statusUpdate.draft_unique_id ?: UUID.randomUUID().toString()
this.account_keys = statusUpdate.accounts.map { it.key }.toTypedArray()
this.account_keys = statusUpdate.accounts.mapToArray { it.key }
this.text = statusUpdate.text
this.location = statusUpdate.location
this.media = statusUpdate.media
@ -154,7 +155,7 @@ private class DraftContentHandler(private val context: Context, private val draf
return@let arrayOf(field.mailbox.let { UserKey(it.localPart, it.domain) })
}
is MailboxListField -> {
return@let field.mailboxList.map { UserKey(it.localPart, it.domain) }.toTypedArray()
return@let field.mailboxList.mapToArray { UserKey(it.localPart, it.domain) }
}
else -> {
return@let null

View File

@ -1,6 +1,7 @@
package org.mariotaku.twidere.extension.model
import android.content.Context
import org.mariotaku.ktextension.mapToArray
import org.mariotaku.twidere.R
import org.mariotaku.twidere.model.AccountDetails
import org.mariotaku.twidere.model.ParcelableMessage
@ -127,6 +128,6 @@ fun ParcelableMessageConversation.addParticipants(users: Collection<ParcelableUs
}
this.participants += addingUsers
}
this.participant_keys = this.participants.map(ParcelableUser::key).toTypedArray()
this.participant_keys = this.participants.mapToArray(ParcelableUser::key)
this.participants.sortBy(ParcelableUser::screen_name)
}

View File

@ -55,6 +55,7 @@ import org.mariotaku.abstask.library.TaskStarter
import org.mariotaku.chameleon.Chameleon
import org.mariotaku.chameleon.ChameleonUtils
import org.mariotaku.kpreferences.get
import org.mariotaku.ktextension.mapToArray
import org.mariotaku.ktextension.setItemAvailability
import org.mariotaku.ktextension.useCursor
import org.mariotaku.library.objectcursor.ObjectCursor
@ -723,7 +724,7 @@ class MessageConversationInfoFragment : BaseFragment(), IToolBarSupportFragment,
val actions = arrayOf(Action(getString(R.string.action_edit_conversation_name), "name"),
Action(getString(R.string.action_edit_conversation_avatar), "avatar"))
val builder = AlertDialog.Builder(context)
builder.setItems(actions.map(Action::title).toTypedArray()) { _, which ->
builder.setItems(actions.mapToArray(Action::title)) { _, which ->
val action = actions[which]
(parentFragment as MessageConversationInfoFragment).openEditAction(action.type)
}

View File

@ -50,6 +50,7 @@ import org.mariotaku.chameleon.ChameleonUtils
import org.mariotaku.kpreferences.get
import org.mariotaku.ktextension.contains
import org.mariotaku.ktextension.empty
import org.mariotaku.ktextension.mapToArray
import org.mariotaku.ktextension.set
import org.mariotaku.pickncrop.library.MediaPickerActivity
import org.mariotaku.sqliteqb.library.Expression
@ -510,7 +511,7 @@ class MessagesConversationFragment : AbsContentListRecyclerViewFragment<Messages
fragment: MessagesConversationFragment,
val media: Array<ParcelableMediaUpdate>
) : AbsDeleteMediaTask<MessagesConversationFragment>(fragment.context,
media.map { Uri.parse(it.uri) }.toTypedArray()) {
media.mapToArray { Uri.parse(it.uri) }) {
init {
callback = fragment

View File

@ -1,6 +1,7 @@
package org.mariotaku.twidere.task
import android.content.Context
import org.mariotaku.ktextension.mapToArray
import org.mariotaku.microblog.library.MicroBlogException
import org.mariotaku.twidere.R
import org.mariotaku.twidere.constant.SharedPreferenceConstants.KEY_NAME_FIRST
@ -27,7 +28,7 @@ class AddUserListMembersTask(
try {
val microBlog = MicroBlogAPIFactory.getInstance(context, accountKey) ?:
throw MicroBlogException("No account")
val userIds = users.map(ParcelableUser::key).toTypedArray()
val userIds = users.mapToArray(ParcelableUser::key)
val result = microBlog.addUserListMembers(listId, UserKey.getIds(userIds))
val list = ParcelableUserListUtils.from(result, accountKey)
return SingleResponse(list)

View File

@ -21,6 +21,7 @@ package org.mariotaku.twidere.task.twitter.message
import android.accounts.AccountManager
import android.content.Context
import org.mariotaku.ktextension.mapToArray
import org.mariotaku.microblog.library.MicroBlog
import org.mariotaku.microblog.library.MicroBlogException
import org.mariotaku.twidere.R
@ -78,7 +79,7 @@ class AddParticipantsTask(
when (account.type) {
AccountType.TWITTER -> {
if (account.isOfficial(context)) {
val ids = participants.map { it.key.id }.toTypedArray()
val ids = participants.mapToArray { it.key.id }
val response = microBlog.addParticipants(conversationId, ids)
if (conversation != null) {
conversation.addParticipants(participants)

View File

@ -23,6 +23,7 @@ import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import org.mariotaku.commons.logansquare.LoganSquareMapperFinder
import org.mariotaku.ktextension.mapToArray
import org.mariotaku.ktextension.toIntOr
import org.mariotaku.ktextension.toLongOr
import org.mariotaku.ktextension.useCursor
@ -582,7 +583,7 @@ class GetMessagesTask(
conversation.addParticipants(users)
} else {
conversation.participants = users.toTypedArray()
conversation.participant_keys = users.map(ParcelableUser::key).toTypedArray()
conversation.participant_keys = users.mapToArray(ParcelableUser::key)
}
return conversation
}

View File

@ -29,6 +29,7 @@ import org.apache.commons.collections.primitives.ArrayLongList
import org.apache.commons.collections.primitives.IntList
import org.mariotaku.abstask.library.TaskStarter
import org.mariotaku.kpreferences.get
import org.mariotaku.ktextension.mapToArray
import org.mariotaku.ktextension.toNulls
import org.mariotaku.microblog.library.MicroBlogException
import org.mariotaku.microblog.library.twitter.model.*
@ -553,7 +554,7 @@ class AsyncTwitterWrapper(
override fun doInBackground(vararg params: Any): SingleResponse<ParcelableUserList> {
val microBlog = MicroBlogAPIFactory.getInstance(context, accountKey) ?: return SingleResponse.getInstance<ParcelableUserList>()
try {
val userKeys = users.map { it.key }.toTypedArray()
val userKeys = users.mapToArray(ParcelableUser::key)
val userList = microBlog.deleteUserListMembers(userListId, UserKey.getIds(userKeys))
val list = ParcelableUserListUtils.from(userList, accountKey)
return SingleResponse.getInstance(list)

View File

@ -20,6 +20,7 @@
package org.mariotaku.twidere.util
import android.content.ContentValues
import org.mariotaku.ktextension.mapToArray
import org.mariotaku.library.objectcursor.ObjectCursor
import org.mariotaku.microblog.library.twitter.model.SavedSearch
import org.mariotaku.microblog.library.twitter.model.Status
@ -73,7 +74,7 @@ object ContentValuesCreator {
}
fun createSavedSearches(savedSearches: List<SavedSearch>, accountKey: UserKey): Array<ContentValues> {
return savedSearches.map { createSavedSearch(it, accountKey) }.toTypedArray()
return savedSearches.mapToArray { createSavedSearch(it, accountKey) }
}
fun createStatus(orig: Status, accountKey: UserKey, accountType: String,

View File

@ -10,6 +10,7 @@ import android.net.Uri
import android.support.annotation.WorkerThread
import android.support.v4.util.LongSparseArray
import org.mariotaku.kpreferences.get
import org.mariotaku.ktextension.mapToArray
import org.mariotaku.ktextension.toStringArray
import org.mariotaku.ktextension.useCursor
import org.mariotaku.library.objectcursor.ObjectCursor
@ -98,7 +99,7 @@ fun buildStatusFilterWhereClause(preferences: SharedPreferences, table: String,
@SuppressLint("Recycle")
fun deleteDrafts(context: Context, draftIds: LongArray): Int {
val where = Expression.inArgs(Drafts._ID, draftIds.size).sql
val whereArgs = draftIds.map(Long::toString).toTypedArray()
val whereArgs = draftIds.mapToArray(Long::toString)
context.contentResolver.query(Drafts.CONTENT_URI, Drafts.COLUMNS, where, whereArgs,
null).useCursor { cursor ->

View File

@ -30,6 +30,7 @@ import android.provider.BaseColumns
import android.support.annotation.WorkerThread
import android.text.TextUtils
import org.mariotaku.kpreferences.get
import org.mariotaku.ktextension.mapToArray
import org.mariotaku.ktextension.useCursor
import org.mariotaku.library.objectcursor.ObjectCursor
import org.mariotaku.microblog.library.MicroBlog
@ -369,7 +370,7 @@ object DataStoreUtils {
extraWhere: Expression?, extraWhereArgs: Array<String>?,
sinceColumn: String, since: Long, followingOnly: Boolean,
accountKeys: Array<UserKey>?): Int {
val keys = (accountKeys ?: getActivatedAccountKeys(context)).map { it.toString() }.toTypedArray()
val keys = (accountKeys ?: getActivatedAccountKeys(context)).mapToArray { it.toString() }
val expressions = ArrayList<Expression>()
expressions.add(Expression.inArgs(Column(Activities.ACCOUNT_KEY), keys.size))
expressions.add(Expression.greaterThan(sinceColumn, since))

View File

@ -94,7 +94,7 @@ class MultiSelectEventHandler(
val am = AccountManager.get(activity)
val intent = Intent(INTENT_ACTION_REPLY_MULTIPLE)
val bundle = Bundle()
val accountScreenNames = AccountUtils.getAccounts(am).map { it.getAccountUser(am).name }.toTypedArray()
val accountScreenNames = AccountUtils.getAccounts(am).map { it.getAccountUser(am).screen_name }
val allMentions = TreeSet(String.CASE_INSENSITIVE_ORDER)
for (selected in selectedItems) {
if (selected is ParcelableStatus) {
@ -104,7 +104,7 @@ class MultiSelectEventHandler(
allMentions.add(selected.screen_name)
}
}
allMentions.removeAll(Arrays.asList(*accountScreenNames))
allMentions.removeAll(accountScreenNames)
val firstObj = selectedItems[0]
if (firstObj is ParcelableStatus) {
bundle.putString(EXTRA_IN_REPLY_TO_ID, firstObj.id)

View File

@ -7,6 +7,7 @@ import com.squareup.otto.Bus
import org.mariotaku.abstask.library.AbstractTask
import org.mariotaku.abstask.library.TaskStarter
import org.mariotaku.kpreferences.KPreferences
import org.mariotaku.ktextension.mapToArray
import org.mariotaku.ktextension.toNulls
import org.mariotaku.twidere.TwidereConstants.LOGTAG
import org.mariotaku.twidere.constant.IntentConstants.INTENT_PACKAGE_PREFIX
@ -77,7 +78,7 @@ class TaskServiceRunner(
override val accountKeys: Array<UserKey> by lazy {
AccountPreferences.getAccountPreferences(context, DataStoreUtils.getAccountKeys(context)).filter {
it.isAutoRefreshEnabled && it.isAutoRefreshDirectMessagesEnabled
}.map(AccountPreferences::accountKey).toTypedArray()
}.mapToArray(AccountPreferences::accountKey)
}
}
return task
@ -103,7 +104,7 @@ class TaskServiceRunner(
override val accountKeys: Array<UserKey> by lazy {
return@lazy AccountPreferences.getAccountPreferences(context, DataStoreUtils.getAccountKeys(context)).filter {
it.isAutoRefreshEnabled && refreshable(it)
}.map(AccountPreferences::accountKey).toTypedArray()
}.mapToArray(AccountPreferences::accountKey)
}
override val sinceIds: Array<String?>?

View File

@ -24,6 +24,7 @@ import android.database.MatrixCursor
import android.database.MergeCursor
import android.net.Uri
import android.text.TextUtils
import org.mariotaku.ktextension.mapToArray
import org.mariotaku.sqliteqb.library.*
import org.mariotaku.twidere.TwidereConstants.*
import org.mariotaku.twidere.model.UserKey
@ -133,7 +134,7 @@ object SuggestionsCursorCreator {
val whereArgs = nicknameKeys + queryEscaped + queryEscaped
val orderBy = arrayOf(CachedUsers.SCORE, CachedUsers.LAST_SEEN, CachedUsers.SCREEN_NAME, CachedUsers.NAME)
val ascending = booleanArrayOf(false, false, true, true)
val mappedProjection = nonNullProjection.map { autoCompleteUsersProjectionMap[it] }.toTypedArray()
val mappedProjection = nonNullProjection.mapToArray { autoCompleteUsersProjectionMap[it] }
val (sql, bindingArgs) = CachedUsersQueryBuilder.withScore(mappedProjection,
where.sql, whereArgs, OrderBy(orderBy, ascending).sql, accountKey, 0)
return db.rawQuery(sql.sql, bindingArgs)
@ -141,7 +142,7 @@ object SuggestionsCursorCreator {
Suggestions.AutoComplete.TYPE_HASHTAGS -> {
val where = Expression.likeRaw(Columns.Column(CachedHashtags.NAME), "?||'%'", "^")
val whereArgs = arrayOf(queryEscaped)
val mappedProjection = nonNullProjection.map { hashtagsProjectionMap[it] }.toTypedArray()
val mappedProjection = nonNullProjection.mapToArray { hashtagsProjectionMap[it] }
return db.query(CachedHashtags.TABLE_NAME, mappedProjection, where.sql, whereArgs, null,
null, null)
}
@ -161,7 +162,7 @@ object SuggestionsCursorCreator {
val order = arrayOf(CachedUsers.LAST_SEEN, CachedUsers.SCORE, CachedUsers.SCREEN_NAME, CachedUsers.NAME)
val ascending = booleanArrayOf(false, false, true, true)
val orderBy = OrderBy(order, ascending)
val usersProjection = selection.map { suggestionUsersProjectionMap[it] }.toTypedArray()
val usersProjection = selection.mapToArray { suggestionUsersProjectionMap[it] }
val usersQuery = CachedUsersQueryBuilder.withScore(usersProjection,
usersSelection.sql, selectionArgs, orderBy.sql, accountKey, 0)
return db.rawQuery(usersQuery.first.sql, usersQuery.second)
@ -170,7 +171,7 @@ object SuggestionsCursorCreator {
private fun getSavedSearchCursor(db: SQLiteDatabaseWrapper, projection: Array<String>, accountKey: UserKey): Cursor {
val savedSearchesWhere = Expression.equalsArgs(SavedSearches.ACCOUNT_KEY)
val whereArgs = arrayOf(accountKey.toString())
val savedSearchesProjection = projection.map { savedSearchesProjectionMap[it] }.toTypedArray()
val savedSearchesProjection = projection.mapToArray { savedSearchesProjectionMap[it] }
return db.query(true, SavedSearches.TABLE_NAME, savedSearchesProjection, savedSearchesWhere.sql,
whereArgs, null, null, SavedSearches.DEFAULT_SORT_ORDER, null)
}
@ -179,7 +180,7 @@ object SuggestionsCursorCreator {
val queryEscaped = query.replace("_", "^_")
val historySelection = Expression.likeRaw(Columns.Column(SearchHistory.QUERY), "?||'%'", "^")
val historySelectionArgs = arrayOf(queryEscaped)
val historyProjection = projection.map { historyProjectionMap[it] }.toTypedArray()
val historyProjection = projection.mapToArray { historyProjectionMap[it] }
val cursorLimit = if (TextUtils.isEmpty(query)) "3" else "2"
return db.query(true, SearchHistory.TABLE_NAME, historyProjection, historySelection.sql,
historySelectionArgs, null, null, SearchHistory.DEFAULT_SORT_ORDER, cursorLimit)

View File

@ -7,6 +7,7 @@ import android.support.v7.app.AlertDialog
import android.view.View
import org.mariotaku.kpreferences.get
import org.mariotaku.ktextension.Bundle
import org.mariotaku.ktextension.mapToArray
import org.mariotaku.ktextension.set
import org.mariotaku.twidere.R
import org.mariotaku.twidere.TwidereConstants.REQUEST_PURCHASE_EXTRA_FEATURES
@ -18,6 +19,7 @@ import org.mariotaku.twidere.extension.applyTheme
import org.mariotaku.twidere.fragment.BaseDialogFragment
import org.mariotaku.twidere.fragment.ExtraFeaturesIntroductionDialogFragment
import org.mariotaku.twidere.fragment.sync.SyncSettingsFragment
import org.mariotaku.twidere.model.sync.SyncProviderEntry
import org.mariotaku.twidere.util.premium.ExtraFeaturesService
import org.mariotaku.twidere.util.sync.DataSyncProvider
@ -89,11 +91,11 @@ class SyncStatusViewController : PremiumDashboardActivity.ExtraFeatureViewContro
class ConnectNetworkStorageSelectionDialogFragment : BaseDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val providers = DataSyncProvider.Factory.getSupportedProviders(context)
val itemNames = providers.map { it.name }.toTypedArray()
val itemNames = providers.mapToArray(SyncProviderEntry::name)
val builder = AlertDialog.Builder(context)
builder.setTitle(R.string.title_dialog_sync_connect_to)
builder.setItems(itemNames) { dialog, which ->
builder.setItems(itemNames) { _, which ->
val activity = activity as PremiumDashboardActivity
activity.startActivityForControllerResult(providers[which].authIntent,
arguments.getInt(EXTRA_POSITION), REQUEST_CONNECT_NETWORK_STORAGE)

View File

@ -24,6 +24,7 @@ import android.support.v7.widget.RecyclerView
import android.view.View
import com.bumptech.glide.RequestManager
import kotlinx.android.synthetic.main.list_item_draft.view.*
import org.mariotaku.ktextension.mapToArray
import org.mariotaku.twidere.R
import org.mariotaku.twidere.extension.model.getActionName
import org.mariotaku.twidere.model.Draft
@ -48,7 +49,7 @@ class DraftViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
Draft.Action.SEND_DIRECT_MESSAGE, Draft.Action.SEND_DIRECT_MESSAGE_COMPAT,
Draft.Action.UPDATE_STATUS, Draft.Action.UPDATE_STATUS_COMPAT_1,
Draft.Action.UPDATE_STATUS_COMPAT_2, Draft.Action.REPLY, Draft.Action.QUOTE -> {
val media = draft.media?.map(::ParcelableMedia)?.toTypedArray()
val media = draft.media?.mapToArray(::ParcelableMedia)
mediaPreviewContainer.visibility = View.VISIBLE
mediaPreviewContainer.displayMedia(requestManager = requestManager,
media = media)