diff --git a/app/build.gradle b/app/build.gradle index b4711913..69432687 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,16 +1,16 @@ plugins { id 'com.android.application' id 'kotlin-android' + id 'org.jetbrains.kotlin.plugin.serialization' } android { - compileSdkVersion 30 - buildToolsVersion "30.0.3" + compileSdk 35 defaultConfig { applicationId "otus.homework.customview" minSdkVersion 23 - targetSdkVersion 30 + targetSdkVersion 35 versionCode 1 versionName "1.0" @@ -24,22 +24,24 @@ android { } } compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 } kotlinOptions { - jvmTarget = '1.8' + jvmTarget = '17' } + namespace 'otus.homework.customview' } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" - implementation 'androidx.core:core-ktx:1.3.2' - implementation 'androidx.appcompat:appcompat:1.2.0' - implementation 'com.google.android.material:material:1.3.0' - implementation 'androidx.constraintlayout:constraintlayout:2.0.4' - testImplementation 'junit:junit:4.+' - androidTestImplementation 'androidx.test.ext:junit:1.1.2' - androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' + implementation 'androidx.core:core-ktx:1.15.0' + implementation 'androidx.appcompat:appcompat:1.7.0' + implementation 'com.google.android.material:material:1.12.0' + implementation 'androidx.constraintlayout:constraintlayout:2.2.0' + implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0-RC' + testImplementation 'junit:junit:4.13.2' + androidTestImplementation 'androidx.test.ext:junit:1.2.1' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1' } \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index efd1e519..59a7d4f9 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,7 +1,6 @@ + xmlns:android="http://schemas.android.com/apk/res/android"> - + diff --git a/app/src/main/java/otus/homework/customview/ExpensesInfoItem.kt b/app/src/main/java/otus/homework/customview/ExpensesInfoItem.kt new file mode 100644 index 00000000..5bafadda --- /dev/null +++ b/app/src/main/java/otus/homework/customview/ExpensesInfoItem.kt @@ -0,0 +1,18 @@ +package otus.homework.customview + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable + +@Serializable +data class ExpensesInfoItem( + @SerialName("id") + val id: Int = 0, + @SerialName("name") + val name: String = "", + @SerialName("amount") + val amount: Int = 0, + @SerialName("category") + val category: String = "", + @SerialName("time") + val time: Long = 0 +) diff --git a/app/src/main/java/otus/homework/customview/ExpensesRepository.kt b/app/src/main/java/otus/homework/customview/ExpensesRepository.kt new file mode 100644 index 00000000..8c6d08fc --- /dev/null +++ b/app/src/main/java/otus/homework/customview/ExpensesRepository.kt @@ -0,0 +1,16 @@ +package otus.homework.customview + +import android.content.Context +import kotlinx.serialization.json.Json + + +class ExpensesRepository(private val context: Context) { + fun getExpenses(): List { + val payloadString = context.resources.openRawResource(R.raw.payload).bufferedReader().use { it.readText() } + return Json.decodeFromString>(payloadString) + } + + fun getExpensesByCategory(category: String): List { + return getExpenses().filter { it.category == category } + } +} \ No newline at end of file diff --git a/app/src/main/java/otus/homework/customview/Extensions.kt b/app/src/main/java/otus/homework/customview/Extensions.kt new file mode 100644 index 00000000..6cf81a18 --- /dev/null +++ b/app/src/main/java/otus/homework/customview/Extensions.kt @@ -0,0 +1,25 @@ +package otus.homework.customview + +import android.content.Context +import android.graphics.Canvas +import android.text.StaticLayout +import android.util.TypedValue +import androidx.core.graphics.withTranslation + +fun Context.dpToPx(dp: Int): Float { + return dp.toFloat() * this.resources.displayMetrics.density +} + +fun Context.spToPx(sp: Int): Float { + return TypedValue.applyDimension( + TypedValue.COMPLEX_UNIT_SP, + sp.toFloat(), + this.resources.displayMetrics + ) +} + +fun StaticLayout.draw(canvas: Canvas, x: Float, y: Float) { + canvas.withTranslation(x, y) { + draw(this) + } +} \ No newline at end of file diff --git a/app/src/main/java/otus/homework/customview/LineChartFragment.kt b/app/src/main/java/otus/homework/customview/LineChartFragment.kt new file mode 100644 index 00000000..06becdbe --- /dev/null +++ b/app/src/main/java/otus/homework/customview/LineChartFragment.kt @@ -0,0 +1,53 @@ +package otus.homework.customview + +import android.graphics.Color +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment + +private const val CATEGORY = "category" +private const val COLOR = "color" + +class LineChartFragment : Fragment() { + private var category: String? = null + private var color: Int = Color.RED + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + arguments?.let { + category = it.getString(CATEGORY) + color = it.getInt(COLOR) + } + } + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?, + ): View? { + return inflater.inflate(R.layout.fragment_line_chart, container, false) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + val lineChart = view.findViewById(R.id.line_chart) + category?.let { + lineChart.setDataAndColor( + ExpensesRepository(requireContext()).getExpensesByCategory(it), + color + ) + } + } + + companion object { + @JvmStatic + fun newInstance(category: String, color: Int) = + LineChartFragment().apply { + arguments = Bundle().apply { + putString(CATEGORY, category) + putInt(COLOR, color) + } + } + } +} \ No newline at end of file diff --git a/app/src/main/java/otus/homework/customview/LineChartInterface.kt b/app/src/main/java/otus/homework/customview/LineChartInterface.kt new file mode 100644 index 00000000..06c3f714 --- /dev/null +++ b/app/src/main/java/otus/homework/customview/LineChartInterface.kt @@ -0,0 +1,5 @@ +package otus.homework.customview + +interface LineChartInterface { + fun setDataAndColor(expensesInfoList: List, color: Int) +} \ No newline at end of file diff --git a/app/src/main/java/otus/homework/customview/LineChartView.kt b/app/src/main/java/otus/homework/customview/LineChartView.kt new file mode 100644 index 00000000..4489342c --- /dev/null +++ b/app/src/main/java/otus/homework/customview/LineChartView.kt @@ -0,0 +1,353 @@ +package otus.homework.customview + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.DashPathEffect +import android.graphics.Paint +import android.graphics.Rect +import android.graphics.Typeface +import android.os.Parcelable +import android.text.TextPaint +import android.util.AttributeSet +import android.view.View +import java.text.SimpleDateFormat +import java.util.Calendar +import java.util.Date +import java.util.Locale +import kotlin.math.ceil +import kotlin.math.pow + +class LineChartView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : + View(context, attrs), LineChartInterface { + + data class ExpensesInfoInternal( + val category: String = "", + val amount: Int = 0, + val dayNumber: Int = 0, + val dayOfMonth: Int = 0, + val month: String = "", + val year: Int = 0, + ) + + data class LineChartViewState( + private val savedState: Parcelable?, + val dataList: List, + ) : BaseSavedState(savedState), Parcelable + + private val paddings = context.dpToPx(20) + private val textMargins = context.dpToPx(6) + private val textsSize = context.spToPx(12) + private val largeTextsSize = context.spToPx(16) + private var textHeight = 0 + private var categoryExpensesText = "" + private var categoryExpensesTextWidth = 0F + private var categoryExpensesTextHeight = 0 + + private var chartHeight = 0F + private var chartTopPosition = 0F + private var chartBottomPosition = 0F + private var horizontalStep = 0 + private var verticalStep = 0 + private var numberOfDaysForChart = 0 + + private val textsPaint = TextPaint().apply { + color = Color.BLACK + textSize = textsSize + isAntiAlias = true + } + private val textRect = Rect() + private val largeTextsPaint = TextPaint().apply { + color = Color.BLACK + typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD) + textSize = largeTextsSize + isAntiAlias = true + setShadowLayer(5F, 3F, 3F, Color.GRAY) + } + + private val axisPaint = Paint().apply { + color = Color.BLACK + style = Paint.Style.STROKE + strokeWidth = 5F + isAntiAlias = true + setShadowLayer(5F, 3F, 3F, Color.GRAY) + } + + private val gridLinesPaint = Paint().apply { + color = Color.GRAY + style = Paint.Style.STROKE + pathEffect = DashPathEffect(floatArrayOf(10F, 10F), 0F) + strokeWidth = 5F + isAntiAlias = true + } + + private val lineChartPaint = Paint().apply { + color = Color.RED + style = Paint.Style.STROKE + strokeWidth = 5F + isAntiAlias = true + setShadowLayer(5F, 3F, 3F, Color.GRAY) + } + + private val pointPaint = Paint().apply { + color = Color.RED + isAntiAlias = true + setShadowLayer(5F, 3F, 3F, Color.GRAY) + } + + private val expensesInfoListInternal = ArrayList() + + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + val initSize = + minOf(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec)) + val maxAmount = expensesInfoListInternal.maxOf { it.amount } + + val maxAmountPeriod = 10.0.pow((maxAmount.toString().length - 1).toDouble()) + val maxAmountRoundedToUp = ceil(maxAmount.toDouble() / maxAmountPeriod) * maxAmountPeriod + verticalStep = maxAmountRoundedToUp.toInt() / 4 + horizontalStep = (initSize - paddings * 2).toInt() / (numberOfDaysForChart - 1) + + textsPaint.getTextBounds( + maxAmountRoundedToUp.toString(), + 0, + maxAmountRoundedToUp.toString().length, + textRect + ) + textHeight = textRect.height() + + largeTextsPaint.getTextBounds( + categoryExpensesText, + 0, + categoryExpensesText.length, + textRect + ) + categoryExpensesTextWidth = largeTextsPaint.measureText(categoryExpensesText) + categoryExpensesTextHeight = textRect.height() + + chartHeight = + initSize - paddings * 2 - textHeight * 2 - categoryExpensesTextHeight - textMargins * 3 + chartTopPosition = paddings + textHeight + categoryExpensesTextHeight + textMargins * 2 + chartBottomPosition = + paddings + textHeight + categoryExpensesTextHeight + textMargins * 2 + chartHeight + + setMeasuredDimension(initSize, initSize) + } + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + //Draw Header + canvas.drawText( + categoryExpensesText, + paddings + horizontalStep * (numberOfDaysForChart - 1) / 2 - categoryExpensesTextWidth / 2, + paddings + categoryExpensesTextHeight, + largeTextsPaint + ) + //DrawAxis + canvas.drawLine( + paddings, + chartTopPosition, + paddings, + chartBottomPosition, + axisPaint + ) + canvas.drawLine( + paddings, + chartBottomPosition, + paddings + horizontalStep * (numberOfDaysForChart - 1), + chartBottomPosition, + axisPaint + ) + //Draw vertical steps and text + for (i in 1..4) { + canvas.drawLine( + paddings, + chartTopPosition + chartHeight * (i - 1) / 4, + paddings + horizontalStep * (numberOfDaysForChart - 1), + chartTopPosition + chartHeight * (i - 1) / 4, + gridLinesPaint + ) + canvas.drawText( + (verticalStep * i).toString(), + paddings + textMargins, + chartTopPosition + chartHeight * (4 - i) / 4 - textMargins, + textsPaint + ) + } + //Draw horizontal steps + for (i in 1.. + val amountText = expenseInfoData.amount.toString() + val dateText = + if (index == 0 || expenseInfoData.month != expensesInfoListInternal[index - 1].month) { + "${expenseInfoData.dayOfMonth} ${expenseInfoData.month}" + } else { + "${expenseInfoData.dayOfMonth}" + } + + val currentStopY = + chartBottomPosition - expenseInfoData.amount * chartHeight / (verticalStep * 4) + val currentStopX = paddings + horizontalStep * index + + textsPaint.getTextBounds(dateText, 0, dateText.length, textRect) + val textX = when (index) { + 0 -> 0F + expensesInfoListInternal.size - 1 -> textsPaint.measureText(dateText) + else -> textsPaint.measureText(dateText) / 2 + } + + canvas.drawText( + dateText, + currentStopX - textX, + chartBottomPosition + textMargins + textHeight, + textsPaint + ) + + if (index > 0) { + canvas.drawLine( + paddings + horizontalStep * (index - 1), + previousStopY, + currentStopX, + currentStopY, + lineChartPaint + ) + } + if (expenseInfoData.amount > 0) { + canvas.drawCircle(currentStopX, currentStopY, 7F, pointPaint) + largeTextsPaint.getTextBounds(amountText, 0, amountText.length, textRect) + val amountTextWidth = largeTextsPaint.measureText(amountText) + canvas.drawText( + amountText, + currentStopX - amountTextWidth / 2, + currentStopY - textMargins, + largeTextsPaint + ) + } + + previousStopY = currentStopY + } + } + + override fun onSaveInstanceState(): Parcelable { + val state = super.onSaveInstanceState() + return LineChartViewState( + state, + expensesInfoListInternal + ) + } + + override fun onRestoreInstanceState(state: Parcelable?) { + val lineChartViewState = state as? LineChartViewState + super.onRestoreInstanceState(lineChartViewState?.superState ?: state) + expensesInfoListInternal.clear() + expensesInfoListInternal.addAll(lineChartViewState?.dataList ?: arrayListOf()) + } + + private fun getDay(time: Long): Int { + val calendar = Calendar.getInstance() + calendar.timeInMillis = time + return calendar.get(Calendar.DAY_OF_MONTH) + } + + private fun getMonth(time: Long): String { + val date = Date(time) + val format = SimpleDateFormat("MMM", Locale.getDefault()) + return format.format(date) + } + + private fun getYear(time: Long): Int { + val calendar = Calendar.getInstance() + calendar.timeInMillis = time + return calendar.get(Calendar.YEAR) + } + + override fun setDataAndColor(expensesInfoList: List, color: Int) { + lineChartPaint.color = color + pointPaint.color = color + expensesInfoListInternal.clear() + categoryExpensesText = String.format( + context.resources.getString(R.string.category_expenses_text), + expensesInfoList[0].category + ) + val minTimeForChart = expensesInfoList.minOf { it.time } - 86400 + val minTimeInDays = (expensesInfoList.minOf { it.time } / 86400).toInt() + val maxTimeInDays = (expensesInfoList.maxOf { it.time } / 86400).toInt() + numberOfDaysForChart = maxTimeInDays - minTimeInDays + 3 + + var previousDayNumber = 0 + expensesInfoList.forEachIndexed { index, expensesInfoItem -> + if (index == 0) { + expensesInfoListInternal.add( + ExpensesInfoInternal( + category = expensesInfoItem.category, + amount = 0, + dayNumber = 0, + dayOfMonth = getDay(minTimeForChart * 1000), + month = getMonth(minTimeForChart * 1000), + year = getYear(minTimeForChart * 1000) + ) + ) + } + + val dayNumber = (expensesInfoItem.time / 86400 - minTimeInDays).toInt() + 1 + + while (previousDayNumber + 1 < dayNumber) { + val time = (previousDayNumber + minTimeInDays) * 86400000L + expensesInfoListInternal.add( + ExpensesInfoInternal( + category = expensesInfoItem.category, + amount = 0, + dayNumber = ++previousDayNumber, + dayOfMonth = getDay(time), + month = getMonth(time), + year = getYear(time) + ) + ) + } + val indexExpensesInfoListInternalItem = + expensesInfoListInternal.indexOfFirst { + it.dayNumber == + dayNumber + && it.category == expensesInfoItem.category + } + if (indexExpensesInfoListInternalItem >= 0) { + expensesInfoListInternal[indexExpensesInfoListInternalItem] = + expensesInfoListInternal[indexExpensesInfoListInternalItem].copy(amount = expensesInfoListInternal[indexExpensesInfoListInternalItem].amount + expensesInfoItem.amount) + } else { + expensesInfoListInternal.add( + ExpensesInfoInternal( + category = expensesInfoItem.category, + amount = expensesInfoItem.amount, + dayNumber = dayNumber, + dayOfMonth = getDay(expensesInfoItem.time * 1000), + month = getMonth(expensesInfoItem.time * 1000), + year = getYear(expensesInfoItem.time * 1000) + ) + ) + } + if (index == expensesInfoList.size - 1) { + val time = (dayNumber + minTimeInDays) * 86400000L + expensesInfoListInternal.add( + ExpensesInfoInternal( + category = expensesInfoItem.category, + amount = 0, + dayNumber = dayNumber + 1, + dayOfMonth = getDay(time), + month = getMonth(time), + year = getYear(time) + ) + ) + } + previousDayNumber = dayNumber + } + } +} \ No newline at end of file diff --git a/app/src/main/java/otus/homework/customview/MainActivity.kt b/app/src/main/java/otus/homework/customview/MainActivity.kt index 78cb9448..31114ce4 100644 --- a/app/src/main/java/otus/homework/customview/MainActivity.kt +++ b/app/src/main/java/otus/homework/customview/MainActivity.kt @@ -1,11 +1,12 @@ package otus.homework.customview -import androidx.appcompat.app.AppCompatActivity import android.os.Bundle +import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) + supportActionBar?.hide() } } \ No newline at end of file diff --git a/app/src/main/java/otus/homework/customview/PieChartFragment.kt b/app/src/main/java/otus/homework/customview/PieChartFragment.kt new file mode 100644 index 00000000..b82d1b1a --- /dev/null +++ b/app/src/main/java/otus/homework/customview/PieChartFragment.kt @@ -0,0 +1,35 @@ +package otus.homework.customview + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment + +class PieChartFragment : Fragment() { + + override fun onCreateView( + inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?, + ): View? { + return inflater.inflate(R.layout.fragment_pie_chart, container, false) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + val pieChart = view.findViewById(R.id.pie_chart) + pieChart.setData(ExpensesRepository(requireContext()).getExpenses()) + pieChart.setOnCategoryClickListener(object : PieChartView.OnCategoryClickListener { + override fun onClick(categoryWithColor: Pair) { + requireActivity().supportFragmentManager.beginTransaction() + .replace( + R.id.main_container, + LineChartFragment.newInstance(categoryWithColor.first, categoryWithColor.second) + ) + .addToBackStack(null) + .commit() + } + + }) + } +} \ No newline at end of file diff --git a/app/src/main/java/otus/homework/customview/PieChartInterface.kt b/app/src/main/java/otus/homework/customview/PieChartInterface.kt new file mode 100644 index 00000000..d3156293 --- /dev/null +++ b/app/src/main/java/otus/homework/customview/PieChartInterface.kt @@ -0,0 +1,6 @@ +package otus.homework.customview + +interface PieChartInterface { + fun setOnCategoryClickListener(onCategoryClickListener: PieChartView.OnCategoryClickListener) + fun setData(expensesInfoList: List) +} \ No newline at end of file diff --git a/app/src/main/java/otus/homework/customview/PieChartView.kt b/app/src/main/java/otus/homework/customview/PieChartView.kt new file mode 100644 index 00000000..444345a8 --- /dev/null +++ b/app/src/main/java/otus/homework/customview/PieChartView.kt @@ -0,0 +1,322 @@ +package otus.homework.customview + +import android.content.Context +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.Rect +import android.graphics.RectF +import android.os.Parcelable +import android.text.Layout +import android.text.StaticLayout +import android.text.TextDirectionHeuristics +import android.text.TextPaint +import android.util.AttributeSet +import android.view.MotionEvent +import android.view.View +import androidx.annotation.ColorInt +import kotlin.math.atan2 +import kotlin.math.min +import kotlin.math.sqrt + +class PieChartView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : + View(context, attrs), PieChartInterface { + + data class ExpensesInfoInternal( + val category: String = "", + val amount: Int = 0, + val percent: Int = 0, + val angle: Float = 0F, + val textHeight: Int = 0, + @ColorInt + val color: Int = 0, + ) + + data class PieChartViewState( + private val savedState: Parcelable?, + val dataList: List, + ) : BaseSavedState(savedState), Parcelable + + private var onClickListener: OnCategoryClickListener? = null + + private val paddings = context.dpToPx(20) + private val textMargins = context.dpToPx(6) + private val amountTextMargins = context.dpToPx(20) + private val textsSize = context.spToPx(16) + private val amountTextSize = context.spToPx(32) + private val smallToFullArcRadiusDiff = context.dpToPx(4).toInt() + private val circleSectionSpace = 2F + + private var pieChartHeight = 0F + private var pieChartFullRadius = 0F + private val pieChartSmallRadius: Float + get() = pieChartFullRadius - smallToFullArcRadiusDiff + private var smallCircleRadius = context.dpToPx(8) + private val smallArcPaddings = paddings + smallToFullArcRadiusDiff + private var arcStrokeWidth = context.dpToPx(72) + private val fullArcRect = RectF() + private val smallArcRect = RectF() + private var centerX = 0F + private var centerY = 0F + private var sumAmount = 0 + private val amountTextRect = Rect() + + private val arcPaint: Paint = Paint().apply { + style = Paint.Style.STROKE + isAntiAlias = true + isDither = true + strokeWidth = arcStrokeWidth + setShadowLayer(15F, 5F, 5F, Color.GRAY) + } + private val smallCirclePaint: Paint = Paint().apply { + isAntiAlias = true + isDither = true + setShadowLayer(5F, 3F, 3F, Color.GRAY) + } + private val textPaint = TextPaint().apply { + color = Color.BLACK + textSize = textsSize + isAntiAlias = true + } + private val amountTextPaint = TextPaint().apply { + color = Color.BLACK + textSize = amountTextSize + isAntiAlias = true + } + + + private val expensesInfoListInternal = ArrayList() + private val textList = ArrayList() + private val colorList = resources.getIntArray(R.array.colors) + + override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { + val initWidth = MeasureSpec.getSize(widthMeasureSpec) + val initHeight = MeasureSpec.getSize(heightMeasureSpec) + + textList.clear() + + var textHeight = expensesInfoListInternal.size * textMargins + paddings + var textHeightForTouchDetect = 0 + expensesInfoListInternal.forEachIndexed { index, expensesInfoInternal -> + val text = String.format( + context.resources.getString(R.string.text_description), + expensesInfoInternal.amount, + expensesInfoInternal.percent, + expensesInfoInternal.category + ) + val textLayout = getStaticLayout(text, initWidth - (paddings * 2).toInt()) + textHeight += textLayout.height + textHeightForTouchDetect += textLayout.height + textMargins.toInt() + expensesInfoListInternal[index] = + expensesInfoInternal.copy(textHeight = textHeightForTouchDetect) + textList.add(textLayout) + } + + pieChartHeight = if (initHeight / 2 < textHeight) initHeight - textHeight + else (initHeight / 2).toFloat() + val viewHeight = pieChartHeight + textHeight.toInt() + + pieChartFullRadius = + (min(pieChartHeight, initWidth.toFloat()) - paddings * 2 - arcStrokeWidth) / 2 + arcStrokeWidth = pieChartFullRadius / 2.1F + + smallCircleRadius = (textHeight - paddings) / expensesInfoListInternal.size / 3 + + centerX = smallArcPaddings + pieChartSmallRadius + arcStrokeWidth / 2 + centerY = smallArcPaddings + pieChartSmallRadius + arcStrokeWidth / 2 + + with(fullArcRect) { + top = paddings + arcStrokeWidth / 2 + bottom = paddings + pieChartFullRadius * 2 + arcStrokeWidth / 2 + left = paddings + arcStrokeWidth / 2 + right = paddings + pieChartFullRadius * 2 + arcStrokeWidth / 2 + } + with(smallArcRect) { + top = smallArcPaddings + arcStrokeWidth / 2 + bottom = smallArcPaddings + pieChartSmallRadius * 2 + arcStrokeWidth / 2 + left = smallArcPaddings + arcStrokeWidth / 2 + right = smallArcPaddings + pieChartSmallRadius * 2 + arcStrokeWidth / 2 + } + + setMeasuredDimension(initWidth, viewHeight.toInt()) + } + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + drawText(canvas) + drawPieChart(canvas) + } + + override fun onTouchEvent(event: MotionEvent?): Boolean { + event ?: return false + when (event.action) { + MotionEvent.ACTION_DOWN -> { + val clickedCategoryWithColor = getClickedCategoryWithColor(event.x, event.y) + if (clickedCategoryWithColor.first != NO_CATEGORY) { + onClickListener?.onClick(clickedCategoryWithColor) + } + } + } + return true + } + + override fun onSaveInstanceState(): Parcelable { + val state = super.onSaveInstanceState() + return PieChartViewState(state, expensesInfoListInternal) + } + + override fun onRestoreInstanceState(state: Parcelable?) { + val pieChartViewState = state as? PieChartViewState + super.onRestoreInstanceState(pieChartViewState?.superState ?: state) + expensesInfoListInternal.clear() + expensesInfoListInternal.addAll(pieChartViewState?.dataList ?: arrayListOf()) + } + + private fun getClickedCategoryWithColor(xPos: Float, yPos: Float): Pair { + val x = xPos - centerX + val y = yPos - centerY + + val radius = sqrt(x * x + y * y) + if (radius > pieChartSmallRadius - arcStrokeWidth / 2 && radius < pieChartFullRadius + arcStrokeWidth / 2) { + var angle = Math.toDegrees(atan2(y.toDouble(), x.toDouble()) + Math.PI / 2) + angle = if (angle < 0) angle + 360 else angle + + var startAngle = 0F + expensesInfoListInternal.forEach { expensesInfoInternal -> + val endAngle = startAngle + expensesInfoInternal.angle + if (angle in startAngle..endAngle) return expensesInfoInternal.category to expensesInfoInternal.color + startAngle = endAngle + } + } else if (radius < pieChartSmallRadius - arcStrokeWidth / 2) { + return NO_CATEGORY to 0 + } + + if (yPos > pieChartHeight + textMargins) { + expensesInfoListInternal.forEach { + if (yPos < pieChartHeight + textMargins + it.textHeight) return it.category to it.color + } + } + + return NO_CATEGORY to 0 + } + + private fun drawPieChart(canvas: Canvas) { + var startAngle = -90F + expensesInfoListInternal.forEachIndexed { index, expensesInfoInternal -> + if (index == 0 || expensesInfoInternal.amount == expensesInfoListInternal[0].amount) { + canvas.drawArc( + fullArcRect, + startAngle, + expensesInfoInternal.angle - circleSectionSpace, + false, + arcPaint.apply { + color = expensesInfoInternal.color + strokeWidth = arcStrokeWidth + smallToFullArcRadiusDiff * 2 + }) + + } else { + canvas.drawArc( + smallArcRect, + startAngle, + expensesInfoInternal.angle - circleSectionSpace, + false, + arcPaint.apply { + color = expensesInfoInternal.color + strokeWidth = arcStrokeWidth + }) + } + startAngle += expensesInfoInternal.angle + } + } + + private fun getStaticLayout(text: CharSequence, viewWidth: Int): StaticLayout { + return StaticLayout.Builder + .obtain(text, 0, text.length, textPaint, viewWidth) + .setAlignment(Layout.Alignment.ALIGN_NORMAL) + .setTextDirection(TextDirectionHeuristics.LOCALE) + .setLineSpacing(0F, 1F) + .build() + } + + private fun drawText(canvas: Canvas) { + var textY = pieChartHeight + textMargins + textList.forEachIndexed { index, it -> + it.draw(canvas, paddings + smallCircleRadius * 2 + textMargins, textY) + canvas.drawCircle( + paddings + smallCircleRadius, + textY + it.height / 2, + smallCircleRadius, + smallCirclePaint.apply { + color = expensesInfoListInternal[index].color + } + ) + textY += it.height + textMargins + } + + var amountText = "$sumAmount" + amountTextPaint.getTextBounds(amountText, 0, amountText.length, amountTextRect) + var amountTextWidth = amountTextPaint.measureText(amountText) + var amountTextHeight = amountTextRect.height() + canvas.drawText( + amountText, + centerX - amountTextWidth / 2, + centerY + amountTextHeight / 2 - amountTextMargins, + amountTextPaint + ) + amountText = context.resources.getString(R.string.currency) + amountTextPaint.getTextBounds(amountText, 0, amountText.length, amountTextRect) + amountTextWidth = amountTextPaint.measureText(amountText) + amountTextHeight = amountTextRect.height() + canvas.drawText( + amountText, + centerX - amountTextWidth / 2, + centerY + amountTextHeight / 2 + amountTextMargins, + amountTextPaint + ) + } + + override fun setOnCategoryClickListener(onCategoryClickListener: OnCategoryClickListener) { + this.onClickListener = onCategoryClickListener + } + + override fun setData(expensesInfoList: List) { + expensesInfoListInternal.clear() + expensesInfoList.forEach { expensesInfoItem -> + val index = + expensesInfoListInternal.indexOfFirst { it.category == expensesInfoItem.category } + if (index >= 0) { + expensesInfoListInternal[index] = + expensesInfoListInternal[index].copy(amount = expensesInfoListInternal[index].amount + expensesInfoItem.amount) + } else expensesInfoListInternal.add( + ExpensesInfoInternal( + category = expensesInfoItem.category, + amount = expensesInfoItem.amount + ) + ) + } + expensesInfoListInternal.sortByDescending { it.amount } + sumAmount = expensesInfoListInternal.sumOf { it.amount } + + var value = 0.0 + var roundedValue = 0L + var prevRoundedValue: Long + expensesInfoListInternal.forEachIndexed { index, expensesInfoItem -> + value += expensesInfoListInternal[index].amount * 100.0 / sumAmount + prevRoundedValue = roundedValue + roundedValue = Math.round(value) + expensesInfoListInternal[index] = expensesInfoItem.copy( + percent = (roundedValue - prevRoundedValue).toInt(), + angle = 360F * (roundedValue - prevRoundedValue) / 100, + color = colorList[index] + ) + } + } + + companion object { + const val NO_CATEGORY = "" + } + + interface OnCategoryClickListener { + fun onClick(categoryWithColor: Pair) + } +} \ No newline at end of file diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index 79ae6993..5598a7d7 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -1,19 +1,12 @@ - - - - \ No newline at end of file + \ No newline at end of file diff --git a/app/src/main/res/layout/fragment_line_chart.xml b/app/src/main/res/layout/fragment_line_chart.xml new file mode 100644 index 00000000..accafb0e --- /dev/null +++ b/app/src/main/res/layout/fragment_line_chart.xml @@ -0,0 +1,19 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/fragment_pie_chart.xml b/app/src/main/res/layout/fragment_pie_chart.xml new file mode 100644 index 00000000..6a60ee5a --- /dev/null +++ b/app/src/main/res/layout/fragment_pie_chart.xml @@ -0,0 +1,19 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/values/arrays.xml b/app/src/main/res/values/arrays.xml new file mode 100644 index 00000000..6344bc01 --- /dev/null +++ b/app/src/main/res/values/arrays.xml @@ -0,0 +1,15 @@ + + + + @color/red_500 + @color/blue_500 + @color/green_500 + @color/purple_500 + @color/orange_500 + @color/blue_300 + @color/teal_200 + @color/purple_200 + @color/yellow_500 + @color/grey + + \ No newline at end of file diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml index f8c6127d..6bab3702 100644 --- a/app/src/main/res/values/colors.xml +++ b/app/src/main/res/values/colors.xml @@ -1,9 +1,17 @@ - #FFBB86FC + #E91E63 + #3F51B5 + #4CAF50 #FF6200EE - #FF3700B3 + #FF5722 + #64B5F6 #FF03DAC5 + #FFBB86FC + #FFEB3B + #828282 + + #FF3700B3 #FF018786 #FF000000 #FFFFFFFF diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 9213c339..b67de0ce 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,3 +1,6 @@ Custom View + %1$d руб. (%2$d%%) - %3$s + Траты в категории %1$s: + руб. \ No newline at end of file diff --git a/build.gradle b/build.gradle index e47bb55b..447d4d7b 100644 --- a/build.gradle +++ b/build.gradle @@ -1,26 +1,32 @@ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { - ext.kotlin_version = "1.4.32" + ext.kotlin_version = '2.1.0' repositories { google() - jcenter() + mavenCentral() } dependencies { - classpath "com.android.tools.build:gradle:4.1.2" + classpath 'com.android.tools.build:gradle:8.6.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } +plugins{ + id 'org.jetbrains.kotlin.plugin.serialization' version '2.1.0' apply false + id 'org.jetbrains.kotlin.android' version '2.1.0' apply false +} + allprojects { repositories { google() - jcenter() + mavenCentral() } } -task clean(type: Delete) { - delete rootProject.buildDir +tasks.register('clean', Delete) { + delete rootProject.layout.buildDirectory } \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index 98bed167..5436bb11 100644 --- a/gradle.properties +++ b/gradle.properties @@ -18,4 +18,6 @@ android.useAndroidX=true # Automatically convert third-party libraries to use AndroidX android.enableJetifier=true # Kotlin code style for this project: "official" or "obsolete": -kotlin.code.style=official \ No newline at end of file +kotlin.code.style=official +android.nonTransitiveRClass=false +android.nonFinalResIds=false \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index f6b961fd..7454180f 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 8734448b..48c0a02c 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,5 @@ -#Fri Jun 11 17:42:46 MSK 2021 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip diff --git a/gradlew b/gradlew index cccdd3d5..1b6c7873 100755 --- a/gradlew +++ b/gradlew @@ -1,78 +1,129 @@ -#!/usr/bin/env sh +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` +APP_BASE_NAME=${0##*/} # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -81,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" + JAVACMD=java which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the @@ -89,84 +140,95 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=$((i+1)) + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - (0) set -- ;; - (1) set -- "$args0" ;; - (2) set -- "$args0" "$args1" ;; - (3) set -- "$args0" "$args1" "$args2" ;; - (4) set -- "$args0" "$args1" "$args2" "$args3" ;; - (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=$(save "$@") - -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" - -# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong -if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then - cd "$(dirname "$0")" -fi +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index f9553162..107acd32 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,3 +1,19 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @@ -13,15 +29,18 @@ if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init +if "%ERRORLEVEL%" == "0" goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -35,7 +54,7 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% @@ -45,28 +64,14 @@ echo location of your Java installation. goto fail -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell