Clean up code after conversions

This commit is contained in:
Quentin Hibon
2021-01-21 18:17:58 +01:00
parent 18db571507
commit 6992b5186e
44 changed files with 284 additions and 349 deletions

View File

@@ -25,7 +25,7 @@ import android.os.Parcelable.ClassLoaderCreator
import androidx.customview.view.AbsSavedState
class BundleSavedState : AbsSavedState {
val bundle: Bundle?
@JvmField val bundle: Bundle?
constructor(superState: Parcelable?, bundle: Bundle?) : super(superState!!) {
this.bundle = bundle

View File

@@ -38,6 +38,9 @@ import java.util.GregorianCalendar
import java.util.Locale
import java.util.Random
import kotlin.collections.HashMap
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
class FrequencyChart : ScrollableChart {
private var pGrid: Paint? = null
@@ -90,8 +93,8 @@ class FrequencyChart : ScrollableChart {
private fun getMaxFreq(frequency: HashMap<Timestamp, Array<Int>>): Int {
var maxValue = 1
for (values in frequency.values) for (value in values) maxValue = Math.max(
value!!,
for (values in frequency.values) for (value in values) maxValue = max(
value,
maxValue
)
return maxValue
@@ -102,7 +105,7 @@ class FrequencyChart : ScrollableChart {
initColors()
}
protected fun initPaints() {
private fun initPaints() {
pText = Paint()
pText!!.isAntiAlias = true
pGraph = Paint()
@@ -155,7 +158,7 @@ class FrequencyChart : ScrollableChart {
pGrid!!.strokeWidth = baseSize * 0.05f
em = pText!!.fontSpacing
columnWidth = baseSize.toFloat()
columnWidth = Math.max(columnWidth, maxMonthWidth * 1.2f)
columnWidth = max(columnWidth, maxMonthWidth * 1.2f)
columnHeight = 8 * baseSize
nColumns = (width / columnWidth).toInt()
internalPaddingTop = 0
@@ -225,20 +228,20 @@ class FrequencyChart : ScrollableChart {
// the real mark radius is scaled down by a factor depending on the maximal frequency
val scale = 1.0f / maxFreq * value!!
val radius = maxRadius * scale
val colorIndex = Math.min(colors.size - 1, Math.round((colors.size - 1) * scale))
val colorIndex = min((colors.size - 1), ((colors.size - 1) * scale).roundToInt())
pGraph!!.color = colors[colorIndex]
canvas.drawCircle(rect.centerX(), rect.centerY(), radius, pGraph!!)
}
private val maxMonthWidth: Float
private get() {
get() {
var maxMonthWidth = 0f
val day: GregorianCalendar =
getStartOfTodayCalendarWithOffset()
for (i in 0..11) {
day[Calendar.MONTH] = i
val monthWidth = pText!!.measureText(dfMonth!!.format(day.time))
maxMonthWidth = Math.max(maxMonthWidth, monthWidth)
maxMonthWidth = max(maxMonthWidth, monthWidth)
}
return maxMonthWidth
}

View File

@@ -41,6 +41,8 @@ import org.isoron.uhabits.utils.InterfaceUtils.getFontAwesome
import org.isoron.uhabits.utils.InterfaceUtils.spToPixels
import org.isoron.uhabits.utils.PaletteUtils.getAndroidTestColor
import org.isoron.uhabits.utils.StyledResources
import kotlin.math.min
import kotlin.math.roundToLong
class RingView : View {
private var color: Int
@@ -140,7 +142,7 @@ class RingView : View {
}
pRing!!.color = color
rect!![0f, 0f, diameter.toFloat()] = diameter.toFloat()
val angle = 360 * Math.round(percentage / precision) * precision
val angle = 360 * (percentage / precision).roundToLong() * precision
activeCanvas!!.drawArc(rect!!, -90f, angle, true, pRing!!)
pRing!!.color = inactiveColor!!
activeCanvas.drawArc(rect!!, angle - 90, 360 - angle, true, pRing!!)
@@ -167,7 +169,7 @@ class RingView : View {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val width = MeasureSpec.getSize(widthMeasureSpec)
val height = MeasureSpec.getSize(heightMeasureSpec)
diameter = Math.min(height, width)
diameter = min(height, width)
pRing!!.textSize = textSize
em = pRing!!.measureText("M")
setMeasuredDimension(diameter, diameter)

View File

@@ -42,6 +42,8 @@ import java.util.GregorianCalendar
import java.util.LinkedList
import java.util.Locale
import java.util.Random
import kotlin.math.max
import kotlin.math.min
class ScoreChart : ScrollableChart {
private var pGrid: Paint? = null
@@ -89,7 +91,7 @@ class ScoreChart : ScrollableChart {
for (i in 1..99) {
val step = 0.1
var current = previous + random.nextDouble() * step * 2 - step
current = Math.max(0.0, Math.min(1.0, current))
current = max(0.0, min(1.0, current))
newScores.add(Score(timestamp.minus(i), current))
previous = current
}
@@ -178,14 +180,14 @@ class ScoreChart : ScrollableChart {
if (height < 9) height = 200
val maxTextSize = getDimension(context, R.dimen.tinyTextSize)
val textSize = height * 0.06f
pText!!.textSize = Math.min(textSize, maxTextSize)
pText!!.textSize = min(textSize, maxTextSize)
em = pText!!.fontSpacing
val footerHeight = (3 * em).toInt()
internalPaddingTop = em.toInt()
baseSize = (height - footerHeight - internalPaddingTop) / 8
columnWidth = baseSize.toFloat()
columnWidth = Math.max(columnWidth, maxDayWidth * 1.5f)
columnWidth = Math.max(columnWidth, maxMonthWidth * 1.2f)
columnWidth = max(columnWidth, maxDayWidth * 1.5f)
columnWidth = max(columnWidth, maxMonthWidth * 1.2f)
nColumns = (width / columnWidth).toInt()
columnWidth = width.toFloat() / nColumns
setScrollerBucketSize(columnWidth.toInt())
@@ -193,7 +195,7 @@ class ScoreChart : ScrollableChart {
val minStrokeWidth = dpToPixels(context, 1f)
pGraph!!.textSize = baseSize * 0.5f
pGraph!!.strokeWidth = baseSize * 0.1f
pGrid!!.strokeWidth = Math.min(minStrokeWidth, baseSize * 0.05f)
pGrid!!.strokeWidth = min(minStrokeWidth, baseSize * 0.05f)
if (isTransparencyEnabled) initCache(width, height)
}
@@ -298,7 +300,7 @@ class ScoreChart : ScrollableChart {
for (i in 0..27) {
day[Calendar.DAY_OF_MONTH] = i
val monthWidth = pText!!.measureText(dfMonth!!.format(day.time))
maxDayWidth = Math.max(maxDayWidth, monthWidth)
maxDayWidth = max(maxDayWidth, monthWidth)
}
return maxDayWidth
}
@@ -310,7 +312,7 @@ class ScoreChart : ScrollableChart {
for (i in 0..11) {
day[Calendar.MONTH] = i
val monthWidth = pText!!.measureText(dfMonth!!.format(day.time))
maxMonthWidth = Math.max(maxMonthWidth, monthWidth)
maxMonthWidth = max(maxMonthWidth, monthWidth)
}
return maxMonthWidth
}

View File

@@ -28,6 +28,9 @@ import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import android.widget.Scroller
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
abstract class ScrollableChart : View, GestureDetector.OnGestureListener, AnimatorUpdateListener {
var dataOffset = 0
@@ -91,37 +94,37 @@ abstract class ScrollableChart : View, GestureDetector.OnGestureListener, Animat
super.onRestoreInstanceState(state)
return
}
val bss = state
val x = bss.bundle!!.getInt("x")
val y = bss.bundle.getInt("y")
direction = bss.bundle.getInt("direction")
dataOffset = bss.bundle.getInt("dataOffset")
maxDataOffset = bss.bundle.getInt("maxDataOffset")
val x = state.bundle!!.getInt("x")
val y = state.bundle.getInt("y")
direction = state.bundle.getInt("direction")
dataOffset = state.bundle.getInt("dataOffset")
maxDataOffset = state.bundle.getInt("maxDataOffset")
scroller!!.startScroll(0, 0, x, y, 0)
scroller!!.computeScrollOffset()
super.onRestoreInstanceState(bss.superState)
super.onRestoreInstanceState(state.superState)
}
public override fun onSaveInstanceState(): Parcelable? {
val superState = super.onSaveInstanceState()
val bundle = Bundle()
bundle.putInt("x", scroller!!.currX)
bundle.putInt("y", scroller!!.currY)
bundle.putInt("dataOffset", dataOffset)
bundle.putInt("direction", direction)
bundle.putInt("maxDataOffset", maxDataOffset)
val bundle = Bundle().apply {
putInt("x", scroller!!.currX)
putInt("y", scroller!!.currY)
putInt("dataOffset", dataOffset)
putInt("direction", direction)
putInt("maxDataOffset", maxDataOffset)
}
return BundleSavedState(superState, bundle)
}
override fun onScroll(e1: MotionEvent?, e2: MotionEvent?, dx: Float, dy: Float): Boolean {
var dx = dx
if (scrollerBucketSize == 0) return false
if (Math.abs(dx) > Math.abs(dy)) {
if (abs(dx) > abs(dy)) {
val parent = parent
parent?.requestDisallowInterceptTouchEvent(true)
}
dx = -direction * dx
dx = Math.min(dx, (maxX - scroller!!.currX).toFloat())
dx *= -direction
dx = min(dx, (maxX - scroller!!.currX).toFloat())
scroller!!.startScroll(
scroller!!.currX,
scroller!!.currY,
@@ -151,7 +154,7 @@ abstract class ScrollableChart : View, GestureDetector.OnGestureListener, Animat
override fun onLongPress(e: MotionEvent) {}
fun setMaxDataOffset(maxDataOffset: Int) {
this.maxDataOffset = maxDataOffset
dataOffset = Math.min(dataOffset, maxDataOffset)
dataOffset = min(dataOffset, maxDataOffset)
scrollController!!.onDataOffsetChanged(dataOffset)
postInvalidate()
}
@@ -181,8 +184,8 @@ abstract class ScrollableChart : View, GestureDetector.OnGestureListener, Animat
private fun updateDataOffset() {
var newDataOffset = scroller!!.currX / scrollerBucketSize
newDataOffset = Math.max(0, newDataOffset)
newDataOffset = Math.min(maxDataOffset, newDataOffset)
newDataOffset = max(0, newDataOffset)
newDataOffset = min(maxDataOffset, newDataOffset)
if (newDataOffset != dataOffset) {
dataOffset = newDataOffset
scrollController!!.onDataOffsetChanged(dataOffset)

View File

@@ -37,6 +37,9 @@ import java.text.DateFormat
import java.util.LinkedList
import java.util.Random
import java.util.TimeZone
import kotlin.math.floor
import kotlin.math.max
import kotlin.math.min
class StreakChart : View {
private var paint: Paint? = null
@@ -72,7 +75,7 @@ class StreakChart : View {
* @return max number of visible streaks
*/
val maxStreakCount: Int
get() = Math.floor((measuredHeight / baseSize).toDouble()).toInt()
get() = floor((measuredHeight / baseSize).toDouble()).toInt()
fun populateWithRandomData() {
var start: Timestamp = getToday()
@@ -105,7 +108,7 @@ class StreakChart : View {
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (streaks!!.size == 0) return
if (streaks!!.isEmpty()) return
rect!![0f, 0f, internalWidth.toFloat()] = baseSize.toFloat()
for (s in streaks!!) {
drawRow(canvas, s, rect)
@@ -137,7 +140,7 @@ class StreakChart : View {
val minTextSize = getDimension(context, R.dimen.tinyTextSize)
val maxTextSize = getDimension(context, R.dimen.regularTextSize)
val textSize = baseSize * 0.5f
paint!!.textSize = Math.max(Math.min(textSize, maxTextSize), minTextSize)
paint!!.textSize = max(min(textSize, maxTextSize), minTextSize)
em = paint!!.fontSpacing
textMargin = 0.5f * em
updateMaxMinLengths()
@@ -149,8 +152,8 @@ class StreakChart : View {
var availableWidth = internalWidth - 2 * maxLabelWidth
if (shouldShowLabels) availableWidth -= 2 * textMargin
var barWidth = percentage * availableWidth
val minBarWidth = paint!!.measureText(java.lang.Long.toString(streak.length.toLong())) + em
barWidth = Math.max(barWidth, minBarWidth)
val minBarWidth = paint!!.measureText(streak.length.toLong().toString()) + em
barWidth = max(barWidth, minBarWidth)
val gap = (internalWidth - barWidth) / 2
val paddingTopBottom = baseSize * 0.05f
paint!!.color = percentageToColor(percentage)
@@ -168,7 +171,7 @@ class StreakChart : View {
paint!!.color = percentageToTextColor(percentage)
paint!!.textAlign = Paint.Align.CENTER
canvas.drawText(
java.lang.Long.toString(streak.length.toLong()),
streak.length.toLong().toString(),
rect.centerX(),
yOffset,
paint!!
@@ -189,7 +192,7 @@ class StreakChart : View {
initColors()
streaks = emptyList()
val newDateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM)
if (!isInEditMode) newDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"))
if (!isInEditMode) newDateFormat.timeZone = TimeZone.getTimeZone("GMT")
dateFormat = newDateFormat
rect = RectF()
baseSize = resources.getDimensionPixelSize(R.dimen.baseSize)
@@ -232,11 +235,11 @@ class StreakChart : View {
minLength = Long.MAX_VALUE
shouldShowLabels = true
for (s in streaks!!) {
maxLength = Math.max(maxLength, s.length.toLong())
minLength = Math.min(minLength, s.length.toLong())
maxLength = max(maxLength, s.length.toLong())
minLength = min(minLength, s.length.toLong())
val lw1 = paint!!.measureText(dateFormat!!.format(s.start.toJavaDate()))
val lw2 = paint!!.measureText(dateFormat!!.format(s.end.toJavaDate()))
maxLabelWidth = Math.max(maxLabelWidth, Math.max(lw1, lw2))
maxLabelWidth = max(maxLabelWidth, max(lw1, lw2))
}
if (internalWidth - 2 * maxLabelWidth < internalWidth * 0.25f) {
maxLabelWidth = 0f

View File

@@ -31,6 +31,8 @@ import org.isoron.uhabits.activities.habits.list.views.toShortString
import org.isoron.uhabits.utils.InterfaceUtils.dpToPixels
import org.isoron.uhabits.utils.InterfaceUtils.getDimension
import org.isoron.uhabits.utils.StyledResources
import kotlin.math.max
import kotlin.math.min
class TargetChart : View {
private var paint: Paint? = null
@@ -62,12 +64,12 @@ class TargetChart : View {
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (labels.size == 0) return
if (labels.isEmpty()) return
maxLabelSize = 0f
for (label in labels) {
paint!!.textSize = tinyTextSize
val len = paint!!.measureText(label)
maxLabelSize = Math.max(maxLabelSize, len)
maxLabelSize = max(maxLabelSize, len)
}
val marginTop = (height - baseSize * labels.size) / 2.0f
rect[0f, marginTop, width.toFloat()] = marginTop + baseSize
@@ -86,7 +88,7 @@ class TargetChart : View {
val params = layoutParams
if (params != null && params.height == ViewGroup.LayoutParams.MATCH_PARENT) {
height = MeasureSpec.getSize(heightSpec)
if (labels.size > 0) baseSize = height / labels.size
if (labels.isNotEmpty()) baseSize = height / labels.size
}
heightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)
widthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY)
@@ -116,7 +118,7 @@ class TargetChart : View {
rect.bottom - baseSize * 0.05f
canvas.drawRoundRect(barRect, round, round, paint!!)
var percentage = (values[row] / targets[row]).toFloat()
percentage = Math.min(1.0f, percentage)
percentage = min(1.0f, percentage)
// Draw completed box
var completedWidth = percentage * barRect.width()

View File

@@ -173,8 +173,8 @@ class ListHabitsScreen
ConfirmDeleteDialog(activity, callback, quantity).show()
}
override fun showEditHabitsScreen(habits: List<Habit>) {
val intent = intentFactory.startEditActivity(activity, habits[0])
override fun showEditHabitsScreen(selected: List<Habit>) {
val intent = intentFactory.startEditActivity(activity, selected[0])
activity.startActivity(intent)
}
@@ -183,8 +183,8 @@ class ListHabitsScreen
activity.startActivity(intent)
}
override fun showHabitScreen(habit: Habit) {
val intent = intentFactory.startShowHabitActivity(activity, habit)
override fun showHabitScreen(h: Habit) {
val intent = intentFactory.startShowHabitActivity(activity, h)
activity.startActivity(intent)
}
@@ -215,7 +215,7 @@ class ListHabitsScreen
)
}
override fun showSendBugReportToDeveloperScreen(log: String?) {
override fun showSendBugReportToDeveloperScreen(log: String) {
val to = R.string.bugReportTo
val subject = R.string.bugReportSubject
activity.showSendEmailScreen(to, subject, log)
@@ -287,13 +287,17 @@ class ListHabitsScreen
private fun onImportData(file: File, onFinished: () -> Unit) {
taskRunner.execute(
importTaskFactory.create(file) { result ->
if (result == ImportDataTask.SUCCESS) {
adapter.refresh()
activity.showMessage(activity.resources.getString(R.string.habits_imported))
} else if (result == ImportDataTask.NOT_RECOGNIZED) {
activity.showMessage(activity.resources.getString(R.string.file_not_recognized))
} else {
activity.showMessage(activity.resources.getString(R.string.could_not_import))
when (result) {
ImportDataTask.SUCCESS -> {
adapter.refresh()
activity.showMessage(activity.resources.getString(R.string.habits_imported))
}
ImportDataTask.NOT_RECOGNIZED -> {
activity.showMessage(activity.resources.getString(R.string.file_not_recognized))
}
else -> {
activity.showMessage(activity.resources.getString(R.string.could_not_import))
}
}
onFinished()
}

View File

@@ -90,10 +90,6 @@ class HabitCardListAdapter @Inject constructor(
return getItem(position)!!.id!!
}
// override fun getSelected(): List<Habit> {
// return LinkedList(selected)
// }
/**
* Returns whether list of selected items is empty.
*
@@ -158,8 +154,8 @@ class HabitCardListAdapter @Inject constructor(
observable.notifyListeners()
}
override fun onItemMoved(fromPosition: Int, toPosition: Int) {
notifyItemMoved(fromPosition, toPosition)
override fun onItemMoved(oldPosition: Int, newPosition: Int) {
notifyItemMoved(oldPosition, newPosition)
observable.notifyListeners()
}
@@ -209,8 +205,8 @@ class HabitCardListAdapter @Inject constructor(
cache.refreshAllHabits()
}
override fun setFilter(matcher: HabitMatcher?) {
if (matcher != null) cache.setFilter(matcher)
override fun setFilter(matcher: HabitMatcher) {
cache.setFilter(matcher)
}
/**

View File

@@ -92,9 +92,7 @@ class HabitCardView(
var score
get() = scoreRing.getPercentage().toDouble()
set(value) {
// scoreRing.percentage = value.toFloat()
scoreRing.setPercentage(value.toFloat())
// scoreRing.precision = 1.0f / 16
scoreRing.setPrecision(1.0f / 16)
}
@@ -228,7 +226,6 @@ class HabitCardView(
}
scoreRing.apply {
setColor(c)
// color = c
}
checkmarkPanel.apply {
color = c

View File

@@ -49,9 +49,7 @@ class OverviewCardView(context: Context, attrs: AttributeSet) : LinearLayout(con
binding.monthDiffLabel.text = formatPercentageDiff(state.scoreMonthDiff)
binding.scoreLabel.setTextColor(androidColor)
binding.scoreLabel.text = String.format("%.0f%%", state.scoreToday * 100)
// binding.scoreRing.color = androidColor
binding.scoreRing.setColor(androidColor)
// binding.scoreRing.percentage = state.scoreToday
binding.scoreRing.setPercentage(state.scoreToday)
binding.title.setTextColor(androidColor)

View File

@@ -80,7 +80,7 @@ class IntentScheduler
return schedule(updateTime, intent, RTC)
}
override fun log(componentName: String?, msg: String?) {
override fun log(componentName: String, msg: String) {
Log.d(componentName, msg)
}

View File

@@ -53,14 +53,14 @@ class AndroidNotificationTray
) : NotificationTray.SystemTray {
private var active = HashSet<Int>()
override fun log(msg: String?) {
override fun log(msg: String) {
Log.d("AndroidNotificationTray", msg)
}
override fun removeNotification(id: Int) {
override fun removeNotification(notificationId: Int) {
val manager = NotificationManagerCompat.from(context)
manager.cancel(id)
active.remove(id)
manager.cancel(notificationId)
active.remove(notificationId)
}
override fun showNotification(

View File

@@ -43,6 +43,7 @@ class SnoozeDelayPickerActivity : FragmentActivity(), OnItemClickListener {
private var dialog: AlertDialog? = null
override fun onCreate(bundle: Bundle?) {
super.onCreate(bundle)
val intent = intent
if (intent == null) finish()
if (intent.data == null) finish()
val app = applicationContext as HabitsApplication

View File

@@ -34,7 +34,7 @@ import org.isoron.uhabits.core.preferences.WidgetPreferences
import org.isoron.uhabits.intents.PendingIntentFactory
abstract class BaseWidget(val context: Context, val id: Int) {
protected val widgetPrefs: WidgetPreferences
private val widgetPrefs: WidgetPreferences
protected val prefs: Preferences
protected val pendingIntentFactory: PendingIntentFactory
protected val commandRunner: CommandRunner
@@ -120,9 +120,9 @@ abstract class BaseWidget(val context: Context, val id: Int) {
return remoteViews
}
private fun measureView(view: View, width: Int, height: Int) {
var width = width
var height = height
private fun measureView(view: View, w: Int, h: Int) {
var width = w
var height = h
val inflater = LayoutInflater.from(context)
val entireView = inflater.inflate(R.layout.widget_wrapper, null)
var specWidth = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY)
@@ -144,7 +144,7 @@ abstract class BaseWidget(val context: Context, val id: Int) {
}
protected val preferedBackgroundAlpha: Int
protected get() = prefs.widgetOpacity
get() = prefs.widgetOpacity
init {
val app = context.applicationContext as HabitsApplication

View File

@@ -83,10 +83,8 @@ class CheckmarkWidgetView : HabitWidgetView {
setShadowAlpha(0x00)
}
}
// ring.percentage = percentage
ring.setPercentage(percentage)
ring.setColor(fgColor)
// ring.color = fgColor
ring.setBackgroundColor(bgColor)
ring.setText(text)
label.text = name