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

@@ -201,7 +201,7 @@ abstract class BaseAndroidTest : TestCase() {
Thread.sleep(1000)
}
private var savedCalendar: GregorianCalendar? = null
private lateinit var savedCalendar: GregorianCalendar
fun saveSystemTime() {
savedCalendar = GregorianCalendar()
}
@@ -209,7 +209,7 @@ abstract class BaseAndroidTest : TestCase() {
@Throws(Exception::class)
fun restoreSystemTime() {
if (savedCalendar == null) throw NullPointerException()
setSystemTime(savedCalendar!!)
setSystemTime(savedCalendar)
}
companion object {

View File

@@ -40,15 +40,13 @@ class HabitFixtures(private val modelFactory: ModelFactory, private val habitLis
100000, 0, 100000
)
@JvmOverloads
fun createEmptyHabit(id: Long? = null): Habit {
fun createEmptyHabit(): Habit {
val habit = modelFactory.buildHabit()
habit.name = "Meditate"
habit.question = "Did you meditate this morning?"
habit.description = "This is a test description"
habit.color = PaletteColor(5)
habit.frequency = DAILY
habit.id = id
habitList.add(habit)
return habit
}
@@ -101,13 +99,14 @@ class HabitFixtures(private val modelFactory: ModelFactory, private val habitLis
}
fun createLongNumericalHabit(): Habit {
val habit = modelFactory.buildHabit()
habit.name = "Read"
habit.question = "How many pages did you walk today?"
habit.type = NUMBER_HABIT
habit.targetType = AT_LEAST
habit.targetValue = 200.0
habit.unit = "pages"
val habit = modelFactory.buildHabit().apply {
name = "Read"
question = "How many pages did you walk today?"
type = NUMBER_HABIT
targetType = AT_LEAST
targetValue = 200.0
unit = "pages"
}
habitList.add(habit)
var timestamp: Timestamp = getToday()
for (value in LONG_NUMERICAL_HABIT_ENTRIES) {
@@ -119,10 +118,11 @@ class HabitFixtures(private val modelFactory: ModelFactory, private val habitLis
}
fun createShortHabit(): Habit {
val habit = modelFactory.buildHabit()
habit.name = "Wake up early"
habit.question = "Did you wake up before 6am?"
habit.frequency = Frequency(2, 3)
val habit = modelFactory.buildHabit().apply {
name = "Wake up early"
question = "Did you wake up before 6am?"
frequency = Frequency(2, 3)
}
habitList.add(habit)
var timestamp: Timestamp = getToday()
for (c in LONG_HABIT_ENTRIES) {

View File

@@ -29,19 +29,17 @@ import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@MediumTest
class FrequencyChartTest : BaseViewTest() {
private var view: FrequencyChart? = null
private lateinit var view: FrequencyChart
@Before
override fun setUp() {
super.setUp()
fixtures.purgeHabits(habitList)
val habit = fixtures.createLongHabit()
view = FrequencyChart(targetContext)
view!!.setFrequency(
habit.originalEntries.computeWeekdayFrequency(
habit.isNumerical
)
)
view!!.setColor(habit.color.toFixedAndroidColor())
view = FrequencyChart(targetContext).apply {
setFrequency(habit.originalEntries.computeWeekdayFrequency(habit.isNumerical))
setColor(habit.color.toFixedAndroidColor())
}
measureView(view, dpToPixels(300), dpToPixels(100))
}
@@ -54,8 +52,8 @@ class FrequencyChartTest : BaseViewTest() {
@Test
@Throws(Throwable::class)
fun testRender_withDataOffset() {
view!!.onScroll(null, null, -dpToPixels(150), 0f)
view!!.invalidate()
view.onScroll(null, null, -dpToPixels(150), 0f)
view.invalidate()
assertRenders(view, BASE_PATH + "renderDataOffset.png")
}
@@ -69,7 +67,7 @@ class FrequencyChartTest : BaseViewTest() {
@Test
@Throws(Throwable::class)
fun testRender_withTransparentBackground() {
view!!.setIsBackgroundTransparent(true)
view.setIsBackgroundTransparent(true)
assertRenders(view, BASE_PATH + "renderTransparent.png")
}

View File

@@ -31,16 +31,18 @@ import java.io.IOException
@RunWith(AndroidJUnit4::class)
@MediumTest
class RingViewTest : BaseViewTest() {
private var view: RingView? = null
private lateinit var view: RingView
@Before
override fun setUp() {
super.setUp()
view = RingView(targetContext)
view!!.setPercentage(0.6f)
view!!.setText("60%")
view!!.setColor(getAndroidTestColor(0))
view!!.setBackgroundColor(Color.WHITE)
view!!.setThickness(dpToPixels(3))
view = RingView(targetContext).apply {
setPercentage(0.6f)
setText("60%")
setColor(getAndroidTestColor(0))
setBackgroundColor(Color.WHITE)
setThickness(dpToPixels(3))
}
}
@Test
@@ -53,8 +55,8 @@ class RingViewTest : BaseViewTest() {
@Test
@Throws(IOException::class)
fun testRender_withDifferentParams() {
view!!.setPercentage(0.25f)
view!!.setColor(getAndroidTestColor(5))
view.setPercentage(0.25f)
view.setColor(getAndroidTestColor(5))
measureView(view, dpToPixels(200), dpToPixels(200))
assertRenders(view, BASE_PATH + "renderDifferentParams.png")
}

View File

@@ -32,17 +32,18 @@ import org.junit.runner.RunWith
@MediumTest
class ScoreChartTest : BaseViewTest() {
private lateinit var habit: Habit
private var view: ScoreChart? = null
private lateinit var view: ScoreChart
@Before
override fun setUp() {
super.setUp()
fixtures.purgeHabits(habitList)
habit = fixtures.createLongHabit()
val (scores, bucketSize, _, color) = buildState(habit, prefs.firstWeekdayInt, 0)
view = ScoreChart(targetContext)
view!!.setScores(scores.toMutableList())
view!!.setColor(color.toFixedAndroidColor())
view!!.setBucketSize(bucketSize)
view = ScoreChart(targetContext).apply {
setScores(scores.toMutableList())
setColor(color.toFixedAndroidColor())
setBucketSize(bucketSize)
}
measureView(view, dpToPixels(300), dpToPixels(200))
}
@@ -55,8 +56,8 @@ class ScoreChartTest : BaseViewTest() {
@Test
@Throws(Throwable::class)
fun testRender_withDataOffset() {
view!!.onScroll(null, null, -dpToPixels(150), 0f)
view!!.invalidate()
view.onScroll(null, null, -dpToPixels(150), 0f)
view.invalidate()
assertRenders(view, BASE_PATH + "renderDataOffset.png")
}
@@ -71,20 +72,20 @@ class ScoreChartTest : BaseViewTest() {
@Throws(Throwable::class)
fun testRender_withMonthlyBucket() {
val (scores, bucketSize) = buildState(
habit!!,
habit,
prefs.firstWeekdayInt,
2
)
view!!.setScores(scores.toMutableList())
view!!.setBucketSize(bucketSize)
view!!.invalidate()
view.setScores(scores.toMutableList())
view.setBucketSize(bucketSize)
view.invalidate()
assertRenders(view, BASE_PATH + "renderMonthly.png")
}
@Test
@Throws(Throwable::class)
fun testRender_withTransparentBackground() {
view!!.setIsTransparencyEnabled(true)
view.setIsTransparencyEnabled(true)
assertRenders(view, BASE_PATH + "renderTransparent.png")
}
@@ -92,13 +93,13 @@ class ScoreChartTest : BaseViewTest() {
@Throws(Throwable::class)
fun testRender_withYearlyBucket() {
val (scores, bucketSize) = buildState(
habit!!,
habit,
prefs.firstWeekdayInt,
4
)
view!!.setScores(scores.toMutableList())
view!!.setBucketSize(bucketSize)
view!!.invalidate()
view.setScores(scores.toMutableList())
view.setBucketSize(bucketSize)
view.invalidate()
assertRenders(view, BASE_PATH + "renderYearly.png")
}

View File

@@ -29,15 +29,16 @@ import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@MediumTest
class StreakChartTest : BaseViewTest() {
private var view: StreakChart? = null
private lateinit var view: StreakChart
@Before
override fun setUp() {
super.setUp()
fixtures.purgeHabits(habitList)
val (color, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, streaks) = fixtures.createLongHabit()
view = StreakChart(targetContext)
view!!.setColor(color.toFixedAndroidColor())
view!!.setStreaks(streaks.getBest(5))
val habit = fixtures.createLongHabit()
view = StreakChart(targetContext).apply {
setColor(habit.color.toFixedAndroidColor())
setStreaks(habit.streaks.getBest(5))
}
measureView(view, dpToPixels(300), dpToPixels(100))
}
@@ -57,7 +58,7 @@ class StreakChartTest : BaseViewTest() {
@Test
@Throws(Throwable::class)
fun testRender_withTransparentBackground() {
view!!.setIsBackgroundTransparent(true)
view.setIsBackgroundTransparent(true)
assertRenders(view, BASE_PATH + "renderTransparent.png")
}

View File

@@ -22,44 +22,44 @@ import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions
import com.nhaarman.mockitokotlin2.whenever
import org.isoron.uhabits.BaseViewTest
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito
@RunWith(AndroidJUnit4::class)
@MediumTest
class HeaderViewTest : BaseViewTest() {
private var view: HeaderView? = null
private lateinit var view: HeaderView
@Before
override fun setUp() {
super.setUp()
prefs = mock()
view = HeaderView(targetContext, prefs, mock())
view!!.buttonCount = 5
view.buttonCount = 5
measureView(view, dpToPixels(600), dpToPixels(48))
}
@Test
@Throws(Exception::class)
fun testRender() {
Mockito.`when`(prefs.isCheckmarkSequenceReversed).thenReturn(false)
whenever(prefs.isCheckmarkSequenceReversed).thenReturn(false)
assertRenders(view, PATH + "render.png")
Mockito.verify(prefs).isCheckmarkSequenceReversed
Mockito.verifyNoMoreInteractions(prefs)
verify(prefs).isCheckmarkSequenceReversed
verifyNoMoreInteractions(prefs)
}
@Test
@Throws(Exception::class)
fun testRender_reverse() {
doReturn(true).whenever(prefs).isCheckmarkSequenceReversed
// Mockito.`when`(prefs.isCheckmarkSequenceReversed).thenReturn(true)
assertRenders(view, PATH + "render_reverse.png")
Mockito.verify(prefs).isCheckmarkSequenceReversed
Mockito.verifyNoMoreInteractions(prefs)
verify(prefs).isCheckmarkSequenceReversed
verifyNoMoreInteractions(prefs)
}
companion object {

View File

@@ -45,8 +45,6 @@ class HintViewTest : BaseViewTest() {
val text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
doReturn(true).whenever(list).shouldShow()
doReturn(text).whenever(list).pop()
// Mockito.`when`(list.shouldShow()).thenReturn(true)
// Mockito.`when`(list.pop()).thenReturn(text)
view.showNext()
skipAnimation(view)
}

View File

@@ -27,11 +27,11 @@ import org.junit.Test
import java.util.HashMap
class AndroidDatabaseTest : BaseAndroidTest() {
private var db: AndroidDatabase? = null
private lateinit var db: AndroidDatabase
override fun setUp() {
super.setUp()
db = AndroidDatabase(SQLiteDatabase.create(null), null)
db!!.execute("create table test(color int, name string)")
db.execute("create table test(color int, name string)")
}
@Test
@@ -40,8 +40,8 @@ class AndroidDatabaseTest : BaseAndroidTest() {
val map = HashMap<String, Any?>()
map["name"] = "asd"
map["color"] = null
db!!.insert("test", map)
val c: Cursor = db!!.query("select * from test")
db.insert("test", map)
val c: Cursor = db.query("select * from test")
c.moveToNext()
assertNull(c.getInt(0))
MatcherAssert.assertThat(c.getString(1), IsEqual.equalTo("asd"))

View File

@@ -38,10 +38,11 @@ class TargetWidgetTest : BaseViewTest() {
super.setUp()
setTheme(R.style.WidgetTheme)
prefs.widgetOpacity = 255
habit = fixtures.createLongNumericalHabit()
habit.color = PaletteColor(11)
habit.frequency = Frequency.WEEKLY
habit.recompute()
habit = fixtures.createLongNumericalHabit().apply {
color = PaletteColor(11)
frequency = Frequency.WEEKLY
recompute()
}
val widget = TargetWidget(targetContext, 0, habit)
view = convertToView(widget, 400, 400)
}

View File

@@ -32,25 +32,24 @@ import java.io.IOException
@RunWith(AndroidJUnit4::class)
@MediumTest
class CheckmarkWidgetViewTest : BaseViewTest() {
private var view: CheckmarkWidgetView? = null
private lateinit var view: CheckmarkWidgetView
@Before
override fun setUp() {
super.setUp()
setTheme(R.style.WidgetTheme)
val habit = fixtures.createShortHabit()
val name = habit.name
val computedEntries = habit.computedEntries
val scores = habit.scores
val today = getTodayWithOffset()
view = CheckmarkWidgetView(targetContext)
val score = scores[today].value
val percentage = score.toFloat()
view!!.activeColor = getAndroidTestColor(0)
view!!.entryState = computedEntries.get(today).value
view!!.entryValue = computedEntries.get(today).value
view!!.percentage = percentage
view!!.name = name
view!!.refresh()
view = CheckmarkWidgetView(targetContext).apply {
activeColor = getAndroidTestColor(0)
entryState = computedEntries.get(today).value
entryValue = computedEntries.get(today).value
percentage = score.toFloat()
name = habit.name
}
view.refresh()
measureView(view, dpToPixels(100), dpToPixels(200))
}

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