Use Kotlin math functions

This commit is contained in:
TacoTheDank 2020-06-08 18:50:51 -04:00
parent 4065eddb32
commit 421147b465
40 changed files with 131 additions and 75 deletions

View File

@ -40,5 +40,5 @@ fun InputStream.expectLine(string: String = "", charset: Charset = Charset.defau
fun InputStream.expectBytes(bytes: ByteArray): Boolean {
val readBytes = ByteArray(bytes.size)
read(readBytes)
return Arrays.equals(readBytes, bytes)
return readBytes.contentEquals(bytes)
}

View File

@ -300,7 +300,7 @@ open class BaseActivity : ChameleonActivity(), IBaseActivity<BaseActivity>, IThe
for (i in 0 until handlerFilter.countDataAuthorities()) {
val authorityEntry = handlerFilter.getDataAuthority(i)
val port = authorityEntry.port
intentFilter.addDataAuthority(authorityEntry.host, if (port < 0) null else Integer.toString(port))
intentFilter.addDataAuthority(authorityEntry.host, if (port < 0) null else port.toString())
}
try {
adapter.enableForegroundDispatch(this, intent, arrayOf(intentFilter), null)

View File

@ -113,6 +113,7 @@ import java.text.Normalizer
import java.util.*
import javax.inject.Inject
import kotlin.collections.ArrayList
import kotlin.math.abs
import android.Manifest.permission as AndroidPermission
@SuppressLint("RestrictedApi")
@ -1906,7 +1907,7 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
override fun onChildDraw(c: Canvas, recyclerView: RecyclerView, viewHolder: ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
// Fade out the view as it is swiped out of the parent's bounds
val alpha = ALPHA_FULL - Math.abs(dY) / viewHolder.itemView.height.toFloat()
val alpha = ALPHA_FULL - abs(dY) / viewHolder.itemView.height.toFloat()
viewHolder.itemView.alpha = alpha
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
} else {

View File

@ -107,6 +107,7 @@ import org.mariotaku.twidere.util.premium.ExtraFeaturesService
import org.mariotaku.twidere.view.HomeDrawerLayout
import org.mariotaku.twidere.view.TabPagerIndicator
import java.lang.ref.WeakReference
import kotlin.math.floor
class HomeActivity : BaseActivity(), OnClickListener, OnPageChangeListener, SupportFragmentCallback,
OnLongClickListener, DrawerLayout.DrawerListener {
@ -860,7 +861,7 @@ class HomeActivity : BaseActivity(), OnClickListener, OnPageChangeListener, Supp
"wide" -> resources.getDimension(R.dimen.preferred_tab_column_width_wide)
else -> resources.getDimension(R.dimen.preferred_tab_column_width_normal)
}
mainTabs.columns = Math.floor(1.0 / pagerAdapter.getPageWidth(0)).toInt()
mainTabs.columns = floor(1.0 / pagerAdapter.getPageWidth(0)).toInt()
} else {
mainPager.pageMargin = 0
mainPager.setPageMarginDrawable(null)

View File

@ -74,6 +74,8 @@ import org.mariotaku.twidere.view.viewer.MediaSwipeCloseContainer
import java.io.File
import javax.inject.Inject
import kotlin.concurrent.thread
import kotlin.math.abs
import kotlin.math.roundToInt
import android.Manifest.permission as AndroidPermissions
class MediaViewerActivity : BaseActivity(), IMediaViewerActivity, MediaSwipeCloseContainer.Listener,
@ -145,7 +147,7 @@ class MediaViewerActivity : BaseActivity(), IMediaViewerActivity, MediaSwipeClos
activityLayout.statusBarAlpha = offset
}
try {
actionBar.hideOffset = Math.round(controlBarHeight * (1f - offset))
actionBar.hideOffset = (controlBarHeight * (1f - offset)).roundToInt()
} catch (e: UnsupportedOperationException) {
// Some device will throw this exception
hideOffsetNotSupported = true
@ -408,10 +410,10 @@ class MediaViewerActivity : BaseActivity(), IMediaViewerActivity, MediaSwipeClos
}
override fun onSwipeOffsetChanged(offset: Int) {
val offsetFactor = 1 - (Math.abs(offset).toFloat() / swipeContainer.height)
val offsetFactor = 1 - (abs(offset).toFloat() / swipeContainer.height)
swipeContainer.backgroundAlpha = offsetFactor
val colorToolbar = overrideTheme.colorToolbar
val alpha = Math.round(Color.alpha(colorToolbar) * offsetFactor).coerceIn(0..255)
val alpha = (Color.alpha(colorToolbar) * offsetFactor).roundToInt().coerceIn(0..255)
activityLayout.statusBarAlpha = alpha / 255f
}

View File

@ -54,6 +54,7 @@ import org.mariotaku.twidere.util.DeviceUtils
import org.mariotaku.twidere.util.KeyboardShortcutsHandler
import org.mariotaku.twidere.util.ThemeUtils
import java.util.*
import kotlin.system.exitProcess
class SettingsActivity : BaseActivity(), OnItemClickListener, OnPreferenceStartFragmentCallback {
@ -74,8 +75,7 @@ class SettingsActivity : BaseActivity(), OnItemClickListener, OnPreferenceStartF
shouldTerminate = savedInstanceState.getBoolean(EXTRA_SHOULD_TERMINATE, shouldTerminate)
} else if (intent.getBooleanExtra(EXTRA_SHOULD_TERMINATE, false)) {
finishNoRestart()
System.exit(0)
return
exitProcess(0)
}
val backgroundOption = currentThemeBackgroundOption

View File

@ -31,6 +31,7 @@ import org.mariotaku.twidere.model.AccountDetails
import org.mariotaku.twidere.view.holder.AccountProfileImageViewHolder
import org.mariotaku.twidere.view.transformer.AccountsSelectorTransformer
import java.util.*
import kotlin.math.max
class AccountSelectorAdapter(
private val inflater: LayoutInflater,
@ -115,16 +116,16 @@ class AccountSelectorAdapter(
}
override fun getCount(): Int {
return Math.max(3, accountsCount)
return max(3, accountsCount)
}
val accountStart: Int
get() = Math.max(0, 3 - accountsCount)
get() = max(0, 3 - accountsCount)
val accountsCount: Int
get() {
val accounts = this.accounts ?: return 0
return Math.max(0, accounts.size - 1)
return max(0, accounts.size - 1)
}
override fun getPageWidth(position: Int): Float {

View File

@ -526,7 +526,7 @@ class ParcelableActivitiesAdapter(
result = 31 * result + timestamp.hashCode()
result = 31 * result + gap.hashCode()
result = 31 * result + action.hashCode()
result = 31 * result + (filteredSources?.let { Arrays.hashCode(it) } ?: 0)
result = 31 * result + (filteredSources?.contentHashCode() ?: 0)
return result
}
}

View File

@ -1,6 +1,8 @@
package org.mariotaku.twidere.extension
import android.graphics.BitmapFactory
import kotlin.math.max
import kotlin.math.roundToInt
fun BitmapFactory.Options.calculateInSampleSize(preferredWidth: Int, preferredHeight: Int): Int {
if (preferredHeight > outHeight && preferredWidth > outWidth) {
@ -9,6 +11,7 @@ fun BitmapFactory.Options.calculateInSampleSize(preferredWidth: Int, preferredHe
if (preferredHeight <= 0 && preferredWidth <= 0) {
return 1
}
val result = Math.round(Math.max(outWidth, outHeight) / Math.max(preferredWidth, preferredHeight).toFloat())
return Math.max(1, result)
val result = (max(outWidth, outHeight) / max(preferredWidth, preferredHeight)
.toFloat()).roundToInt()
return max(1, result)
}

View File

@ -15,6 +15,7 @@ import org.mariotaku.twidere.util.InternalTwitterContentUtils
import org.mariotaku.twidere.util.text.FanfouValidator
import org.mariotaku.twidere.util.text.MastodonValidator
import org.mariotaku.twidere.util.text.TwitterValidator
import kotlin.math.min
fun AccountDetails.isOfficial(context: Context?): Boolean {
if (context == null) {
@ -118,7 +119,7 @@ val Array<AccountDetails>.textLimit: Int
limit = if (limit <= 0) {
currentLimit
} else {
Math.min(limit, currentLimit)
min(limit, currentLimit)
}
}
}

View File

@ -24,6 +24,8 @@ import androidx.core.os.LocaleListCompat
import org.mariotaku.ktextension.localesCompat
import org.mariotaku.twidere.model.presentation.LaunchPresentation
import java.util.*
import kotlin.math.abs
import kotlin.math.roundToInt
fun LaunchPresentation.shouldShow(context: Context): Boolean {
// Check language
@ -69,16 +71,16 @@ fun LaunchPresentation.Image.displayingScore(viewDensity: Float, viewWidth: Int,
viewWidth < width && viewHeight < height -> {
val diffW = (width / viewWidth.toFloat() - 1).coerceAtMost(0.5f)
val diffH = (height / viewHeight.toFloat() - 1).coerceAtMost(0.5f)
100 - Math.round(diffH * 100) - Math.round(diffW * 100)
100 - (diffH * 100).roundToInt() - (diffW * 100).roundToInt()
}
else -> {
val diffW = (width / viewWidth.toFloat() - 1).coerceAtMost(0.5f)
val diffH = (height / viewHeight.toFloat() - 1).coerceAtMost(0.5f)
100 - Math.round(diffH * 50) - Math.round(diffW * 50)
100 - (diffH * 50).roundToInt() - (diffW * 50).roundToInt()
}
}
if (this.density != 0f) {
score += 100 - Math.round(Math.abs(this.density / viewDensity - 1).coerceAtMost(1f))
score += 100 - abs(this.density / viewDensity - 1).coerceAtMost(1f).roundToInt()
}
return score
}

View File

@ -22,6 +22,7 @@ package org.mariotaku.twidere.extension.view
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import androidx.recyclerview.widget.recyclerView
import kotlin.math.max
fun RecyclerView.LayoutManager.calculateSpaceItemHeight(child: View, spaceViewType: Int, typeStart: Int): Int {
val recyclerView = recyclerView ?: return 0
@ -39,7 +40,7 @@ fun RecyclerView.LayoutManager.calculateSpaceItemHeight(child: View, spaceViewTy
if (heightBeforeSpace != 0) {
val spaceHeight = recyclerView.measuredHeight - recyclerView.paddingTop -
recyclerView.paddingBottom - heightBeforeSpace
return Math.max(0, spaceHeight)
return max(0, spaceHeight)
}
return -1
}

View File

@ -39,6 +39,7 @@ import org.mariotaku.twidere.util.ContentScrollHandler.ContentListSupport
import org.mariotaku.twidere.util.ListViewScrollHandler
import org.mariotaku.twidere.util.ThemeUtils
import org.mariotaku.twidere.util.TwidereColorUtils
import kotlin.math.roundToInt
/**
* Created by mariotaku on 15/4/16.
@ -211,10 +212,11 @@ abstract class AbsContentListViewFragment<A : ListAdapter> : BaseFragment(),
}
val density = resources.displayMetrics.density
val progressCircleDiameter = swipeLayout.progressCircleDiameter
val controlBarOffsetPixels = Math.round(activity.controlBarHeight * (1 - activity.controlBarOffset))
val controlBarOffsetPixels =
(activity.controlBarHeight * (1 - activity.controlBarOffset)).roundToInt()
val swipeStart = systemWindowsInsets.top - controlBarOffsetPixels - progressCircleDiameter
// 64: SwipeRefreshLayout.DEFAULT_CIRCLE_TARGET
val swipeDistance = Math.round(64 * density)
val swipeDistance = (64 * density).roundToInt()
swipeLayout.setProgressViewOffset(false, swipeStart, swipeStart + swipeDistance)
}

View File

@ -51,6 +51,8 @@ import org.mariotaku.twidere.util.DataStoreUtils
import org.mariotaku.twidere.util.DataStoreUtils.getTableNameByUri
import org.mariotaku.twidere.util.ErrorInfoStore
import org.mariotaku.twidere.util.Utils
import kotlin.math.max
import kotlin.math.min
/**
* Displays statuses from database
@ -241,8 +243,8 @@ abstract class CursorActivitiesFragment : AbsActivitiesFragment() {
fun replaceStatusStates(result: ParcelableStatus?) {
if (result == null) return
val lm = layoutManager
val rangeStart = Math.max(adapter.activityStartIndex, lm.findFirstVisibleItemPosition())
val rangeEnd = Math.min(lm.findLastVisibleItemPosition(), adapter.activityStartIndex + adapter.getActivityCount(false) - 1)
val rangeStart = max(adapter.activityStartIndex, lm.findFirstVisibleItemPosition())
val rangeEnd = min(lm.findLastVisibleItemPosition(), adapter.activityStartIndex + adapter.getActivityCount(false) - 1)
loop@ for (i in rangeStart..rangeEnd) {
val activity = adapter.getActivity(i, false)
if (result.account_key == activity.account_key && result.id == activity.id) {

View File

@ -46,6 +46,8 @@ import org.mariotaku.twidere.model.pagination.Pagination
import org.mariotaku.twidere.model.pagination.SinceMaxPagination
import org.mariotaku.twidere.util.Utils
import java.util.*
import kotlin.math.max
import kotlin.math.min
/**
* Created by mariotaku on 14/12/3.
@ -211,8 +213,8 @@ abstract class ParcelableStatusesFragment : AbsStatusesFragment() {
fun replaceStatusStates(status: ParcelableStatus?) {
if (status == null) return
val lm = layoutManager
val rangeStart = Math.max(adapter.statusStartIndex, lm.findFirstVisibleItemPosition())
val rangeEnd = Math.min(lm.findLastVisibleItemPosition(), adapter.statusStartIndex + adapter.getStatusCount(false) - 1)
val rangeStart = max(adapter.statusStartIndex, lm.findFirstVisibleItemPosition())
val rangeEnd = min(lm.findLastVisibleItemPosition(), adapter.statusStartIndex + adapter.getStatusCount(false) - 1)
for (i in rangeStart..rangeEnd) {
val item = adapter.getStatus(i, false)
if (status == item) {

View File

@ -150,6 +150,8 @@ import org.mariotaku.twidere.view.TabPagerIndicator
import org.mariotaku.twidere.view.iface.IExtendedView.OnSizeChangedListener
import java.lang.ref.WeakReference
import java.util.*
import kotlin.math.max
import kotlin.math.roundToInt
class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
OnSizeChangedListener, OnTouchListener, DrawerCallback, SupportFragmentCallback,
@ -475,7 +477,7 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
if (user.created_at >= 0) {
val createdAt = Utils.formatToLongTimeString(activity, user.created_at)
val daysSinceCreation = (System.currentTimeMillis() - user.created_at) / 1000 / 60 / 60 / 24.toFloat()
val dailyTweets = Math.round(user.statuses_count / Math.max(1f, daysSinceCreation))
val dailyTweets = (user.statuses_count / max(1f, daysSinceCreation)).roundToInt()
createdAtContainer.visibility = View.VISIBLE
createdAtContainer.createdAt.text = resources.getQuantityString(R.plurals.created_at_with_N_tweets_per_day, dailyTweets,
@ -1729,10 +1731,10 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
}
private fun updateValue() {
val shadowAlpha = Math.round(alpha * (1 - factor).coerceIn(0f, 1f))
val shadowAlpha = (alpha * (1 - factor).coerceIn(0f, 1f)).roundToInt()
shadowDrawable.alpha = shadowAlpha
val hasColor = color != 0
val colorAlpha = if (hasColor) Math.round(alpha * factor.coerceIn(0f, 1f)) else 0
val colorAlpha = if (hasColor) (alpha * factor.coerceIn(0f, 1f)).roundToInt() else 0
colorDrawable.alpha = colorAlpha
invalidateSelf()
}

View File

@ -39,6 +39,9 @@ import org.mariotaku.twidere.util.UriUtils
import org.mariotaku.twidere.util.media.MediaExtra
import java.io.IOException
import java.lang.ref.WeakReference
import kotlin.math.ceil
import kotlin.math.max
import kotlin.math.min
class ImagePageFragment : SubsampleImageViewerFragment() {
@ -150,9 +153,9 @@ class ImagePageFragment : SubsampleImageViewerFragment() {
val cr = context.contentResolver
decodeBitmap(cr, uri, o)
val dm = context.resources.displayMetrics
val targetSize = Math.min(1024, Math.max(dm.widthPixels, dm.heightPixels))
val sizeRatio = Math.ceil(Math.max(o.outHeight, o.outWidth) / targetSize.toDouble())
o.inSampleSize = Math.max(1.0, sizeRatio).toInt().nextPowerOf2
val targetSize = min(1024, max(dm.widthPixels, dm.heightPixels))
val sizeRatio = ceil(max(o.outHeight, o.outWidth) / targetSize.toDouble())
o.inSampleSize = max(1.0, sizeRatio).toInt().nextPowerOf2
o.inJustDecodeBounds = false
return decodeBitmap(cr, uri, o) ?: throw IOException()
}

View File

@ -61,6 +61,7 @@ import org.mariotaku.twidere.util.promotion.PromotionService
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import kotlin.math.roundToInt
class VideoPageFragment : CacheDownloadMediaViewerFragment(), IBaseFragment<VideoPageFragment>,
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener,
@ -125,7 +126,7 @@ class VideoPageFragment : CacheDownloadMediaViewerFragment(), IBaseFragment<Vide
if (!fromUser) return
val duration = videoView.duration
if (duration <= 0) return
videoView.seekTo(Math.round(duration * (progress.toFloat() / seekBar.max)))
videoView.seekTo((duration * (progress.toFloat() / seekBar.max)).roundToInt())
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
@ -358,7 +359,7 @@ class VideoPageFragment : CacheDownloadMediaViewerFragment(), IBaseFragment<Vide
val duration = mediaPlayerControl.duration
val position = mediaPlayerControl.currentPosition
if (duration <= 0 || position < 0) return
progressBar.progress = Math.round(1000 * position / duration.toFloat())
progressBar.progress = (1000 * position / duration.toFloat()).roundToInt()
val durationSecs = TimeUnit.SECONDS.convert(duration.toLong(), TimeUnit.MILLISECONDS)
val positionSecs = TimeUnit.SECONDS.convert(position.toLong(), TimeUnit.MILLISECONDS)
durationLabel.text = String.format(Locale.ROOT, "%02d:%02d", durationSecs / 60, durationSecs % 60)

View File

@ -61,6 +61,7 @@ import org.mariotaku.twidere.text.MarkForDeleteSpan
import org.mariotaku.twidere.util.IntentUtils
import org.mariotaku.twidere.util.view.SimpleTextWatcher
import java.lang.ref.WeakReference
import kotlin.math.roundToInt
/**
* Created by mariotaku on 2017/2/15.
@ -370,7 +371,7 @@ class MessageNewConversationFragment : BaseFragment(), LoaderCallbacks<List<Parc
paint.textSize = textSizeBackup - padding
nameWidth = paint.measureText(displayName)
paint.textSize = textSizeBackup
return Math.round(nameWidth + padding * 2)
return (nameWidth + padding * 2).roundToInt()
}
}

View File

@ -58,6 +58,7 @@ import org.mariotaku.twidere.util.view.SimpleTextWatcher
import org.mariotaku.twidere.view.ComposeEditText
import org.mariotaku.twidere.view.StatusTextCountView
import java.util.*
import kotlin.math.max
/**
* Asks user to retweet/quote a status.
@ -228,8 +229,9 @@ class RetweetQuoteDialogFragment : AbsStatusDialogFragment() {
update.repost_status_id = status.quoted_id
}
if (FanfouValidator.calculateLength(commentText) > FanfouValidator.textLimit) {
commentText = commentText.substring(0, Math.max(FanfouValidator.textLimit,
editingComment.length))
commentText = commentText.substring(0, max(FanfouValidator.textLimit,
editingComment.length)
)
}
}
else -> {

View File

@ -107,6 +107,8 @@ import org.mariotaku.twidere.view.holder.iface.IStatusViewHolder
import org.mariotaku.twidere.view.holder.iface.IStatusViewHolder.StatusClickListener
import org.mariotaku.yandex.YandexAPIFactory
import java.lang.ref.WeakReference
import kotlin.math.max
import kotlin.math.min
/**
* Displays status details
@ -832,7 +834,7 @@ class StatusFragment : BaseFragment(), LoaderCallbacks<SingleResponse<Parcelable
override fun computeVerticalScrollExtent(state: RecyclerView.State): Int {
val firstPosition = findFirstVisibleItemPosition()
val lastPosition = Math.min(validScrollItemCount - 1, findLastVisibleItemPosition())
val lastPosition = min(validScrollItemCount - 1, findLastVisibleItemPosition())
if (firstPosition < 0 || lastPosition < 0) return 0
val childCount = lastPosition - firstPosition + 1
if (childCount > 0) {
@ -861,7 +863,7 @@ class StatusFragment : BaseFragment(), LoaderCallbacks<SingleResponse<Parcelable
override fun computeVerticalScrollOffset(state: RecyclerView.State): Int {
val firstPosition = findFirstVisibleItemPosition()
val lastPosition = Math.min(validScrollItemCount - 1, findLastVisibleItemPosition())
val lastPosition = min(validScrollItemCount - 1, findLastVisibleItemPosition())
if (firstPosition < 0 || lastPosition < 0) return 0
val childCount = lastPosition - firstPosition + 1
val skippedCount = skippedScrollItemCount
@ -871,7 +873,7 @@ class StatusFragment : BaseFragment(), LoaderCallbacks<SingleResponse<Parcelable
val top = view.top
val height = view.height
if (height > 0) {
return Math.max((firstPosition - skippedCount) * 100 - top * 100 / height, 0)
return max((firstPosition - skippedCount) * 100 - top * 100 / height, 0)
}
} else {
val count = validScrollItemCount
@ -888,7 +890,7 @@ class StatusFragment : BaseFragment(), LoaderCallbacks<SingleResponse<Parcelable
override fun computeVerticalScrollRange(state: RecyclerView.State): Int {
return if (isSmoothScrollbarEnabled) {
Math.max(validScrollItemCount * 100, 0)
max(validScrollItemCount * 100, 0)
} else {
validScrollItemCount
}

View File

@ -50,6 +50,7 @@ import java.io.IOException
import java.util.*
import java.util.concurrent.atomic.AtomicReference
import javax.inject.Inject
import kotlin.math.min
abstract class AbsRequestStatusesLoader(
context: Context,
@ -211,7 +212,7 @@ abstract class AbsRequestStatusesLoader(
if (key == null || data == null) return
val databaseItemLimit = preferences[loadItemLimitKey]
try {
val statuses = data.subList(0, Math.min(databaseItemLimit, data.size))
val statuses = data.subList(0, min(databaseItemLimit, data.size))
jsonCache.saveList(key, statuses, ParcelableStatus::class.java)
} catch (e: Exception) {
// Ignore

View File

@ -70,6 +70,7 @@ import org.mariotaku.twidere.util.deleteDrafts
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.concurrent.TimeUnit
import kotlin.math.min
/**
* Intent service for lengthy operations like update status/send DM.
@ -334,7 +335,7 @@ class LengthyOperationsService : BaseIntentService("lengthy_operations") {
var streamReadLength = 0
var segmentIndex = 0
while (streamReadLength < length) {
val currentBulkSize = Math.min(BULK_SIZE, length - streamReadLength).toInt()
val currentBulkSize = min(BULK_SIZE, length - streamReadLength).toInt()
val output = ByteArrayOutputStream()
Utils.copyStream(stream, output, currentBulkSize)
val data = Base64.encodeToString(output.toByteArray(), Base64.DEFAULT)

View File

@ -35,6 +35,8 @@ import org.mariotaku.twidere.util.content.ContentResolverUtils
import org.mariotaku.twidere.util.sync.SyncTaskRunner
import org.mariotaku.twidere.util.sync.TimelineSyncManager
import java.util.*
import kotlin.math.max
import kotlin.math.min
/**
* Created by mariotaku on 16/1/4.
@ -142,12 +144,12 @@ abstract class GetActivitiesTask(
if (deleteBound[0] < 0) {
deleteBound[0] = activity.min_sort_position
} else {
deleteBound[0] = Math.min(deleteBound[0], activity.min_sort_position)
deleteBound[0] = min(deleteBound[0], activity.min_sort_position)
}
if (deleteBound[1] < 0) {
deleteBound[1] = activity.max_sort_position
} else {
deleteBound[1] = Math.max(deleteBound[1], activity.max_sort_position)
deleteBound[1] = max(deleteBound[1], activity.max_sort_position)
}
if (minIdx == -1 || activity < activities[minIdx]) {
minIdx = i

View File

@ -57,6 +57,7 @@ import org.mariotaku.twidere.util.text.StatusTextValidator
import java.io.*
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.math.min
/**
* Update status
@ -842,7 +843,7 @@ class UpdateStatusTask(
var streamReadLength = 0
var segmentIndex = 0
while (streamReadLength < length) {
val currentBulkSize = Math.min(BULK_SIZE.toLong(), length - streamReadLength).toInt()
val currentBulkSize = min(BULK_SIZE.toLong(), length - streamReadLength).toInt()
val output = ByteArrayOutputStream()
Utils.copyStream(stream, output, currentBulkSize)
val data = Base64.encodeToString(output.toByteArray(), Base64.DEFAULT)

View File

@ -23,6 +23,7 @@ import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.text.style.DynamicDrawableSpan
import kotlin.math.roundToInt
/**
* Created by mariotaku on 15/12/22.
@ -38,16 +39,16 @@ class EmojiSpan(private val drawable: Drawable) : DynamicDrawableSpan(ALIGN_BOTT
fm: Paint.FontMetricsInt?): Int {
val drawable = getDrawable() ?: return 0
paint.getFontMetrics(fontMetrics)
val textHeightPx = Math.round(fontMetrics.descent - fontMetrics.ascent)
val textHeightPx = (fontMetrics.descent - fontMetrics.ascent).roundToInt()
val intrinsicWidth = drawable.intrinsicWidth.toFloat()
val intrinsicHeight = drawable.intrinsicHeight.toFloat()
val scaledWidth: Int
scaledWidth = if (intrinsicWidth > intrinsicHeight) {
Math.round(textHeightPx * (intrinsicWidth / intrinsicHeight))
(textHeightPx * (intrinsicWidth / intrinsicHeight)).roundToInt()
} else {
Math.round(intrinsicWidth * (textHeightPx / intrinsicHeight))
(intrinsicWidth * (textHeightPx / intrinsicHeight)).roundToInt()
}
val top = Math.round(fontMetrics.bottom) - textHeightPx
val top = fontMetrics.bottom.roundToInt() - textHeightPx
val left = 0
drawable.setBounds(left, top, left + scaledWidth, top + textHeightPx)
return scaledWidth

View File

@ -26,6 +26,7 @@ import android.view.View
import org.mariotaku.twidere.adapter.iface.ILoadMoreSupportAdapter
import org.mariotaku.twidere.adapter.iface.ILoadMoreSupportAdapter.IndicatorPosition
import kotlin.math.abs
/**
* Created by mariotaku on 15/3/15.
@ -107,7 +108,7 @@ open class ContentScrollHandler<A>(
scrollSum = 0
}
scrollSum += dy
if (Math.abs(scrollSum) > touchSlop) {
if (abs(scrollSum) > touchSlop) {
contentListSupport.setControlVisible(reversed xor (dy < 0))
scrollSum = 0
}

View File

@ -25,6 +25,7 @@ import androidx.appcompat.view.menu.MenuBuilder
import android.util.DisplayMetrics
import android.view.Menu
import android.view.WindowManager
import kotlin.math.min
/**
* Created by mariotaku on 2017/4/17.
@ -55,7 +56,7 @@ object DeviceUtils {
} else {
defaultDisplay.getRealMetrics(metrics)
}
val mw = Math.min(metrics.widthPixels / metrics.density, metrics.heightPixels / metrics.density)
val mw = min(metrics.widthPixels / metrics.density, metrics.heightPixels / metrics.density)
return mw >= 600
}

View File

@ -72,6 +72,7 @@ import org.mariotaku.twidere.task.DestroyFavoriteTask
import org.mariotaku.twidere.task.RetweetStatusTask
import org.mariotaku.twidere.util.menu.TwidereMenuInfo
import java.io.IOException
import kotlin.math.roundToInt
/**
* Created by mariotaku on 15/4/12.
@ -83,7 +84,7 @@ object MenuUtils {
val pm = context.packageManager
val res = context.resources
val density = res.displayMetrics.density
val padding = Math.round(density * 4)
val padding = (density * 4).roundToInt()
val activities = pm.queryIntentActivities(queryIntent, 0)
for (info in activities) {
val intent = Intent(queryIntent)
@ -383,7 +384,7 @@ object MenuUtils {
val pm = context.packageManager
val res = context.resources
val density = res.displayMetrics.density
val padding = Math.round(density * 4)
val padding = (density * 4).roundToInt()
val queryIntent = Intent(action)
queryIntent.setExtrasClassLoader(TwidereApplication::class.java.classLoader)
val activities = pm.queryIntentActivities(queryIntent, PackageManager.GET_META_DATA)

View File

@ -24,6 +24,8 @@ import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.RectF
import android.view.View
import kotlin.math.min
import kotlin.math.roundToInt
/**
* Static utility methods for Transitions.
@ -50,9 +52,9 @@ object TransitionUtils {
*/
fun createViewBitmap(view: View, matrix: Matrix, bounds: RectF): Bitmap? {
if (bounds.isEmpty) return null
var bitmapWidth = Math.round(bounds.width())
var bitmapHeight = Math.round(bounds.height())
val scale = Math.min(1f, MAX_IMAGE_SIZE.toFloat() / (bitmapWidth * bitmapHeight))
var bitmapWidth = bounds.width().roundToInt()
var bitmapHeight = bounds.height().roundToInt()
val scale = min(1f, MAX_IMAGE_SIZE.toFloat() / (bitmapWidth * bitmapHeight))
bitmapWidth *= scale.toInt()
bitmapHeight *= scale.toInt()
matrix.postTranslate(-bounds.left, -bounds.top)

View File

@ -50,6 +50,7 @@ import org.mariotaku.twidere.util.IntentUtils
import org.mariotaku.twidere.util.dagger.DependencyHolder
import org.mariotaku.twidere.util.glide.DeferredTarget
import java.lang.ref.WeakReference
import kotlin.math.roundToInt
/**
* Created by mariotaku on 2017/8/23.
@ -159,8 +160,8 @@ object ShortcutCreator {
private fun Drawable.toProfileImageIcon(context: Context): IconCompat {
if (useAdaptiveIcon) {
val density = context.resources.displayMetrics.density
val adaptiveIconSize = Math.round(adaptiveIconSizeDp * density)
val adaptiveIconOuterSides = Math.round(adaptiveIconOuterSidesDp * density)
val adaptiveIconSize = (adaptiveIconSizeDp * density).roundToInt()
val adaptiveIconOuterSides = (adaptiveIconOuterSidesDp * density).roundToInt()
val bitmap = Bitmap.createBitmap(adaptiveIconSize, adaptiveIconSize,
Bitmap.Config.ARGB_8888)

View File

@ -36,6 +36,8 @@ import org.mariotaku.twidere.model.UserKey
import org.mariotaku.twidere.model.media.AuthenticatedUri
import org.mariotaku.twidere.model.util.ParcelableMediaUtils
import java.lang.ref.WeakReference
import kotlin.math.ceil
import kotlin.math.roundToInt
/**
* Dynamic layout for media preview
@ -219,13 +221,14 @@ class CardMediaContainer(context: Context, attrs: AttributeSet? = null) : ViewGr
private fun measure1Media(contentWidth: Int, childIndices: IntArray, ratioMultiplier: Float): Int {
val child = getChildAt(childIndices[0])
var childHeight = Math.round(contentWidth.toFloat() * WIDTH_HEIGHT_RATIO * ratioMultiplier)
var childHeight =
(contentWidth.toFloat() * WIDTH_HEIGHT_RATIO * ratioMultiplier).roundToInt()
if (style == PreviewStyle.ACTUAL_SIZE) {
val media = (child.layoutParams as MediaLayoutParams).media
if (media != null) {
val aspectRatio = media.aspect_ratio
if (!aspectRatio.isNaN()) {
childHeight = Math.round(contentWidth / aspectRatio.coerceIn(0.3, 20.0)).toInt()
childHeight = (contentWidth / aspectRatio.coerceIn(0.3, 20.0)).roundToInt()
}
}
}
@ -250,14 +253,14 @@ class CardMediaContainer(context: Context, attrs: AttributeSet? = null) : ViewGr
widthHeightRatio: Float, horizontalSpacing: Int, verticalSpacing: Int,
childIndices: IntArray): Int {
val childWidth = (contentWidth - horizontalSpacing * (columnCount - 1)) / columnCount
val childHeight = Math.round(childWidth * widthHeightRatio)
val childHeight = (childWidth * widthHeightRatio).roundToInt()
val widthSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY)
val heightSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY)
for (i in 0 until childCount) {
getChildAt(childIndices[i]).measure(widthSpec, heightSpec)
findViewById<View>(videoViewIds[i])?.measure(widthSpec, heightSpec)
}
val rowsCount = Math.ceil(childCount / columnCount.toDouble()).toInt()
val rowsCount = ceil(childCount / columnCount.toDouble()).toInt()
return rowsCount * childHeight + (rowsCount - 1) * verticalSpacing
}
@ -290,11 +293,11 @@ class CardMediaContainer(context: Context, attrs: AttributeSet? = null) : ViewGr
val child1 = getChildAt(childIndices[1])
val child2 = getChildAt(childIndices[2])
val childWidth = (contentWidth - horizontalSpacing) / 2
val childLeftHeightSpec = MeasureSpec.makeMeasureSpec(Math.round(childWidth * ratioMultiplier), MeasureSpec.EXACTLY)
val childLeftHeightSpec = MeasureSpec.makeMeasureSpec((childWidth * ratioMultiplier).roundToInt(), MeasureSpec.EXACTLY)
val widthSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY)
child0.measure(widthSpec, childLeftHeightSpec)
val childRightHeight = Math.round((childWidth - horizontalSpacing) / 2 * ratioMultiplier)
val childRightHeight = ((childWidth - horizontalSpacing) / 2 * ratioMultiplier).roundToInt()
val childRightHeightSpec = MeasureSpec.makeMeasureSpec(childRightHeight, MeasureSpec.EXACTLY)
child1.measure(widthSpec, childRightHeightSpec)
child2.measure(widthSpec, childRightHeightSpec)
@ -302,7 +305,7 @@ class CardMediaContainer(context: Context, attrs: AttributeSet? = null) : ViewGr
findViewById<View>(videoViewIds[0])?.measure(widthSpec, childLeftHeightSpec)
findViewById<View>(videoViewIds[1])?.measure(widthSpec, childRightHeightSpec)
findViewById<View>(videoViewIds[2])?.measure(widthSpec, childRightHeightSpec)
return Math.round(contentWidth.toFloat() * WIDTH_HEIGHT_RATIO * ratioMultiplier)
return (contentWidth.toFloat() * WIDTH_HEIGHT_RATIO * ratioMultiplier).roundToInt()
}
private fun layout3Media(horizontalSpacing: Int, verticalSpacing: Int, childIndices: IntArray) {

View File

@ -24,6 +24,7 @@ import android.util.AttributeSet
import android.view.View
import android.widget.ScrollView
import org.mariotaku.twidere.R
import kotlin.math.min
class MaxHeightScrollView(context: Context, attrs: AttributeSet? = null) : ScrollView(context, attrs) {
@ -40,7 +41,8 @@ class MaxHeightScrollView(context: Context, attrs: AttributeSet? = null) : Scrol
val hSpec = if (maxHeight >= 0) {
val measuredHeight = MeasureSpec.getSize(heightMeasureSpec)
if (measuredHeight > 0) {
MeasureSpec.makeMeasureSpec(Math.min(measuredHeight, maxHeight),
MeasureSpec.makeMeasureSpec(
min(measuredHeight, maxHeight),
MeasureSpec.AT_MOST)
} else {
maxHeight

View File

@ -31,6 +31,7 @@ import android.view.WindowInsets
import android.widget.ImageView
import org.mariotaku.twidere.R
import org.mariotaku.twidere.view.iface.IExtendedView
import kotlin.math.roundToInt
class ProfileBannerImageView(context: Context, attrs: AttributeSet) :
ForegroundImageView(context, attrs), IExtendedView {
@ -67,7 +68,7 @@ class ProfileBannerImageView(context: Context, attrs: AttributeSet) :
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val width = MeasureSpec.getSize(widthMeasureSpec)
val height = Math.round(width / bannerAspectRatio)
val height = (width / bannerAspectRatio).roundToInt()
setMeasuredDimension(width, height)
super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY))
}

View File

@ -28,6 +28,7 @@ import org.mariotaku.twidere.Constants
import org.mariotaku.twidere.R
import org.mariotaku.twidere.util.Utils.formatSameDayTime
import java.lang.ref.WeakReference
import kotlin.math.abs
class ShortTimeView(
context: Context,
@ -63,7 +64,7 @@ class ShortTimeView(
setTextIfChanged(formatSameDayTime(context, time))
} else {
val current = System.currentTimeMillis()
if (Math.abs(current - time) > 60 * 1000) {
if (abs(current - time) > 60 * 1000) {
setTextIfChanged(DateUtils.getRelativeTimeSpanString(time, System.currentTimeMillis(),
DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_ABBREV_ALL))
} else {

View File

@ -31,6 +31,7 @@ import android.widget.TextView
import org.mariotaku.chameleon.view.ChameleonTextView
import org.mariotaku.twidere.extension.setupEmojiFactory
import java.lang.ref.WeakReference
import kotlin.math.roundToInt
/**
* Returns true when not clicking links
@ -98,7 +99,7 @@ class TimelineContentTextView(
val layout = widget.layout
val x = event.x - widget.paddingLeft + widget.scrollX
val y = event.y - widget.paddingTop + widget.scrollY
val line = layout.getLineForVertical(Math.round(y))
val line = layout.getLineForVertical(y.roundToInt())
val offset = layout.getOffsetForHorizontal(line, x)
targetSpan = if (x <= layout.getLineWidth(line)) {
WeakReference(text.getSpans(offset, offset, ClickableSpan::class.java).firstOrNull())

View File

@ -23,6 +23,7 @@ import android.content.Context
import android.util.AttributeSet
import android.view.View
import org.mariotaku.twidere.util.support.ViewSupport
import kotlin.math.roundToInt
/**
* Created by mariotaku on 15/1/1.
@ -46,7 +47,7 @@ class TwitterCardContainer(context: Context, attrs: AttributeSet? = null) : Cont
return
}
val measuredWidth = MeasureSpec.getSize(widthMeasureSpec)
val measuredHeight = Math.round(measuredWidth * (cardHeight / cardWidth.toFloat()))
val measuredHeight = (measuredWidth * (cardHeight / cardWidth.toFloat())).roundToInt()
val newWidthMeasureSpec = MeasureSpec.makeMeasureSpec(measuredWidth, MeasureSpec.EXACTLY)
val newHeightMeasureSpec: Int
newHeightMeasureSpec = if (measuredHeight != 0) {

View File

@ -51,6 +51,7 @@ import org.mariotaku.twidere.util.support.ViewSupport
import org.mariotaku.twidere.view.ContainerView
import java.lang.ref.WeakReference
import java.util.*
import kotlin.math.roundToInt
/**
* Created by mariotaku on 15/12/20.
@ -191,7 +192,9 @@ class CardPollViewController : ContainerView.ViewController() {
if (label == null) throw NullPointerException()
val choicePercent = if (votesSum == 0) 0f else value / votesSum.toFloat()
choiceLabelView.spannable = label
choicePercentView.text = String.format(Locale.US, "%d%%", Math.round(choicePercent * 100))
choicePercentView.text = String.format(Locale.US, "%d%%",
(choicePercent * 100).roundToInt()
)
pollItem.setOnClickListener(clickListener)

View File

@ -34,6 +34,7 @@ import org.mariotaku.twidere.extension.loadProfileImage
import org.mariotaku.twidere.model.ActivityTitleSummaryMessage
import org.mariotaku.twidere.model.ParcelableActivity
import org.mariotaku.twidere.model.ParcelableLiteUser
import kotlin.math.min
/**
* Created by mariotaku on 15/1/3.
@ -128,7 +129,7 @@ class ActivityTitleSummaryViewHolder(
}
return
}
val length = Math.min(profileImageViews.size, users.size)
val length = min(profileImageViews.size, users.size)
for (i in profileImageViews.indices) {
val view = profileImageViews[i]
view.setImageDrawable(null)

View File

@ -12,6 +12,8 @@ import android.view.View
import android.view.ViewConfiguration
import android.view.ViewGroup
import org.mariotaku.ktextension.coerceInOr
import kotlin.math.abs
import kotlin.math.roundToInt
/**
* Created by mariotaku on 2017/1/29.
@ -48,7 +50,7 @@ class MediaSwipeCloseContainer(context: Context, attrs: AttributeSet? = null) :
override fun onViewReleased(releasedChild: View, xvel: Float, yvel: Float) {
val container = this@MediaSwipeCloseContainer
val minVel = ViewConfiguration.get(context).scaledMinimumFlingVelocity
if (Math.abs(yvel) < Math.abs(xvel)) {
if (abs(yvel) < abs(xvel)) {
container.dragHelper.smoothSlideViewTo(releasedChild, 0, 0)
} else when {
yvel > minVel && childTop > 0 -> {
@ -125,6 +127,6 @@ class MediaSwipeCloseContainer(context: Context, attrs: AttributeSet? = null) :
var backgroundAlpha: Float
get() = (background?.let(DrawableCompat::getAlpha) ?: 0) / 255f
set(@FloatRange(from = 0.0, to = 1.0) value) {
background?.alpha = Math.round(value * 0xFF)
background?.alpha = (value * 0xFF).roundToInt()
}
}