Replace cascade ifs with whens

This commit is contained in:
TacoTheDank 2020-06-08 20:21:48 -04:00
parent 50ee094889
commit 966bd2c7b5
39 changed files with 809 additions and 540 deletions

View File

@ -25,26 +25,38 @@ import java.util.*
@SuppressLint("RestrictedApi")
object LocaleHelperAccessor {
fun forLanguageTag(str: String): Locale {
if (str.contains("-")) {
val args = str.split("-").dropLastWhile { it.isEmpty() }.toTypedArray()
if (args.size > 2) {
return Locale(args[0], args[1], args[2])
} else if (args.size > 1) {
return Locale(args[0], args[1])
} else if (args.size == 1) {
return Locale(args[0])
when {
str.contains("-") -> {
val args = str.split("-").dropLastWhile { it.isEmpty() }.toTypedArray()
when {
args.size > 2 -> {
return Locale(args[0], args[1], args[2])
}
args.size > 1 -> {
return Locale(args[0], args[1])
}
args.size == 1 -> {
return Locale(args[0])
}
}
}
} else if (str.contains("_")) {
val args = str.split("_").dropLastWhile { it.isEmpty() }.toTypedArray()
if (args.size > 2) {
return Locale(args[0], args[1], args[2])
} else if (args.size > 1) {
return Locale(args[0], args[1])
} else if (args.size == 1) {
return Locale(args[0])
str.contains("_") -> {
val args = str.split("_").dropLastWhile { it.isEmpty() }.toTypedArray()
when {
args.size > 2 -> {
return Locale(args[0], args[1], args[2])
}
args.size > 1 -> {
return Locale(args[0], args[1])
}
args.size == 1 -> {
return Locale(args[0])
}
}
}
else -> {
return Locale(str)
}
} else {
return Locale(str)
}
throw IllegalArgumentException("Can not parse language tag: [$str]")

View File

@ -35,20 +35,24 @@ object InternalActivityCreator {
activity.maxSortPosition = activity.minSortPosition
activity.createdAt = status.getCreatedAt()
if (status.getInReplyToUserId() == accountId) {
activity.action = Activity.Action.REPLY
activity.targetStatuses = arrayOf(status)
when {
status.getInReplyToUserId() == accountId -> {
activity.action = Activity.Action.REPLY
activity.targetStatuses = arrayOf(status)
//TODO set target statuses (in reply to status)
activity.targetObjectStatuses = arrayOfNulls<Status>(0)
} else if (status.quotedStatus?.user?.id == accountId) {
activity.action = Activity.Action.QUOTE
activity.targetStatuses = arrayOf(status)
activity.targetObjectStatuses = arrayOfNulls<Status>(0)
} else {
activity.action = Activity.Action.MENTION
activity.targetUsers = arrayOfNulls<User>(0)
activity.targetObjectStatuses = arrayOf(status)
//TODO set target statuses (in reply to status)
activity.targetObjectStatuses = arrayOfNulls<Status>(0)
}
status.quotedStatus?.user?.id == accountId -> {
activity.action = Activity.Action.QUOTE
activity.targetStatuses = arrayOf(status)
activity.targetObjectStatuses = arrayOfNulls<Status>(0)
}
else -> {
activity.action = Activity.Action.MENTION
activity.targetUsers = arrayOfNulls<User>(0)
activity.targetObjectStatuses = arrayOf(status)
}
}
activity.sourcesSize = 1
activity.sources = arrayOf(status.getUser())

View File

@ -435,7 +435,10 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
val src = MediaPickerActivity.getMediaUris(data)?.takeIf(Array<Uri>::isNotEmpty) ?:
data.getParcelableExtra<Uri>(EXTRA_IMAGE_URI)?.let { arrayOf(it) }
if (src != null) {
TaskStarter.execute(AddMediaTask(this, src, null, false, false))
TaskStarter.execute(AddMediaTask(this, src, null,
copySrc = false,
deleteSrc = false
))
}
}
}
@ -1087,16 +1090,20 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
val action = intent.action
val hasVisibility = intent.hasExtra(EXTRA_VISIBILITY)
val hasAccountKeys: Boolean
if (intent.hasExtra(EXTRA_ACCOUNT_KEYS)) {
val accountKeys = intent.getTypedArrayExtra<UserKey>(EXTRA_ACCOUNT_KEYS)
accountsAdapter.selectedAccountKeys = accountKeys
hasAccountKeys = true
} else if (intent.hasExtra(EXTRA_ACCOUNT_KEY)) {
val accountKey = intent.getParcelableExtra<UserKey>(EXTRA_ACCOUNT_KEY)
accountsAdapter.selectedAccountKeys = arrayOf(accountKey)
hasAccountKeys = true
} else {
hasAccountKeys = false
when {
intent.hasExtra(EXTRA_ACCOUNT_KEYS) -> {
val accountKeys = intent.getTypedArrayExtra<UserKey>(EXTRA_ACCOUNT_KEYS)
accountsAdapter.selectedAccountKeys = accountKeys
hasAccountKeys = true
}
intent.hasExtra(EXTRA_ACCOUNT_KEY) -> {
val accountKey = intent.getParcelableExtra<UserKey>(EXTRA_ACCOUNT_KEY)
accountsAdapter.selectedAccountKeys = arrayOf(accountKey)
hasAccountKeys = true
}
else -> {
hasAccountKeys = false
}
}
when (action) {
Intent.ACTION_SEND, Intent.ACTION_SEND_MULTIPLE -> {
@ -1105,7 +1112,10 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
val stream = intent.getStreamExtra()
if (stream != null) {
val src = stream.toTypedArray()
TaskStarter.execute(AddMediaTask(this, src, null, true, false))
TaskStarter.execute(AddMediaTask(this, src, null,
copySrc = true,
deleteSrc = false
))
}
}
else -> {
@ -1114,7 +1124,10 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
val data = intent.data
if (data != null) {
val src = arrayOf(data)
TaskStarter.execute(AddMediaTask(this, src, null, true, false))
TaskStarter.execute(AddMediaTask(this, src, null,
copySrc = true,
deleteSrc = false
))
}
}
}
@ -1820,7 +1833,10 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
})
editText.customSelectionActionModeCallback = this
editText.imageInputListener = { contentInfo ->
val task = AddMediaTask(this, arrayOf(contentInfo.contentUri), null, true, false)
val task = AddMediaTask(this, arrayOf(contentInfo.contentUri), null,
copySrc = true,
deleteSrc = false
)
task.callback = {
contentInfo.releasePermission()
}
@ -2123,13 +2139,16 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
textView.spannable = ParcelableLocationUtils.getHumanReadableString(location, 3)
textView.tag = location
} else {
val tag = textView.tag
if (tag is Address) {
textView.spannable = tag.locality
} else if (tag is NoAddress) {
textView.setText(R.string.label_location_your_coarse_location)
} else {
textView.setText(R.string.getting_location)
when (val tag = textView.tag) {
is Address -> {
textView.spannable = tag.locality
}
is NoAddress -> {
textView.setText(R.string.label_location_your_coarse_location)
}
else -> {
textView.setText(R.string.getting_location)
}
}
}
} else {

View File

@ -87,13 +87,17 @@ class FileSelectorActivity : BaseActivity(), FileSelectorDialogFragment.Callback
finish()
return
}
if (checkAllSelfPermissionsGranted(AndroidPermissions.READ_EXTERNAL_STORAGE, AndroidPermissions.WRITE_EXTERNAL_STORAGE)) {
showPickFileDialog()
} else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
val permissions = arrayOf(AndroidPermissions.READ_EXTERNAL_STORAGE, AndroidPermissions.WRITE_EXTERNAL_STORAGE)
ActivityCompat.requestPermissions(this, permissions, REQUEST_REQUEST_PERMISSIONS)
} else {
finishWithDeniedMessage()
when {
checkAllSelfPermissionsGranted(AndroidPermissions.READ_EXTERNAL_STORAGE, AndroidPermissions.WRITE_EXTERNAL_STORAGE) -> {
showPickFileDialog()
}
Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN -> {
val permissions = arrayOf(AndroidPermissions.READ_EXTERNAL_STORAGE, AndroidPermissions.WRITE_EXTERNAL_STORAGE)
ActivityCompat.requestPermissions(this, permissions, REQUEST_REQUEST_PERMISSIONS)
}
else -> {
finishWithDeniedMessage()
}
}
}

View File

@ -428,23 +428,30 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher,
internal fun onSignInError(exception: Exception) {
DebugLog.w(LOGTAG, "Sign in error", exception)
var errorReason: String? = null
if (exception is AuthenticityTokenException) {
Toast.makeText(this, R.string.message_toast_wrong_api_key, Toast.LENGTH_SHORT).show()
errorReason = "wrong_api_key"
} else if (exception is WrongUserPassException) {
Toast.makeText(this, R.string.message_toast_wrong_username_password, Toast.LENGTH_SHORT).show()
errorReason = "wrong_username_password"
} else if (exception is SignInTask.WrongBasicCredentialException) {
Toast.makeText(this, R.string.message_toast_wrong_username_password, Toast.LENGTH_SHORT).show()
errorReason = "wrong_username_password"
} else if (exception is SignInTask.WrongAPIURLFormatException) {
Toast.makeText(this, R.string.message_toast_wrong_api_key, Toast.LENGTH_SHORT).show()
errorReason = "wrong_api_key"
} else if (exception is LoginVerificationException) {
Toast.makeText(this, R.string.message_toast_login_verification_failed, Toast.LENGTH_SHORT).show()
errorReason = "login_verification_failed"
} else {
Toast.makeText(this, exception.getErrorMessage(this), Toast.LENGTH_SHORT).show()
when (exception) {
is AuthenticityTokenException -> {
Toast.makeText(this, R.string.message_toast_wrong_api_key, Toast.LENGTH_SHORT).show()
errorReason = "wrong_api_key"
}
is WrongUserPassException -> {
Toast.makeText(this, R.string.message_toast_wrong_username_password, Toast.LENGTH_SHORT).show()
errorReason = "wrong_username_password"
}
is SignInTask.WrongBasicCredentialException -> {
Toast.makeText(this, R.string.message_toast_wrong_username_password, Toast.LENGTH_SHORT).show()
errorReason = "wrong_username_password"
}
is SignInTask.WrongAPIURLFormatException -> {
Toast.makeText(this, R.string.message_toast_wrong_api_key, Toast.LENGTH_SHORT).show()
errorReason = "wrong_api_key"
}
is LoginVerificationException -> {
Toast.makeText(this, R.string.message_toast_login_verification_failed, Toast.LENGTH_SHORT).show()
errorReason = "login_verification_failed"
}
else -> {
Toast.makeText(this, exception.getErrorMessage(this), Toast.LENGTH_SHORT).show()
}
}
Analyzer.log(SignIn(false, credentialsType = apiConfig.credentialsType,
errorReason = errorReason, accountType = apiConfig.type))

View File

@ -129,12 +129,16 @@ class UserSelectorActivity : BaseActivity(), OnItemClickListener, LoaderManager.
listContainer.visibility = View.VISIBLE
adapter.setData(data, true)
loader as CacheUserSearchLoader
if (data.isNotNullOrEmpty()) {
showList()
} else if (loader.query.isEmpty()) {
showSearchHint()
} else {
showNotFound()
when {
data.isNotNullOrEmpty() -> {
showList()
}
loader.query.isEmpty() -> {
showSearchHint()
}
else -> {
showNotFound()
}
}
}

View File

@ -80,14 +80,18 @@ class DummyItemAdapter(
}
override fun getStatus(position: Int, raw: Boolean): ParcelableStatus {
if (adapter is ParcelableStatusesAdapter) {
return adapter.getStatus(position, raw)
} else if (adapter is VariousItemsAdapter) {
return adapter.getItem(position) as ParcelableStatus
} else if (adapter is ParcelableActivitiesAdapter) {
return adapter.getActivity(position).activityStatus!!
return when (adapter) {
is ParcelableStatusesAdapter -> {
adapter.getStatus(position, raw)
}
is VariousItemsAdapter -> {
adapter.getItem(position) as ParcelableStatus
}
is ParcelableActivitiesAdapter -> {
adapter.getActivity(position).activityStatus!!
}
else -> throw IndexOutOfBoundsException()
}
throw IndexOutOfBoundsException()
}
override fun getStatusCount(raw: Boolean) = 0

View File

@ -171,25 +171,29 @@ abstract class ParcelableStatusesAdapter(
override fun setData(data: List<ParcelableStatus>?): Boolean {
var changed = true
if (data == null) {
displayPositions = null
displayDataCount = 0
} else if (data is ObjectCursor) {
displayPositions = null
displayDataCount = data.size
} else {
var filteredCount = 0
displayPositions = IntArray(data.size).apply {
data.forEachIndexed { i, item ->
if (!item.is_gap && item.is_filtered) {
filteredCount++
} else {
this[i - filteredCount] = i
when (data) {
null -> {
displayPositions = null
displayDataCount = 0
}
is ObjectCursor -> {
displayPositions = null
displayDataCount = data.size
}
else -> {
var filteredCount = 0
displayPositions = IntArray(data.size).apply {
data.forEachIndexed { i, item ->
if (!item.is_gap && item.is_filtered) {
filteredCount++
} else {
this[i - filteredCount] = i
}
}
}
displayDataCount = data.size - filteredCount
changed = this.data != data
}
displayDataCount = data.size - filteredCount
changed = this.data != data
}
this.data = data
this.infoCache = if (data != null) arrayOfNulls(data.size) else null

View File

@ -43,15 +43,19 @@ fun View.getFrame(rect: Rect) {
@UiThread
fun View.getFrameRelatedTo(rect: Rect, other: View? = null) {
this.getFrame(rect)
if (other == null) {
offsetToRoot(this, rect)
} else if (other === this) {
rect.offsetTo(0, 0)
} else if (other !== parent) {
offsetToRoot(this, rect)
other.getFrame(tempRect)
offsetToRoot(other, tempRect)
rect.offset(-tempRect.left, -tempRect.top)
when {
other == null -> {
offsetToRoot(this, rect)
}
other === this -> {
rect.offsetTo(0, 0)
}
other !== parent -> {
offsetToRoot(this, rect)
other.getFrame(tempRect)
offsetToRoot(other, tempRect)
rect.offset(-tempRect.left, -tempRect.top)
}
}
}

View File

@ -29,14 +29,18 @@ fun Attachment.toParcelable(externalUrl: String?) : ParcelableMedia? {
val mimeType = mimetype ?: return null
val result = ParcelableMedia()
if (mimeType.startsWith("image/")) {
result.type = ParcelableMedia.Type.IMAGE
} else if (mimeType.startsWith("video/")) {
result.type = ParcelableMedia.Type.VIDEO
} else {
// https://github.com/TwidereProject/Twidere-Android/issues/729
// Skip unsupported attachment
return null
when {
mimeType.startsWith("image/") -> {
result.type = ParcelableMedia.Type.IMAGE
}
mimeType.startsWith("video/") -> {
result.type = ParcelableMedia.Type.VIDEO
}
else -> {
// https://github.com/TwidereProject/Twidere-Android/issues/729
// Skip unsupported attachment
return null
}
}
result.width = width
result.height = height

View File

@ -48,14 +48,19 @@ class APIEditorDialogFragment : BaseDialogFragment() {
val targetFragment = this.targetFragment
val parentFragment = this.parentFragment
val host = this.host
if (targetFragment is APIEditorCallback) {
targetFragment.onSaveAPIConfig(applyCustomAPIConfig())
} else if (parentFragment is APIEditorCallback) {
parentFragment.onSaveAPIConfig(applyCustomAPIConfig())
} else if (host is APIEditorCallback) {
host.onSaveAPIConfig(applyCustomAPIConfig())
} else {
kPreferences[defaultAPIConfigKey] = applyCustomAPIConfig()
when {
targetFragment is APIEditorCallback -> {
targetFragment.onSaveAPIConfig(applyCustomAPIConfig())
}
parentFragment is APIEditorCallback -> {
parentFragment.onSaveAPIConfig(applyCustomAPIConfig())
}
host is APIEditorCallback -> {
host.onSaveAPIConfig(applyCustomAPIConfig())
}
else -> {
kPreferences[defaultAPIConfigKey] = applyCustomAPIConfig()
}
}
}
builder.setNegativeButton(android.R.string.cancel, null)

View File

@ -290,12 +290,16 @@ abstract class AbsStatusesFragment : AbsContentListRecyclerViewFragment<Parcelab
} else {
firstVisibleItemPosition
}.coerceInOr(statusRange, -1)
lastReadId = if (lastReadPosition < 0) {
-1
} else if (useSortIdAsReadPosition) {
adapter.getStatusSortId(lastReadPosition, false)
} else {
adapter.getStatusPositionKey(lastReadPosition)
lastReadId = when {
lastReadPosition < 0 -> {
-1
}
useSortIdAsReadPosition -> {
adapter.getStatusSortId(lastReadPosition, false)
}
else -> {
adapter.getStatusPositionKey(lastReadPosition)
}
}
lastReadViewTop = layoutManager.findViewByPosition(lastReadPosition)?.top ?: 0
loadMore = statusRange.last in 0..lastVisibleItemPosition
@ -623,15 +627,19 @@ abstract class AbsStatusesFragment : AbsContentListRecyclerViewFragment<Parcelab
}
}
R.id.favorite -> {
if (fragment.preferences[favoriteConfirmationKey]) {
fragment.executeAfterFragmentResumed {
FavoriteConfirmDialogFragment.show(it.childFragmentManager,
when {
fragment.preferences[favoriteConfirmationKey] -> {
fragment.executeAfterFragmentResumed {
FavoriteConfirmDialogFragment.show(it.childFragmentManager,
status.account_key, status.id, status)
}
}
status.is_favorite -> {
fragment.twitterWrapper.destroyFavoriteAsync(status.account_key, status.id)
}
else -> {
holder.playLikeAnimation(DefaultOnLikedListener(fragment.twitterWrapper, status))
}
} else if (status.is_favorite) {
fragment.twitterWrapper.destroyFavoriteAsync(status.account_key, status.id)
} else {
holder.playLikeAnimation(DefaultOnLikedListener(fragment.twitterWrapper, status))
}
}
}
@ -721,16 +729,20 @@ abstract class AbsStatusesFragment : AbsContentListRecyclerViewFragment<Parcelab
return true
}
ACTION_STATUS_FAVORITE -> {
if (fragment.preferences[favoriteConfirmationKey]) {
fragment.executeAfterFragmentResumed {
FavoriteConfirmDialogFragment.show(it.childFragmentManager,
when {
fragment.preferences[favoriteConfirmationKey] -> {
fragment.executeAfterFragmentResumed {
FavoriteConfirmDialogFragment.show(it.childFragmentManager,
status.account_key, status.id, status)
}
}
status.is_favorite -> {
fragment.twitterWrapper.destroyFavoriteAsync(status.account_key, status.id)
}
else -> {
val holder = fragment.recyclerView.findViewHolderForLayoutPosition(position) as StatusViewHolder
holder.playLikeAnimation(DefaultOnLikedListener(fragment.twitterWrapper, status))
}
} else if (status.is_favorite) {
fragment.twitterWrapper.destroyFavoriteAsync(status.account_key, status.id)
} else {
val holder = fragment.recyclerView.findViewHolderForLayoutPosition(position) as StatusViewHolder
holder.playLikeAnimation(DefaultOnLikedListener(fragment.twitterWrapper, status))
}
return true
}

View File

@ -532,12 +532,16 @@ class AccountsDashboardFragment : BaseFragment(), LoaderCallbacks<AccountsInfo>,
val width = if (bannerWidth > 0) bannerWidth else defWidth
val bannerView = accountProfileBanner.nextView as ImageView
val user = account.user
val fallbackBanner = if (user.link_color != 0) {
ColorDrawable(user.link_color)
} else if (user.account_color != 0) {
ColorDrawable(user.account_color)
} else {
ColorDrawable(Chameleon.getOverrideTheme(requireActivity(), activity).colorPrimary)
val fallbackBanner = when {
user.link_color != 0 -> {
ColorDrawable(user.link_color)
}
user.account_color != 0 -> {
ColorDrawable(user.account_color)
}
else -> {
ColorDrawable(Chameleon.getOverrideTheme(requireActivity(), activity).colorPrimary)
}
}
requestManager.loadProfileBanner(requireContext(), account.user, width).fallback(fallbackBanner)

View File

@ -87,24 +87,29 @@ class AddStatusFilterDialogFragment : BaseDialogFragment() {
}
val info = filterItems!![checkPositions.keyAt(i)]
val value = info.value
if (value is ParcelableUserMention) {
userKeys.add(value.key)
userValues.add(ContentValuesCreator.createFilteredUser(value))
} else if (value is UserItem) {
userKeys.add(value.key)
userValues.add(createFilteredUser(value))
} else if (info.type == FilterItemInfo.FILTER_TYPE_KEYWORD) {
val keyword = ParseUtils.parseString(value)
keywords.add(keyword)
val values = ContentValues()
values.put(Filters.Keywords.VALUE, "#$keyword")
keywordValues.add(values)
} else if (info.type == FilterItemInfo.FILTER_TYPE_SOURCE) {
val source = ParseUtils.parseString(value)
sources.add(source)
val values = ContentValues()
values.put(Filters.Sources.VALUE, source)
sourceValues.add(values)
when {
value is ParcelableUserMention -> {
userKeys.add(value.key)
userValues.add(ContentValuesCreator.createFilteredUser(value))
}
value is UserItem -> {
userKeys.add(value.key)
userValues.add(createFilteredUser(value))
}
info.type == FilterItemInfo.FILTER_TYPE_KEYWORD -> {
val keyword = ParseUtils.parseString(value)
keywords.add(keyword)
val values = ContentValues()
values.put(Filters.Keywords.VALUE, "#$keyword")
keywordValues.add(values)
}
info.type == FilterItemInfo.FILTER_TYPE_SOURCE -> {
val source = ParseUtils.parseString(value)
sources.add(source)
val values = ContentValues()
values.put(Filters.Sources.VALUE, source)
sourceValues.add(values)
}
}
}
context?.contentResolver?.let { resolver ->
@ -164,12 +169,15 @@ class AddStatusFilterDialogFragment : BaseDialogFragment() {
}
private fun getName(manager: UserColorNameManager, value: Any, nameFirst: Boolean): String {
return if (value is ParcelableUserMention) {
manager.getDisplayName(value.key, value.name, value.screen_name, nameFirst)
} else if (value is UserItem) {
manager.getDisplayName(value.key, value.name, value.screen_name, nameFirst)
} else
ParseUtils.parseString(value)
return when (value) {
is ParcelableUserMention -> {
manager.getDisplayName(value.key, value.name, value.screen_name, nameFirst)
}
is UserItem -> {
manager.getDisplayName(value.key, value.name, value.screen_name, nameFirst)
}
else -> ParseUtils.parseString(value)
}
}
internal data class FilterItemInfo(

View File

@ -89,14 +89,19 @@ class ExtraFeaturesIntroductionDialogFragment : BaseDialogFragment() {
}
private fun startActivityForResultOnTarget(intent: Intent) {
if (targetFragment != null) {
targetFragment?.startActivityForResult(intent, targetRequestCode)
} else if (requestCode == 0) {
startActivity(intent)
} else if (parentFragment != null) {
parentFragment?.startActivityForResult(intent, requestCode)
} else {
activity?.startActivityForResult(intent, requestCode)
when {
targetFragment != null -> {
targetFragment?.startActivityForResult(intent, targetRequestCode)
}
requestCode == 0 -> {
startActivity(intent)
}
parentFragment != null -> {
parentFragment?.startActivityForResult(intent, requestCode)
}
else -> {
activity?.startActivityForResult(intent, requestCode)
}
}
}

View File

@ -113,12 +113,16 @@ class GroupFragment : AbsToolbarTabPagesFragment(), LoaderCallbacks<SingleRespon
val twitter = MicroBlogAPIFactory.getInstance(context, accountKey) ?:
throw MicroBlogException("No account")
val group: Group
group = if (groupId != null) {
twitter.showGroup(groupId)
} else if (groupName != null) {
twitter.showGroupByName(groupName)
} else {
return SingleResponse()
group = when {
groupId != null -> {
twitter.showGroup(groupId)
}
groupName != null -> {
twitter.showGroupByName(groupName)
}
else -> {
return SingleResponse()
}
}
return SingleResponse.getInstance(ParcelableGroupUtils.from(group, accountKey, 0,
group.isMember))

View File

@ -48,12 +48,16 @@ class SettingsDetailsFragment : BasePreferenceFragment(), OnSharedPreferenceChan
val args = arguments
val rawResId = args?.get(EXTRA_RESID)
val resId: Int
resId = if (rawResId is Int) {
rawResId
} else if (rawResId is String) {
Utils.getResId(activity, rawResId)
} else {
0
resId = when (rawResId) {
is Int -> {
rawResId
}
is String -> {
Utils.getResId(activity, rawResId)
}
else -> {
0
}
}
if (resId != 0) {
addPreferencesFromResource(resId)
@ -81,12 +85,16 @@ class SettingsDetailsFragment : BasePreferenceFragment(), OnSharedPreferenceChan
val currentActivity = activity ?: return
val extras = preference.extras
if (extras != null) {
if (extras.containsKey(EXTRA_SHOULD_RESTART)) {
SettingsActivity.setShouldRestart(currentActivity)
} else if (extras.containsKey(EXTRA_SHOULD_RECREATE)) {
SettingsActivity.setShouldRecreate(currentActivity)
} else if (extras.containsKey(EXTRA_SHOULD_TERMINATE)) {
SettingsActivity.setShouldTerminate(currentActivity)
when {
extras.containsKey(EXTRA_SHOULD_RESTART) -> {
SettingsActivity.setShouldRestart(currentActivity)
}
extras.containsKey(EXTRA_SHOULD_RECREATE) -> {
SettingsActivity.setShouldRecreate(currentActivity)
}
extras.containsKey(EXTRA_SHOULD_TERMINATE) -> {
SettingsActivity.setShouldTerminate(currentActivity)
}
}
if (extras.containsKey(EXTRA_RECREATE_ACTIVITY)) {
currentActivity.recreate()

View File

@ -244,38 +244,42 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
override fun onLoadFinished(loader: Loader<SingleResponse<ParcelableUser>>,
data: SingleResponse<ParcelableUser>) {
val activity = activity ?: return
if (data.data != null) {
val user = data.data
cardContent.visibility = View.VISIBLE
errorContainer.visibility = View.GONE
progressContainer.visibility = View.GONE
val account: AccountDetails = data.extras.getParcelable(EXTRA_ACCOUNT)!!
displayUser(user, account)
if (user.is_cache) {
val args = Bundle()
args.putParcelable(EXTRA_ACCOUNT_KEY, user.account_key)
args.putParcelable(EXTRA_USER_KEY, user.key)
args.putString(EXTRA_SCREEN_NAME, user.screen_name)
args.putBoolean(EXTRA_OMIT_INTENT_EXTRA, true)
loaderManager.restartLoader(LOADER_ID_USER, args, this)
when {
data.data != null -> {
val user = data.data
cardContent.visibility = View.VISIBLE
errorContainer.visibility = View.GONE
progressContainer.visibility = View.GONE
val account: AccountDetails = data.extras.getParcelable(EXTRA_ACCOUNT)!!
displayUser(user, account)
if (user.is_cache) {
val args = Bundle()
args.putParcelable(EXTRA_ACCOUNT_KEY, user.account_key)
args.putParcelable(EXTRA_USER_KEY, user.key)
args.putString(EXTRA_SCREEN_NAME, user.screen_name)
args.putBoolean(EXTRA_OMIT_INTENT_EXTRA, true)
loaderManager.restartLoader(LOADER_ID_USER, args, this)
}
updateOptionsMenuVisibility()
}
updateOptionsMenuVisibility()
} else if (user?.is_cache == true) {
cardContent.visibility = View.VISIBLE
errorContainer.visibility = View.GONE
progressContainer.visibility = View.GONE
displayUser(user, account)
updateOptionsMenuVisibility()
} else {
if (data.hasException()) {
errorText.text = data.exception?.getErrorMessage(activity)
errorText.visibility = View.VISIBLE
user?.is_cache == true -> {
cardContent.visibility = View.VISIBLE
errorContainer.visibility = View.GONE
progressContainer.visibility = View.GONE
displayUser(user, account)
updateOptionsMenuVisibility()
}
else -> {
if (data.hasException()) {
errorText.text = data.exception?.getErrorMessage(activity)
errorText.visibility = View.VISIBLE
}
cardContent.visibility = View.GONE
errorContainer.visibility = View.VISIBLE
progressContainer.visibility = View.GONE
displayUser(null, null)
updateOptionsMenuVisibility()
}
cardContent.visibility = View.GONE
errorContainer.visibility = View.VISIBLE
progressContainer.visibility = View.GONE
displayUser(null, null)
updateOptionsMenuVisibility()
}
}
@ -495,13 +499,17 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
listedContainer.visibility = if (user.listed_count < 0) View.GONE else View.VISIBLE
groupsContainer.visibility = if (user.groups_count < 0) View.GONE else View.VISIBLE
if (user.color != 0) {
setUiColor(user.color)
} else if (user.link_color != 0) {
setUiColor(user.link_color)
} else {
val theme = Chameleon.getOverrideTheme(activity, activity)
setUiColor(theme.colorPrimary)
when {
user.color != 0 -> {
setUiColor(user.color)
}
user.link_color != 0 -> {
setUiColor(user.link_color)
}
else -> {
val theme = Chameleon.getOverrideTheme(activity, activity)
setUiColor(theme.colorPrimary)
}
}
val defWidth = resources.displayMetrics.widthPixels
val width = if (bannerWidth > 0) bannerWidth else defWidth
@ -1227,14 +1235,19 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
val userRelationship = relationship
val twitter = twitterWrapper
if (userRelationship == null) return
if (userRelationship.blocking) {
twitter.destroyBlockAsync(accountKey, user.key)
} else if (userRelationship.blocked_by) {
CreateUserBlockDialogFragment.show(childFragmentManager, user)
} else if (userRelationship.following) {
DestroyFriendshipDialogFragment.show(fragmentManager, user)
} else {
twitter.createFriendshipAsync(accountKey, user.key, user.screen_name)
when {
userRelationship.blocking -> {
twitter.destroyBlockAsync(accountKey, user.key)
}
userRelationship.blocked_by -> {
CreateUserBlockDialogFragment.show(childFragmentManager, user)
}
userRelationship.following -> {
DestroyFriendshipDialogFragment.show(fragmentManager, user)
}
else -> {
twitter.createFriendshipAsync(accountKey, user.key, user.screen_name)
}
}
}
}

View File

@ -49,12 +49,16 @@ class GroupTimelineFragment : ParcelableStatusesFragment() {
val result = ArrayList<String>()
result.add(AUTHORITY_GROUP_TIMELINE)
result.add("account=$accountKey")
if (groupId != null) {
result.add("group_id=$groupId")
} else if (groupName != null) {
result.add("group_name=$groupName")
} else {
return null
when {
groupId != null -> {
result.add("group_id=$groupId")
}
groupName != null -> {
result.add("group_name=$groupName")
}
else -> {
return null
}
}
return result.toTypedArray()
}

View File

@ -46,12 +46,16 @@ class UserFavoritesFragment : ParcelableStatusesFragment() {
val result = ArrayList<String>()
result.add(AUTHORITY_USER_FAVORITES)
result.add("account=$accountKey")
if (userKey != null) {
result.add("user_id=$userKey")
} else if (screenName != null) {
result.add("screen_name=$screenName")
} else {
return null
when {
userKey != null -> {
result.add("user_id=$userKey")
}
screenName != null -> {
result.add("screen_name=$screenName")
}
else -> {
return null
}
}
return result.toTypedArray()
}
@ -65,12 +69,16 @@ class UserFavoritesFragment : ParcelableStatusesFragment() {
val userKey = arguments.getParcelable<UserKey>(EXTRA_USER_KEY)
val screenName = arguments.getString(EXTRA_SCREEN_NAME)
if (userKey != null) {
sb.append(userKey)
} else if (screenName != null) {
sb.append(screenName)
} else {
return null
when {
userKey != null -> {
sb.append(userKey)
}
screenName != null -> {
sb.append(screenName)
}
else -> {
return null
}
}
return sb.toString()
}

View File

@ -49,17 +49,21 @@ class UserListTimelineFragment : ParcelableStatusesFragment() {
val result = ArrayList<String>()
result.add(TwidereConstants.AUTHORITY_USER_LIST_TIMELINE)
result.add("account=$accountKey")
if (listId != null) {
result.add("list_id=$listId")
} else if (listName != null) {
if (userKey != null) {
result.add("user_id=$userKey")
} else if (screenName != null) {
result.add("screen_name=$screenName")
when {
listId != null -> {
result.add("list_id=$listId")
}
listName != null -> {
if (userKey != null) {
result.add("user_id=$userKey")
} else if (screenName != null) {
result.add("screen_name=$screenName")
}
return null
}
else -> {
return null
}
return null
} else {
return null
}
return result.toTypedArray()
}
@ -72,22 +76,30 @@ class UserListTimelineFragment : ParcelableStatusesFragment() {
if (tabPosition < 0) return null
val listId = arguments.getString(EXTRA_LIST_ID)
val listName = arguments.getString(EXTRA_LIST_NAME)
if (listId != null) {
sb.append(listId)
} else if (listName != null) {
val userKey = arguments.getParcelable<UserKey?>(EXTRA_USER_KEY)
val screenName = arguments.getString(EXTRA_SCREEN_NAME)
if (userKey != null) {
sb.append(userKey)
} else if (screenName != null) {
sb.append(screenName)
} else {
when {
listId != null -> {
sb.append(listId)
}
listName != null -> {
val userKey = arguments.getParcelable<UserKey?>(EXTRA_USER_KEY)
val screenName = arguments.getString(EXTRA_SCREEN_NAME)
when {
userKey != null -> {
sb.append(userKey)
}
screenName != null -> {
sb.append(screenName)
}
else -> {
return null
}
}
sb.append('_')
sb.append(listName)
}
else -> {
return null
}
sb.append('_')
sb.append(listName)
} else {
return null
}
return sb.toString()
}

View File

@ -61,12 +61,16 @@ class UserTimelineFragment : ParcelableStatusesFragment() {
val result = ArrayList<String>()
result.add(AUTHORITY_USER_TIMELINE)
result.add("account=$accountKey")
if (userKey != null) {
result.add("user_id=$userKey")
} else if (screenName != null) {
result.add("screen_name=$screenName")
} else {
return null
when {
userKey != null -> {
result.add("user_id=$userKey")
}
screenName != null -> {
result.add("screen_name=$screenName")
}
else -> {
return null
}
}
(timelineFilter as? UserTimelineFilter)?.let {
if (it.isIncludeReplies) {
@ -87,12 +91,16 @@ class UserTimelineFragment : ParcelableStatusesFragment() {
val userKey = arguments.getParcelable<UserKey>(EXTRA_USER_KEY)
val screenName = arguments.getString(EXTRA_SCREEN_NAME)
if (userKey != null) {
sb.append(userKey)
} else if (screenName != null) {
sb.append(screenName)
} else {
return null
when {
userKey != null -> {
sb.append(userKey)
}
screenName != null -> {
sb.append(screenName)
}
else -> {
return null
}
}
return sb.toString()
}

View File

@ -140,20 +140,24 @@ class UserTimelineLoader(
option.setExcludeReplies(!timelineFilter.isIncludeReplies)
option.setIncludeRetweets(timelineFilter.isIncludeRetweets)
}
if (userKey != null) {
if (account.type == AccountType.STATUSNET && userKey.host != account.key.host
when {
userKey != null -> {
if (account.type == AccountType.STATUSNET && userKey.host != account.key.host
&& profileUrl != null) {
try {
return showStatusNetExternalTimeline(profileUrl, paging)
} catch (e: IOException) {
throw MicroBlogException(e)
try {
return showStatusNetExternalTimeline(profileUrl, paging)
} catch (e: IOException) {
throw MicroBlogException(e)
}
}
return microBlog.getUserTimeline(userKey.id, paging, option)
}
screenName != null -> {
return microBlog.getUserTimelineByScreenName(screenName, paging, option)
}
else -> {
throw MicroBlogException("Invalid user")
}
return microBlog.getUserTimeline(userKey.id, paging, option)
} else if (screenName != null) {
return microBlog.getUserTimelineByScreenName(screenName, paging, option)
} else {
throw MicroBlogException("Invalid user")
}
}

View File

@ -229,22 +229,26 @@ class ActivityTitleSummaryMessage private constructor(val icon: Int, val color:
nameFirst))
firstDisplayName.setSpan(StyleSpan(Typeface.BOLD), 0, firstDisplayName.length,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
if (sources.size == 1) {
val format = resources.getString(stringRes)
return SpanFormatter.format(format, firstDisplayName)
} else if (sources.size == 2) {
val format = resources.getString(stringResMulti)
val secondDisplayName = SpannableString(manager.getDisplayName(sources[1],
when (sources.size) {
1 -> {
val format = resources.getString(stringRes)
return SpanFormatter.format(format, firstDisplayName)
}
2 -> {
val format = resources.getString(stringResMulti)
val secondDisplayName = SpannableString(manager.getDisplayName(sources[1],
nameFirst))
secondDisplayName.setSpan(StyleSpan(Typeface.BOLD), 0, secondDisplayName.length,
secondDisplayName.setSpan(StyleSpan(Typeface.BOLD), 0, secondDisplayName.length,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
return SpanFormatter.format(format, firstDisplayName,
return SpanFormatter.format(format, firstDisplayName,
secondDisplayName)
} else {
val othersCount = sources.size - 1
val nOthers = resources.getQuantityString(R.plurals.N_others, othersCount, othersCount)
val format = resources.getString(stringResMulti)
return SpanFormatter.format(format, firstDisplayName, nOthers)
}
else -> {
val othersCount = sources.size - 1
val nOthers = resources.getQuantityString(R.plurals.N_others, othersCount, othersCount)
val format = resources.getString(stringResMulti)
return SpanFormatter.format(format, firstDisplayName, nOthers)
}
}
}
}

View File

@ -414,13 +414,17 @@ class TwidereDataProvider : ContentProvider(), LazyLoadCallback {
}
else -> {
val conflictAlgorithm = getConflictAlgorithm(tableId)
rowId = if (conflictAlgorithm != SQLiteDatabase.CONFLICT_NONE) {
databaseWrapper.insertWithOnConflict(table, null, values,
conflictAlgorithm)
} else if (table != null) {
databaseWrapper.insert(table, null, values)
} else {
return null
rowId = when {
conflictAlgorithm != SQLiteDatabase.CONFLICT_NONE -> {
databaseWrapper.insertWithOnConflict(table, null, values,
conflictAlgorithm)
}
table != null -> {
databaseWrapper.insert(table, null, values)
}
else -> {
return null
}
}
}
}

View File

@ -119,12 +119,16 @@ class HtmlBuilder(
}
private fun appendSource(builder: StringBuilder, start: Int, end: Int, escapeSource: Boolean, sourceEscaped: Boolean) {
if (sourceEscaped == escapeSource) {
builder.append(source.substring(start, end), escapeSource, sourceEscaped)
} else if (escapeSource) {
builder.append(HtmlEscapeHelper.escape(source.substring(start, end)), true, sourceEscaped)
} else {
builder.append(HtmlEscapeHelper.unescape(source.substring(start, end)), false, sourceEscaped)
when {
sourceEscaped == escapeSource -> {
builder.append(source.substring(start, end), escapeSource, sourceEscaped)
}
escapeSource -> {
builder.append(HtmlEscapeHelper.escape(source.substring(start, end)), true, sourceEscaped)
}
else -> {
builder.append(HtmlEscapeHelper.unescape(source.substring(start, end)), false, sourceEscaped)
}
}
}
@ -166,12 +170,16 @@ class HtmlBuilder(
companion object {
private fun StringBuilder.append(text: String, escapeText: Boolean, textEscaped: Boolean) {
if (textEscaped == escapeText) {
append(text)
} else if (escapeText) {
append(HtmlEscapeHelper.escape(text))
} else {
append(HtmlEscapeHelper.unescape(text))
when {
textEscaped == escapeText -> {
append(text)
}
escapeText -> {
append(HtmlEscapeHelper.escape(text))
}
else -> {
append(HtmlEscapeHelper.unescape(text))
}
}
}
}

View File

@ -125,13 +125,17 @@ object MenuUtils {
val favoriteHighlight = ContextCompat.getColor(context, R.color.highlight_favorite)
val likeHighlight = ContextCompat.getColor(context, R.color.highlight_like)
val isMyRetweet: Boolean =
if (RetweetStatusTask.isCreatingRetweet(status.account_key, status.id)) {
true
} else if (twitter.isDestroyingStatus(status.account_key, status.id)) {
false
} else {
status.retweeted || Utils.isMyRetweet(status)
}
when {
RetweetStatusTask.isCreatingRetweet(status.account_key, status.id) -> {
true
}
twitter.isDestroyingStatus(status.account_key, status.id) -> {
false
}
else -> {
status.retweeted || Utils.isMyRetweet(status)
}
}
val isMyStatus = Utils.isMyStatus(status)
menu.setItemAvailability(R.id.delete, isMyStatus)
if (isMyStatus) {
@ -165,13 +169,17 @@ object MenuUtils {
val favorite = menu.findItem(R.id.favorite)
if (favorite != null) {
val isFavorite: Boolean =
if (CreateFavoriteTask.isCreatingFavorite(status.account_key, status.id)) {
true
} else if (DestroyFavoriteTask.isDestroyingFavorite(status.account_key, status.id)) {
false
} else {
status.is_favorite
}
when {
CreateFavoriteTask.isCreatingFavorite(status.account_key, status.id) -> {
true
}
DestroyFavoriteTask.isDestroyingFavorite(status.account_key, status.id) -> {
false
}
else -> {
status.is_favorite
}
}
val provider = MenuItemCompat.getActionProvider(favorite)
val useStar = preferences[iWantMyStarsBackKey]
if (provider is FavoriteItemProvider) {
@ -205,20 +213,25 @@ object MenuUtils {
INTENT_ACTION_EXTENSION_OPEN_STATUS, EXTRA_STATUS, EXTRA_STATUS_JSON, status)
val shareItem = menu.findItem(R.id.share)
val shareProvider = MenuItemCompat.getActionProvider(shareItem)
if (shareProvider is SupportStatusShareProvider) {
shareProvider.status = status
} else if (shareProvider is ShareActionProvider) {
val shareIntent = Utils.createStatusShareIntent(context, status)
shareProvider.setShareIntent(shareIntent)
} else if (shareItem.hasSubMenu()) {
val shareSubMenu = shareItem.subMenu
val shareIntent = Utils.createStatusShareIntent(context, status)
shareSubMenu.removeGroup(MENU_GROUP_STATUS_SHARE)
addIntentToMenu(context, shareSubMenu, shareIntent, MENU_GROUP_STATUS_SHARE)
} else {
val shareIntent = Utils.createStatusShareIntent(context, status)
val chooserIntent = Intent.createChooser(shareIntent, context.getString(R.string.share_status))
shareItem.intent = chooserIntent
when {
shareProvider is SupportStatusShareProvider -> {
shareProvider.status = status
}
shareProvider is ShareActionProvider -> {
val shareIntent = Utils.createStatusShareIntent(context, status)
shareProvider.setShareIntent(shareIntent)
}
shareItem.hasSubMenu() -> {
val shareSubMenu = shareItem.subMenu
val shareIntent = Utils.createStatusShareIntent(context, status)
shareSubMenu.removeGroup(MENU_GROUP_STATUS_SHARE)
addIntentToMenu(context, shareSubMenu, shareIntent, MENU_GROUP_STATUS_SHARE)
}
else -> {
val shareIntent = Utils.createStatusShareIntent(context, status)
val chooserIntent = Intent.createChooser(shareIntent, context.getString(R.string.share_status))
shareItem.intent = chooserIntent
}
}
}
@ -233,19 +246,23 @@ object MenuUtils {
}
}
R.id.retweet -> {
if (fragment is BaseFragment) {
fragment.executeAfterFragmentResumed {
RetweetQuoteDialogFragment.show(it.childFragmentManager, status.account_key,
when {
fragment is BaseFragment -> {
fragment.executeAfterFragmentResumed {
RetweetQuoteDialogFragment.show(it.childFragmentManager, status.account_key,
status.id, status)
}
}
} else if (context is BaseActivity) {
context.executeAfterFragmentResumed {
RetweetQuoteDialogFragment.show(it.supportFragmentManager, status.account_key,
context is BaseActivity -> {
context.executeAfterFragmentResumed {
RetweetQuoteDialogFragment.show(it.supportFragmentManager, status.account_key,
status.id, status)
}
}
} else {
RetweetQuoteDialogFragment.show(fm, status.account_key,
else -> {
RetweetQuoteDialogFragment.show(fm, status.account_key,
status.id, status)
}
}
}
R.id.quote -> {
@ -260,19 +277,23 @@ object MenuUtils {
}
R.id.favorite -> {
if (preferences[favoriteConfirmationKey]) {
if (fragment is BaseFragment) {
fragment.executeAfterFragmentResumed {
FavoriteConfirmDialogFragment.show(it.childFragmentManager,
when {
fragment is BaseFragment -> {
fragment.executeAfterFragmentResumed {
FavoriteConfirmDialogFragment.show(it.childFragmentManager,
status.account_key, status.id, status)
}
}
} else if (context is BaseActivity) {
context.executeAfterFragmentResumed {
FavoriteConfirmDialogFragment.show(it.supportFragmentManager,
context is BaseActivity -> {
context.executeAfterFragmentResumed {
FavoriteConfirmDialogFragment.show(it.supportFragmentManager,
status.account_key, status.id, status)
}
}
} else {
FavoriteConfirmDialogFragment.show(fm, status.account_key, status.id,
else -> {
FavoriteConfirmDialogFragment.show(fm, status.account_key, status.id,
status)
}
}
} else if (status.is_favorite) {
twitter.destroyFavoriteAsync(status.account_key, status.id)

View File

@ -116,12 +116,16 @@ object ThemeUtils {
fun getCardBackgroundColor(context: Context, backgroundOption: String, themeAlpha: Int): Int {
val color = getColorFromAttribute(context, R.attr.cardItemBackgroundColor)
return if (isTransparentBackground(backgroundOption)) {
ColorUtils.setAlphaComponent(color, themeAlpha)
} else if (isSolidBackground(backgroundOption)) {
TwidereColorUtils.getContrastYIQ(color, Color.WHITE, Color.BLACK)
} else {
color
return when {
isTransparentBackground(backgroundOption) -> {
ColorUtils.setAlphaComponent(color, themeAlpha)
}
isSolidBackground(backgroundOption) -> {
TwidereColorUtils.getContrastYIQ(color, Color.WHITE, Color.BLACK)
}
else -> {
color
}
}
}
@ -163,15 +167,20 @@ object ThemeUtils {
}
fun applyWindowBackground(context: Context, window: Window, backgroundOption: String, alpha: Int) {
if (isWindowFloating(context)) {
window.setBackgroundDrawable(getWindowBackground(context))
} else if (VALUE_THEME_BACKGROUND_TRANSPARENT == backgroundOption) {
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER)
window.setBackgroundDrawable(getWindowBackgroundFromThemeApplyAlpha(context, alpha))
} else if (VALUE_THEME_BACKGROUND_SOLID == backgroundOption) {
window.setBackgroundDrawable(ColorDrawable(if (isLightTheme(context)) Color.WHITE else Color.BLACK))
} else {
window.setBackgroundDrawable(getWindowBackground(context))
when {
isWindowFloating(context) -> {
window.setBackgroundDrawable(getWindowBackground(context))
}
VALUE_THEME_BACKGROUND_TRANSPARENT == backgroundOption -> {
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER)
window.setBackgroundDrawable(getWindowBackgroundFromThemeApplyAlpha(context, alpha))
}
VALUE_THEME_BACKGROUND_SOLID == backgroundOption -> {
window.setBackgroundDrawable(ColorDrawable(if (isLightTheme(context)) Color.WHITE else Color.BLACK))
}
else -> {
window.setBackgroundDrawable(getWindowBackground(context))
}
}
}

View File

@ -160,25 +160,29 @@ object Utils {
fun getAccountKeys(context: Context, args: Bundle?): Array<UserKey>? {
if (args == null) return null
if (args.containsKey(EXTRA_ACCOUNT_KEYS)) {
return args.getNullableTypedArray(EXTRA_ACCOUNT_KEYS)
} else if (args.containsKey(EXTRA_ACCOUNT_KEY)) {
val accountKey = args.getParcelable<UserKey>(EXTRA_ACCOUNT_KEY) ?: return emptyArray()
return arrayOf(accountKey)
} else if (args.containsKey(EXTRA_ACCOUNT_ID)) {
val accountId = args.get(EXTRA_ACCOUNT_ID).toString()
try {
if (java.lang.Long.parseLong(accountId) <= 0) return null
} catch (e: NumberFormatException) {
// Ignore
when {
args.containsKey(EXTRA_ACCOUNT_KEYS) -> {
return args.getNullableTypedArray(EXTRA_ACCOUNT_KEYS)
}
args.containsKey(EXTRA_ACCOUNT_KEY) -> {
val accountKey = args.getParcelable<UserKey>(EXTRA_ACCOUNT_KEY) ?: return emptyArray()
return arrayOf(accountKey)
}
args.containsKey(EXTRA_ACCOUNT_ID) -> {
val accountId = args.get(EXTRA_ACCOUNT_ID).toString()
try {
if (java.lang.Long.parseLong(accountId) <= 0) return null
} catch (e: NumberFormatException) {
// Ignore
}
val accountKey = DataStoreUtils.findAccountKey(context, accountId)
args.putParcelable(EXTRA_ACCOUNT_KEY, accountKey)
if (accountKey == null) return arrayOf(UserKey(accountId, null))
return arrayOf(accountKey)
val accountKey = DataStoreUtils.findAccountKey(context, accountId)
args.putParcelable(EXTRA_ACCOUNT_KEY, accountKey)
if (accountKey == null) return arrayOf(UserKey(accountId, null))
return arrayOf(accountKey)
}
else -> return null
}
return null
}
fun getAccountKey(context: Context, args: Bundle?): UserKey? {
@ -456,12 +460,16 @@ object Utils {
}
fun getInsetsTopWithoutActionBarHeight(context: Context, top: Int): Int {
val actionBarHeight: Int = if (context is AppCompatActivity) {
getActionBarHeight(context.supportActionBar)
} else if (context is Activity) {
getActionBarHeight(context.actionBar)
} else {
return top
val actionBarHeight: Int = when (context) {
is AppCompatActivity -> {
getActionBarHeight(context.supportActionBar)
}
is Activity -> {
getActionBarHeight(context.actionBar)
}
else -> {
return top
}
}
if (actionBarHeight > top) {
return top

View File

@ -35,12 +35,16 @@ import java.io.IOException
object TwidereExceptionFactory : ExceptionFactory<MicroBlogException> {
override fun newException(cause: Throwable?, request: HttpRequest?, response: HttpResponse?): MicroBlogException {
val te = if (cause != null) {
MicroBlogException(cause)
} else if (response != null) {
parseTwitterException(response)
} else {
MicroBlogException()
val te = when {
cause != null -> {
MicroBlogException(cause)
}
response != null -> {
parseTwitterException(response)
}
else -> {
MicroBlogException()
}
}
te.httpRequest = request
te.httpResponse = response

View File

@ -123,16 +123,20 @@ class ContentNotificationManager(
val displayName = userColorNameManager.getDisplayName(userCursor.getString(userIndices[Statuses.USER_KEY]),
userCursor.getString(userIndices[Statuses.USER_NAME]), userCursor.getString(userIndices[Statuses.USER_SCREEN_NAME]),
nameFirst)
notificationContent = if (usersCount == 1) {
context.getString(R.string.from_name, displayName)
} else if (usersCount == 2) {
userCursor.moveToPosition(1)
val othersName = userColorNameManager.getDisplayName(userCursor.getString(userIndices[Statuses.USER_KEY]),
userCursor.getString(userIndices[Statuses.USER_NAME]), userCursor.getString(userIndices[Statuses.USER_SCREEN_NAME]),
nameFirst)
resources.getString(R.string.from_name_and_name, displayName, othersName)
} else {
resources.getString(R.string.from_name_and_N_others, displayName, usersCount - 1)
notificationContent = when (usersCount) {
1 -> {
context.getString(R.string.from_name, displayName)
}
2 -> {
userCursor.moveToPosition(1)
val othersName = userColorNameManager.getDisplayName(userCursor.getString(userIndices[Statuses.USER_KEY]),
userCursor.getString(userIndices[Statuses.USER_NAME]), userCursor.getString(userIndices[Statuses.USER_SCREEN_NAME]),
nameFirst)
resources.getString(R.string.from_name_and_name, displayName, othersName)
}
else -> {
resources.getString(R.string.from_name_and_N_others, displayName, usersCount - 1)
}
}
// Setup notification

View File

@ -72,20 +72,25 @@ abstract class FileBasedDraftsSyncAction<RemoteFileInfo>(val context: Context) :
remoteDrafts.forEach { remoteDraft ->
val localDraft = localDrafts.find { it.filename == remoteDraft.draftFileName }
if (remoteDraft.draftFileName.substringBefore(".eml") in localRemovedIds) {
// Local removed, remove remote
removeRemoteInfoList.add(remoteDraft)
} else if (localDraft == null) {
// Local doesn't exist, download remote
downloadRemoteInfoList.add(remoteDraft)
} else if (remoteDraft.draftTimestamp - localDraft.timestamp > 1000) {
// Local is older, update from remote
localDraft.remote_extras = remoteDraft.draftRemoteExtras
updateLocalInfoList[localDraft._id] = remoteDraft
} else if (localDraft.timestamp - remoteDraft.draftTimestamp > 1000) {
// Local is newer, upload local
localDraft.remote_extras = remoteDraft.draftRemoteExtras
uploadLocalList.add(localDraft)
when {
remoteDraft.draftFileName.substringBefore(".eml") in localRemovedIds -> {
// Local removed, remove remote
removeRemoteInfoList.add(remoteDraft)
}
localDraft == null -> {
// Local doesn't exist, download remote
downloadRemoteInfoList.add(remoteDraft)
}
remoteDraft.draftTimestamp - localDraft.timestamp > 1000 -> {
// Local is older, update from remote
localDraft.remote_extras = remoteDraft.draftRemoteExtras
updateLocalInfoList[localDraft._id] = remoteDraft
}
localDraft.timestamp - remoteDraft.draftTimestamp > 1000 -> {
// Local is newer, upload local
localDraft.remote_extras = remoteDraft.draftRemoteExtras
uploadLocalList.add(localDraft)
}
}
}

View File

@ -53,14 +53,18 @@ abstract class TwitterCardViewFactory {
private fun createCardFragment(status: ParcelableStatus): ContainerView.ViewController? {
val card = status.card
if (card?.name == null) return null
if (TwitterCardUtils.CARD_NAME_PLAYER == card.name) {
return createGenericPlayerFragment(card)
} else if (TwitterCardUtils.CARD_NAME_AUDIO == card.name) {
return createGenericPlayerFragment(card)
} else if (TwitterCardUtils.isPoll(card)) {
return createCardPollFragment(status)
return when {
TwitterCardUtils.CARD_NAME_PLAYER == card.name -> {
createGenericPlayerFragment(card)
}
TwitterCardUtils.CARD_NAME_AUDIO == card.name -> {
createGenericPlayerFragment(card)
}
TwitterCardUtils.isPoll(card) -> {
createCardPollFragment(status)
}
else -> null
}
return null
}

View File

@ -97,12 +97,16 @@ class ActionIconThemedTextView(
for (d in TextViewSupport.getCompoundDrawablesRelative(this)) {
if (d == null) continue
d.mutate()
val color: Int = if (isActivated) {
activatedColor
} else if (isEnabled) {
defaultColor
} else {
disabledColor
val color: Int = when {
isActivated -> {
activatedColor
}
isEnabled -> {
defaultColor
}
else -> {
disabledColor
}
}
if (iconWidth > 0 && iconHeight > 0) {

View File

@ -65,14 +65,18 @@ class CardMediaContainer(context: Context, attrs: AttributeSet? = null) : ViewGr
val k = imageRes.size
for (i in 0 until childCount) {
val child = getChildAt(i)
if (child !is ImageView) {
child.visibility = View.GONE
} else if (i < k) {
child.setImageResource(imageRes[i])
child.visibility = View.VISIBLE
} else {
child.setImageDrawable(null)
child.visibility = View.GONE
when {
child !is ImageView -> {
child.visibility = View.GONE
}
i < k -> {
child.setImageResource(imageRes[i])
child.visibility = View.VISIBLE
}
else -> {
child.setImageDrawable(null)
child.visibility = View.GONE
}
}
}
}
@ -159,12 +163,16 @@ class CardMediaContainer(context: Context, attrs: AttributeSet? = null) : ViewGr
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
val childCount = rebuildChildInfo()
if (childCount > 0) {
if (childCount == 1) {
layout1Media(childIndices)
} else if (childCount == 3) {
layout3Media(horizontalSpacing, verticalSpacing, childIndices)
} else {
layoutGridMedia(childCount, 2, horizontalSpacing, verticalSpacing, childIndices)
when (childCount) {
1 -> {
layout1Media(childIndices)
}
3 -> {
layout3Media(horizontalSpacing, verticalSpacing, childIndices)
}
else -> {
layoutGridMedia(childCount, 2, horizontalSpacing, verticalSpacing, childIndices)
}
}
}
}
@ -182,16 +190,21 @@ class CardMediaContainer(context: Context, attrs: AttributeSet? = null) : ViewGr
val childCount = rebuildChildInfo()
var heightSum = 0
if (childCount > 0) {
heightSum = if (childCount == 1) {
measure1Media(contentWidth, childIndices, ratioMultiplier)
} else if (childCount == 2) {
measureGridMedia(childCount, 2, contentWidth, ratioMultiplier, horizontalSpacing,
verticalSpacing, childIndices)
} else if (childCount == 3) {
measure3Media(contentWidth, horizontalSpacing, childIndices, ratioMultiplier)
} else {
measureGridMedia(childCount, 2, contentWidth,
WIDTH_HEIGHT_RATIO * ratioMultiplier, horizontalSpacing, verticalSpacing, childIndices)
heightSum = when (childCount) {
1 -> {
measure1Media(contentWidth, childIndices, ratioMultiplier)
}
2 -> {
measureGridMedia(childCount, 2, contentWidth, ratioMultiplier, horizontalSpacing,
verticalSpacing, childIndices)
}
3 -> {
measure3Media(contentWidth, horizontalSpacing, childIndices, ratioMultiplier)
}
else -> {
measureGridMedia(childCount, 2, contentWidth,
WIDTH_HEIGHT_RATIO * ratioMultiplier, horizontalSpacing, verticalSpacing, childIndices)
}
}
if (contentHeight > 0) {
heightSum = contentHeight

View File

@ -111,12 +111,16 @@ class IconActionButton(
fun IIconActionButton.updateColorFilter() {
this as ImageView
if (isActivated) {
setColorFilter(activatedColor)
} else if (isEnabled) {
setColorFilter(defaultColor)
} else {
setColorFilter(disabledColor)
when {
isActivated -> {
setColorFilter(activatedColor)
}
isEnabled -> {
setColorFilter(defaultColor)
}
else -> {
setColorFilter(disabledColor)
}
}
}
}

View File

@ -76,12 +76,16 @@ class DraftViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
} else {
contentView.drawEnd()
}
if (summaryText != null) {
textView.spannable = summaryText
} else if (draft.text.isNullOrEmpty()) {
textView.setText(R.string.empty_content)
} else {
textView.spannable = draft.text
when {
summaryText != null -> {
textView.spannable = summaryText
}
draft.text.isNullOrEmpty() -> {
textView.setText(R.string.empty_content)
}
else -> {
textView.spannable = draft.text
}
}
if (draft.timestamp > 0) {

View File

@ -167,18 +167,22 @@ class DetailStatusViewHolder(
val quotedMedia = status.quoted_media
if (quotedMedia?.isEmpty() != false) {
itemView.quotedMediaLabel.visibility = View.GONE
itemView.quotedMediaPreview.visibility = View.GONE
} else if (adapter.isDetailMediaExpanded) {
itemView.quotedMediaLabel.visibility = View.GONE
itemView.quotedMediaPreview.visibility = View.VISIBLE
itemView.quotedMediaPreview.displayMedia(adapter.requestManager,
when {
quotedMedia?.isEmpty() != false -> {
itemView.quotedMediaLabel.visibility = View.GONE
itemView.quotedMediaPreview.visibility = View.GONE
}
adapter.isDetailMediaExpanded -> {
itemView.quotedMediaLabel.visibility = View.GONE
itemView.quotedMediaPreview.visibility = View.VISIBLE
itemView.quotedMediaPreview.displayMedia(adapter.requestManager,
media = quotedMedia, accountKey = status.account_key,
mediaClickListener = adapter.fragment)
} else {
itemView.quotedMediaLabel.visibility = View.VISIBLE
itemView.quotedMediaPreview.visibility = View.GONE
}
else -> {
itemView.quotedMediaLabel.visibility = View.VISIBLE
itemView.quotedMediaPreview.visibility = View.GONE
}
}
} else {
itemView.quotedName.visibility = View.GONE
@ -299,22 +303,26 @@ class DetailStatusViewHolder(
val media = status.media
if (media?.isEmpty() != false) {
itemView.mediaPreviewContainer.visibility = View.GONE
itemView.mediaPreview.visibility = View.GONE
itemView.mediaPreviewLoad.visibility = View.GONE
itemView.mediaPreview.displayMedia()
} else if (adapter.isDetailMediaExpanded) {
itemView.mediaPreviewContainer.visibility = View.VISIBLE
itemView.mediaPreview.visibility = View.VISIBLE
itemView.mediaPreviewLoad.visibility = View.GONE
itemView.mediaPreview.displayMedia(adapter.requestManager, media = media,
when {
media?.isEmpty() != false -> {
itemView.mediaPreviewContainer.visibility = View.GONE
itemView.mediaPreview.visibility = View.GONE
itemView.mediaPreviewLoad.visibility = View.GONE
itemView.mediaPreview.displayMedia()
}
adapter.isDetailMediaExpanded -> {
itemView.mediaPreviewContainer.visibility = View.VISIBLE
itemView.mediaPreview.visibility = View.VISIBLE
itemView.mediaPreviewLoad.visibility = View.GONE
itemView.mediaPreview.displayMedia(adapter.requestManager, media = media,
accountKey = status.account_key, mediaClickListener = adapter.fragment)
} else {
itemView.mediaPreviewContainer.visibility = View.VISIBLE
itemView.mediaPreview.visibility = View.GONE
itemView.mediaPreviewLoad.visibility = View.VISIBLE
itemView.mediaPreview.displayMedia()
}
else -> {
itemView.mediaPreviewContainer.visibility = View.VISIBLE
itemView.mediaPreview.visibility = View.GONE
itemView.mediaPreviewLoad.visibility = View.VISIBLE
itemView.mediaPreview.displayMedia()
}
}
if (TwitterCardUtils.isCardSupported(status)) {

View File

@ -26,12 +26,16 @@ object AccountsSelectorTransformer : ViewPager.PageTransformer {
internal const val selectorAccountsCount: Int = 3
override fun transformPage(page: View, position: Float) {
if (position < 0) {
page.alpha = 1 + position * selectorAccountsCount
} else if (position > (selectorAccountsCount - 1f) / selectorAccountsCount) {
page.alpha = (1 - position) * selectorAccountsCount
} else {
page.alpha = 1f
when {
position < 0 -> {
page.alpha = 1 + position * selectorAccountsCount
}
position > (selectorAccountsCount - 1f) / selectorAccountsCount -> {
page.alpha = (1 - position) * selectorAccountsCount
}
else -> {
page.alpha = 1f
}
}
}