content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package com.opening.openingassignment.utils import java.text.SimpleDateFormat import java.util.Date fun generateGreeting(): String { val currentTimeMillis = System.currentTimeMillis() val currentDate = Date(currentTimeMillis) val sdf = SimpleDateFormat("HH:mm") val currentTimeString = sdf.format(currentDate) val hour = currentTimeString.substring(0, 2).toInt() val minute = currentTimeString.substring(3).toInt() return when { hour in 5 until 12 -> "Good morning!" hour in 12 until 18 -> "Good afternoon!" else -> "Good evening!" } }
opening_assignment/app/src/main/java/com/opening/openingassignment/utils/GreetingGenerator.kt
1111645289
package com.opening.openingassignment.utils import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Context.CLIPBOARD_SERVICE import android.widget.Toast fun copyToClipboard(text: CharSequence , context: Context) { try { val clipboard = context.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText("akc no.", text) clipboard.setPrimaryClip(clip) Toast.makeText(context, "acknowledgement number copied", Toast.LENGTH_SHORT) .show() } catch (e: Exception) { Toast.makeText(context, "Error while copying number", Toast.LENGTH_SHORT) .show() } }
opening_assignment/app/src/main/java/com/opening/openingassignment/utils/copyToClipboard.kt
1951204641
package com.opening.network import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.openning.network", appContext.packageName) } }
opening_assignment/network/src/androidTest/java/com/opening/network/ExampleInstrumentedTest.kt
3328110359
package com.opening.network import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
opening_assignment/network/src/test/java/com/opening/network/ExampleUnitTest.kt
4268252788
package com.opening.network.di import android.util.Log import com.google.gson.GsonBuilder import com.opening.network.Constants.BASE_URL import com.opening.network.data.api.ApiService import com.opening.network.data.api.RetrofitHeaderInterceptor import com.opening.network.data.repository.DashBoardRepository import okhttp3.EventListener import okhttp3.OkHttpClient import okhttp3.Response import okhttp3.logging.HttpLoggingInterceptor import org.koin.dsl.module import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.io.IOException import java.net.ConnectException import java.net.SocketException import java.util.concurrent.TimeUnit val networkModule = module { val gson = GsonBuilder().setLenient().create() val loggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } fun makeOkHttpClient(httpLoggingInterceptor: HttpLoggingInterceptor): OkHttpClient { return OkHttpClient.Builder() .addInterceptor { chain -> val original = chain.request() // Customize the request val request = original.newBuilder() request.header("Content-Type", "application/x-www-form-urlencoded") var response: Response? try { response = chain.proceed(request.build()) // Customize or return the response response } catch (e: ConnectException) { Log.e("RETROFIT", "ERROR : " + e.localizedMessage) chain.proceed(original) } catch (e: SocketException) { Log.e("RETROFIT", "ERROR : " + e.localizedMessage) chain.proceed(original) } catch (e: IOException) { Log.e("RETROFIT", "ERROR : " + e.localizedMessage) chain.proceed(original) } catch (e: Exception) { Log.e("RETROFIT", "ERROR : " + e.localizedMessage) chain.proceed(original) } } .eventListener(object : EventListener() { }) .addInterceptor(httpLoggingInterceptor) .addInterceptor(RetrofitHeaderInterceptor()) .connectTimeout(120, TimeUnit.SECONDS) .readTimeout(120, TimeUnit.SECONDS) .build() } single { val okHttpClient = makeOkHttpClient(loggingInterceptor) okHttpClient } single { Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .client(get()) .build() } single { get<Retrofit>().create(ApiService::class.java) } single { DashBoardRepository(get()) } }
opening_assignment/network/src/main/java/com/opening/network/di/MainModule.kt
1293035507
package com.opening.network.model data class RecentLink( val app: String, val created_at: String, val domain_id: String, val is_favourite: Boolean, val original_image: String, val smart_link: String, val thumbnail: Any, val times_ago: String, val title: String, val total_clicks: Int, val url_id: Int, val url_prefix: Any, val url_suffix: String, val web_link: String )
opening_assignment/network/src/main/java/com/opening/network/model/RecentLink.kt
3838358300
package com.opening.network.model data class TopLink( val app: String, val created_at: String, val domain_id: String, val is_favourite: Boolean, val original_image: String, val smart_link: String, val thumbnail: Any, val times_ago: String, val title: String, val total_clicks: Int, val url_id: Int, val url_prefix: String, val url_suffix: String, val web_link: String )
opening_assignment/network/src/main/java/com/opening/network/model/TopLink.kt
1013566509
package com.opening.network.model data class Data( val favourite_links: List<Any>, val overall_url_chart: Map<String, Int>, val recent_links: List<TopLink>, val top_links: List<TopLink> )
opening_assignment/network/src/main/java/com/opening/network/model/Data.kt
1783806387
package com.opening.network.model data class DashBoardResponse( val applied_campaign: Int, val data: Data, val extra_income: Double, val links_created_today: Int, val message: String, val startTime: String, val status: Boolean, val statusCode: Int, val support_whatsapp_number: String, val today_clicks: Int, val top_location: String, val top_source: String, val total_clicks: Int, val total_links: Int )
opening_assignment/network/src/main/java/com/opening/network/model/DashBoardResponse.kt
1029430728
package com.opening.network.data.repository import com.opening.network.data.api.ApiService class DashBoardRepository( private val apiService: ApiService ) { suspend fun getData() = apiService.getData() }
opening_assignment/network/src/main/java/com/opening/network/data/repository/DashBoardRepository.kt
3582177429
package com.opening.network.data.response sealed class GenericResponse<out T> { class Success<out T>(val data: T) : GenericResponse<T>() class Error(val message: String) : GenericResponse<Nothing>() object Loading : GenericResponse<Nothing>() }
opening_assignment/network/src/main/java/com/opening/network/data/response/GenericResponse.kt
828392485
package com.opening.network.data.api import okhttp3.Interceptor import okhttp3.Response class RetrofitHeaderInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val originalRequest = chain.request() val modifiedRequest = originalRequest.newBuilder() .addHeader( "Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MjU5MjcsImlhdCI6MTY3NDU1MDQ1MH0.dCkW0ox8tbjJA2GgUx2UEwNlbTZ7Rr38PVFJevYcXFI" ) .build() val response = chain.proceed(modifiedRequest) return response } }
opening_assignment/network/src/main/java/com/opening/network/data/api/RetrofitHeaderInterceptor.kt
3420227303
package com.opening.network.data.api import com.opening.network.model.DashBoardResponse import retrofit2.Response import retrofit2.http.GET interface ApiService { @GET("dashboardNew") suspend fun getData(): Response<DashBoardResponse> }
opening_assignment/network/src/main/java/com/opening/network/data/api/ApiService.kt
1710261969
package com.opening.network object Constants { const val BASE_URL = "https://api.inopenapp.com/api/v1/" }
opening_assignment/network/src/main/java/com/opening/network/Constants.kt
3887447981
package com.example.form import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.form", appContext.packageName) } }
forms/app/src/androidTest/java/com/example/form/ExampleInstrumentedTest.kt
269395152
package com.example.form import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
forms/app/src/test/java/com/example/form/ExampleUnitTest.kt
1017610611
package com.example.form import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.EditText import android.widget.RadioGroup class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val radioGroup = findViewById<RadioGroup>(R.id.radio1) val salaryEditText = findViewById<EditText>(R.id.editTextText8) radioGroup.setOnCheckedChangeListener { group, checkedId -> if (checkedId == R.id.radioButton) { salaryEditText.visibility = View.VISIBLE } else { salaryEditText.visibility = View.INVISIBLE } } } }
forms/app/src/main/java/com/example/form/MainActivity.kt
2902037171
package com.alatoo.coursescheduler import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.alatoo.coursescheduler", appContext.packageName) } }
course-schedule-project/app/src/androidTest/java/com/alatoo/coursescheduler/ExampleInstrumentedTest.kt
3445641616
package com.alatoo.coursescheduler import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
course-schedule-project/app/src/test/java/com/alatoo/coursescheduler/ExampleUnitTest.kt
2486780458
package com.alatoo.coursescheduler.ui.fragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.Observer import androidx.navigation.fragment.findNavController import com.alatoo.coursescheduler.dataBase.DataBase import com.alatoo.coursescheduler.repository.UserRepository import com.alatoo.coursescheduler.databinding.FragmentEditProfileBinding import com.alatoo.coursescheduler.entities.User import com.alatoo.coursescheduler.utils.Constants import com.alatoo.coursescheduler.viewModels.UserViewModel class EditProfileFragment : Fragment() { private lateinit var binding: FragmentEditProfileBinding private lateinit var viewModel: UserViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = FragmentEditProfileBinding.inflate(layoutInflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) var db = DataBase.getDatabase(requireContext()).userDao() val repository = UserRepository(db) viewModel = UserViewModel(repository) var id = 0 viewModel.user.observe(viewLifecycleOwner, Observer{ binding.nameEditText.setText(it[0].name) binding.groupEditText.setText(it[0].course) id = it[0].id }) binding.saveBtn.setOnClickListener { val name = binding.nameEditText.text.toString() val group = binding.groupEditText.text.toString() val user = User(id,name, group) Constants.USER_GROUP = group viewModel.update(user) findNavController().navigateUp() } } }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/ui/fragments/EditProfileFragment.kt
3321882629
package com.alatoo.coursescheduler.ui.fragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import com.alatoo.coursescheduler.adapters.ScheduleRvAdapter import com.alatoo.coursescheduler.databinding.FragmentMainPageBinding import com.alatoo.coursescheduler.utils.Constants import com.alatoo.coursescheduler.viewModels.ScheduleViewModel class MainPageFragment : Fragment() { lateinit var binding: FragmentMainPageBinding val adapter1 = ScheduleRvAdapter() val adapter2 = ScheduleRvAdapter() val adapter3 = ScheduleRvAdapter() val adapter4 = ScheduleRvAdapter() val adapter5 = ScheduleRvAdapter() val adapter6 = ScheduleRvAdapter() val viewModel = ScheduleViewModel() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment viewModel.getSchedule() binding = FragmentMainPageBinding.inflate(layoutInflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) var courses: List<List<String>> = emptyList() viewModel.getSchedule() viewModel.scheduleResponse.observe(viewLifecycleOwner, Observer{ val time = ArrayList<String>(it.values[2]) time.removeAt(0) time.removeAt(0) courses = filterScheduleGroup(it.values) setMonday(courses[0], time) setTuesday(courses[1], time) setWednesday(courses[2], time) setThursday(courses[3], time) setFriday(courses[4], time) setSaturday(courses[5], time) }) } override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) viewModel.getSchedule() } fun filterScheduleGroup(schedule: List<List<String>>): List<List<String>> { val filteredSchedule = mutableListOf<List<String>>() for (entry in schedule) { if (entry.getOrNull(1) == Constants.USER_GROUP) { filteredSchedule.add(entry) } } return filteredSchedule } fun setMonday(courses: List<String>, time: ArrayList<String>){ binding.mondayRv.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false) val array = ArrayList<String>(courses) array.removeAt(0) array.remove(Constants.USER_GROUP) adapter1.setItem(array, time) binding.mondayRv.adapter = adapter1 } fun setTuesday(courses: List<String>, time: ArrayList<String>){ binding.tuestayRv.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false) val array = ArrayList<String>(courses) array.removeAt(0) array.remove(Constants.USER_GROUP) adapter2.setItem(array, time) binding.tuestayRv.adapter = adapter2 } fun setWednesday(courses: List<String>, time: ArrayList<String>){ binding.wednesdayRv.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false) val array = ArrayList<String>(courses) array.removeAt(0) array.remove(Constants.USER_GROUP) adapter3.setItem(array, time) binding.wednesdayRv.adapter = adapter3 } fun setThursday(courses: List<String>, time: ArrayList<String>){ binding.thursdayRv.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false) val array = ArrayList<String>(courses) array.removeAt(0) array.remove(Constants.USER_GROUP) adapter4.setItem(array, time) binding.thursdayRv.adapter = adapter4 } fun setFriday(courses: List<String>, time: ArrayList<String>){ binding.fridayRv.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false) val array = ArrayList<String>(courses) array.removeAt(0) array.remove(Constants.USER_GROUP) adapter5.setItem(array, time) binding.fridayRv.adapter = adapter5 } fun setSaturday(courses: List<String>, time: ArrayList<String>){ binding.saturdayRv.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false) val array = ArrayList<String>(courses) array.removeAt(0) array.remove(Constants.USER_GROUP) adapter6.setItem(array, time) binding.saturdayRv.adapter = adapter6 } }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/ui/fragments/MainPageFragment.kt
3630898887
package com.alatoo.coursescheduler.ui.fragments import android.app.Dialog import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import com.alatoo.coursescheduler.R import com.alatoo.coursescheduler.adapters.CheckListRvAdapter import com.alatoo.coursescheduler.dataBase.DataBase import com.alatoo.coursescheduler.repository.Repository import com.alatoo.coursescheduler.databinding.FragmentCheckListBinding import com.alatoo.coursescheduler.entities.TaskItem import com.alatoo.coursescheduler.viewModels.MainViewModel import com.alatoo.coursescheduler.viewModels.ViewModelFactory class CheckListFragment : Fragment() { private lateinit var binding: FragmentCheckListBinding lateinit var mainViewModel: MainViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = FragmentCheckListBinding.inflate(layoutInflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) var db = DataBase.getDatabase(requireContext()).taskItemDao() val repository = Repository(db) mainViewModel = ViewModelProvider(this, ViewModelFactory(repository)).get(MainViewModel::class.java) val adapter = CheckListRvAdapter() mainViewModel.items.observe(viewLifecycleOwner, Observer { adapter.setList(it) }) binding.checkListRv.layoutManager = LinearLayoutManager(requireContext()) binding.checkListRv.adapter = adapter adapter.update = { mainViewModel.updateItem(it) } binding.addNewTaskBtn.setOnClickListener { callAlertDialogToMaps() } } private fun callAlertDialogToMaps(){ val dialogScreen = Dialog(requireContext()) dialogScreen.setContentView(R.layout.alert_dialog) dialogScreen.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) val createBtn = dialogScreen.findViewById<Button>(R.id.createBtn) val cancelBtn = dialogScreen.findViewById<Button>(R.id.cancelBtn) val input = dialogScreen.findViewById<EditText>(R.id.taskNameEditTxt) createBtn.setOnClickListener { mainViewModel.insertItem(TaskItem(0, input.text.toString())) dialogScreen.dismiss() } cancelBtn.setOnClickListener { dialogScreen.dismiss() } dialogScreen.show() } }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/ui/fragments/CheckListFragment.kt
4097589469
package com.alatoo.coursescheduler.ui.fragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.Observer import androidx.navigation.fragment.findNavController import com.alatoo.coursescheduler.R import com.alatoo.coursescheduler.dataBase.DataBase import com.alatoo.coursescheduler.repository.UserRepository import com.alatoo.coursescheduler.databinding.FragmentProfileBinding import com.alatoo.coursescheduler.viewModels.UserViewModel class ProfileFragment : Fragment() { private lateinit var binding: FragmentProfileBinding private lateinit var viewModel: UserViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = FragmentProfileBinding.inflate(layoutInflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) var db = DataBase.getDatabase(requireContext()).userDao() val repository = UserRepository(db) viewModel = UserViewModel(repository) viewModel.user.observe(viewLifecycleOwner, Observer{ binding.groupTxt.text = "Group: " + it[0].course binding.nameTxt.text = "Name: " + it[0].name }) binding.optionsBtn.setOnClickListener { findNavController().navigate(R.id.action_profileFragment_to_academicCalendarFragment) } binding.editBtn.setOnClickListener { findNavController().navigate(R.id.action_profileFragment_to_editProfileFragment) } } }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/ui/fragments/ProfileFragment.kt
2936273774
package com.alatoo.coursescheduler.ui.fragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebChromeClient import android.webkit.WebSettings import android.webkit.WebViewClient import androidx.navigation.fragment.findNavController import com.alatoo.coursescheduler.R import com.alatoo.coursescheduler.databinding.FragmentAcademicCalendarBinding import com.alatoo.coursescheduler.utils.Constants import com.google.android.material.bottomnavigation.BottomNavigationView class AcademicCalendarFragment : Fragment() { private lateinit var binding: FragmentAcademicCalendarBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = FragmentAcademicCalendarBinding.inflate(layoutInflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val bottomNavigationView = activity?.findViewById<BottomNavigationView>(R.id.bottomNavigationView) bottomNavigationView?.visibility = View.GONE binding.closeBtn.setOnClickListener { findNavController().navigateUp() bottomNavigationView?.visibility = View.VISIBLE } binding.calendarWebView.apply { webViewClient = WebViewClient() settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW loadUrl(Constants.ACADEMIC_CALENDAR) } } }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/ui/fragments/AcademicCalendarFragment.kt
325474960
package com.alatoo.coursescheduler.ui.activities import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.lifecycle.Observer import com.alatoo.coursescheduler.MainActivity import com.alatoo.coursescheduler.R import com.alatoo.coursescheduler.dataBase.DataBase import com.alatoo.coursescheduler.databinding.ActivitySplashScreenBinding import com.alatoo.coursescheduler.repository.UserRepository import com.alatoo.coursescheduler.utils.Constants import com.alatoo.coursescheduler.viewModels.UserViewModel class SplashScreenActivity : AppCompatActivity() { lateinit var binding: ActivitySplashScreenBinding private lateinit var viewModel: UserViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySplashScreenBinding.inflate(layoutInflater) setContentView(binding.root) var db = DataBase.getDatabase(this).userDao() val repository = UserRepository(db) viewModel = UserViewModel(repository) binding.root.alpha = 0f binding.root.animate().setDuration(2500).alpha(1f).withEndAction{ viewModel.user.observe(this, Observer{ if(!it.isEmpty()){ Constants.USER_GROUP = it[0].course val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() }else{ val intent = Intent(this, RegistrationActivity::class.java) startActivity(intent) finish() } }) } } }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/ui/activities/SplashScreenActivity.kt
318647855
package com.alatoo.coursescheduler.ui.activities import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import androidx.lifecycle.Observer import com.alatoo.coursescheduler.MainActivity import com.alatoo.coursescheduler.dataBase.DataBase import com.alatoo.coursescheduler.repository.UserRepository import com.alatoo.coursescheduler.databinding.ActivityRegistrationBinding import com.alatoo.coursescheduler.entities.User import com.alatoo.coursescheduler.utils.Constants import com.alatoo.coursescheduler.viewModels.UserViewModel class RegistrationActivity : AppCompatActivity() { private lateinit var binding: ActivityRegistrationBinding private lateinit var viewModel: UserViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityRegistrationBinding.inflate(layoutInflater) setContentView(binding.root) var db = DataBase.getDatabase(this).userDao() val repository = UserRepository(db) viewModel = UserViewModel(repository) binding.registerBtn.setOnClickListener{ val group = binding.groupEditText.text.toString() val userName = binding.nameEditText.text.toString() Constants.USER_GROUP = group if(!group.isEmpty() && !userName.isEmpty()){ val user = User(0, userName, group) viewModel.save(user) val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() }else{ Toast.makeText(this, "Enter your group and name!", Toast.LENGTH_SHORT).show() } } } }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/ui/activities/RegistrationActivity.kt
1252380944
package com.alatoo.coursescheduler.dataBase import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import androidx.room.Update import com.alatoo.coursescheduler.entities.User @Dao interface UserDao { @Insert suspend fun save(user: User) @Update suspend fun update(user: User) @Query("SELECT * FROM user") fun getUser(): LiveData<List<User>> }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/dataBase/UserDao.kt
1490609939
package com.alatoo.coursescheduler.dataBase import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update import com.alatoo.coursescheduler.entities.TaskItem @Dao interface TaskItemDao { @Insert suspend fun save(item: TaskItem) @Delete suspend fun deleteItem(taskItem: TaskItem) @Query("SELECT * FROM tasks") fun getAllNotes(): LiveData<List<TaskItem>> @Update suspend fun updateItem(taskItem: TaskItem) }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/dataBase/TaskItemDao.kt
129688901
package com.alatoo.coursescheduler.dataBase import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.alatoo.coursescheduler.entities.TaskItem import com.alatoo.coursescheduler.entities.User @Database(entities = [TaskItem::class, User::class], version = 2, exportSchema = false) abstract class DataBase: RoomDatabase() { abstract fun taskItemDao(): TaskItemDao abstract fun userDao(): UserDao companion object{ @Volatile private var INSTANCE: DataBase ?= null fun getDatabase(context: Context): DataBase{ val tempInstance = INSTANCE if(tempInstance!=null){ return tempInstance } synchronized(this){ val instance = Room.databaseBuilder( context.applicationContext, DataBase::class.java, "dataBase" ).build() INSTANCE = instance return instance } } } }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/dataBase/DataBase.kt
1157655668
package com.alatoo.coursescheduler.viewModels import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.alatoo.coursescheduler.repository.Repository import com.alatoo.coursescheduler.entities.TaskItem import kotlinx.coroutines.launch class MainViewModel(private val repository: Repository): ViewModel() { val items = repository.getAllItems() fun insertItem(taskItem: TaskItem){ viewModelScope.launch { repository.insertItem(taskItem) } } fun deleteItem(taskItem: TaskItem){ viewModelScope.launch { repository.deleteItem(taskItem) } } fun updateItem(taskItem: TaskItem){ viewModelScope.launch { repository.updateItem(taskItem) } } }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/viewModels/MainViewModel.kt
1084844703
package com.alatoo.coursescheduler.viewModels import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.alatoo.coursescheduler.repository.Repository class ViewModelFactory(private val repository: Repository) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(MainViewModel::class.java)) { return MainViewModel(repository) as T } throw IllegalArgumentException("Unknown ViewModel class") } }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/viewModels/ViewModelFactory.kt
677097817
package com.alatoo.coursescheduler.viewModels import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.alatoo.coursescheduler.repository.UserRepository import com.alatoo.coursescheduler.entities.User import kotlinx.coroutines.launch class UserViewModel(private val repository: UserRepository): ViewModel() { val user = repository.user fun save(user: User){ viewModelScope.launch { repository.save(user) } } fun update(user: User){ viewModelScope.launch { repository.update(user) } } }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/viewModels/UserViewModel.kt
1853743551
package com.alatoo.coursescheduler.viewModels import android.telecom.Call import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.alatoo.coursescheduler.entities.ScheduleItem import com.alatoo.coursescheduler.repository.ScheduleRepository import kotlinx.coroutines.launch class ScheduleViewModel: ViewModel() { val repository = ScheduleRepository() val scheduleResponse: MutableLiveData<ScheduleItem> = MutableLiveData() fun getSchedule(){ viewModelScope.launch { val response = repository.getSchedule() scheduleResponse.postValue(response.body()) } } }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/viewModels/ScheduleViewModel.kt
3541002230
package com.alatoo.coursescheduler.repository import com.alatoo.coursescheduler.dataBase.TaskItemDao import com.alatoo.coursescheduler.entities.TaskItem class Repository(private val db: TaskItemDao){ fun getAllItems() = db.getAllNotes() suspend fun insertItem(item: TaskItem) = db.save(item) suspend fun updateItem(item: TaskItem) = db.updateItem(item) suspend fun deleteItem(item: TaskItem) = db.deleteItem(item) }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/repository/Repository.kt
1841982533
package com.alatoo.coursescheduler.repository import com.alatoo.coursescheduler.dataBase.UserDao import com.alatoo.coursescheduler.entities.User class UserRepository(private val db: UserDao) { val user = db.getUser() suspend fun save(user: User) = db.save(user) suspend fun update(user: User) = db.update(user) }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/repository/UserRepository.kt
1003757431
package com.alatoo.coursescheduler.repository import com.alatoo.coursescheduler.retrofit.RetrofitInstance class ScheduleRepository { suspend fun getSchedule() = RetrofitInstance.api.getSheetData("AIzaSyAtG2Ad-DnN-O12rMHsW8HQ0hFZ8Fib5B4") }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/repository/ScheduleRepository.kt
2970546944
package com.alatoo.coursescheduler import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.setupWithNavController import com.alatoo.coursescheduler.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val navController = supportFragmentManager.findFragmentById(R.id.fragmentContainerView) as NavHostFragment binding.bottomNavigationView.setupWithNavController(navController.navController) } }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/MainActivity.kt
1740068946
package com.alatoo.coursescheduler.utils object Constants { const val ACADEMIC_CALENDAR = "http://alatoo.edu.kg/view/public/pages/page.xhtml?id=281#gsc.tab=0" var USER_GROUP = "" }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/utils/Constants.kt
4288377814
package com.alatoo.coursescheduler.retrofit import com.alatoo.coursescheduler.entities.ScheduleItem import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Query interface Api { @GET("/v4/spreadsheets/1uLmqF8Re8LVWrlAnLqINADtvv_drylmL6fNfqrUleas/values/B8:N86") suspend fun getSheetData(@Query("key") apiKey: String): Response<ScheduleItem> }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/retrofit/Api.kt
1871215236
package com.alatoo.coursescheduler.retrofit import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class RetrofitInstance { companion object{ private val retrofit by lazy { Retrofit.Builder().baseUrl("https://sheets.googleapis.com") .addConverterFactory(GsonConverterFactory.create()) .build() } val api by lazy { retrofit.create(Api::class.java) } } }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/retrofit/RetrofitInstance.kt
1573701212
package com.alatoo.coursescheduler.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.alatoo.coursescheduler.R import com.alatoo.coursescheduler.databinding.ScheduleHolderItemBinding class ScheduleRvAdapter: RecyclerView.Adapter<ScheduleRvAdapter.ViewHolder>() { private var items: ArrayList<String> = ArrayList() private var times: ArrayList<String> = ArrayList() inner class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { val binding = ScheduleHolderItemBinding.bind(itemView) fun bind(item: String, time: String){ binding.subjectNameTxt.text = item binding.timeTxt.text = time } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val itemView = LayoutInflater.from(parent.context).inflate(R.layout.schedule_holder_item, parent, false) return ViewHolder(itemView) } override fun getItemCount(): Int { return items.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(items[position], times[position]) } fun setItem(newItems: ArrayList<String>, newTime: ArrayList<String>){ items = newItems times = newTime notifyDataSetChanged() } }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/adapters/ScheduleRvAdapter.kt
492767582
package com.alatoo.coursescheduler.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.alatoo.coursescheduler.R import com.alatoo.coursescheduler.databinding.CheckListItemBinding import com.alatoo.coursescheduler.entities.TaskItem class CheckListRvAdapter: RecyclerView.Adapter<CheckListRvAdapter.ViewHolder>() { private var items: List<TaskItem> = emptyList() var delete : ((TaskItem) -> Unit)? = null var update: ((TaskItem) -> Unit)? = null inner class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){ val binding = CheckListItemBinding.bind(itemView) fun bind(item: TaskItem){ binding.taskNameTxt.text = item.name binding.checkbox.isChecked = item.done!! } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val itemView = LayoutInflater.from(parent.context).inflate(R.layout.check_list_item, parent, false) return ViewHolder(itemView) } override fun getItemCount(): Int { return items.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(items[position]) holder.binding.checkbox.setOnCheckedChangeListener { _, isChecked -> if (isChecked) { items[position].done = true update?.invoke(items[position]) }else{ items[position].done = false update?.invoke(items[position]) } } } fun setList(newList: List<TaskItem>) { items = newList notifyDataSetChanged() } }
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/adapters/CheckListRvAdapter.kt
2346574467
package com.alatoo.coursescheduler.entities import java.io.Serializable data class ScheduleItem( val majorDimension: String, val range: String, val values: List<List<String>> ): Serializable
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/entities/ScheduleItem.kt
233996813
package com.alatoo.coursescheduler.entities import android.os.Parcelable import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.android.parcel.Parcelize @Entity("user") @Parcelize data class User( @PrimaryKey(autoGenerate = true) var id: Int, var name: String, val course: String ): Parcelable
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/entities/User.kt
3659893697
package com.alatoo.coursescheduler.entities import android.os.Parcelable import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.android.parcel.Parcelize @Entity("tasks") @Parcelize data class TaskItem( @PrimaryKey(autoGenerate = true) var id: Int, var name: String, var done: Boolean? = false ): Parcelable
course-schedule-project/app/src/main/java/com/alatoo/coursescheduler/entities/TaskItem.kt
2910834400
package com.semuju.gemini_image_describer import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.semuju.gemini_image_describer", appContext.packageName) } }
gemini-image-describer/app/src/androidTest/java/com/semuju/gemini_image_describer/ExampleInstrumentedTest.kt
1843959869
package com.semuju.gemini_image_describer import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
gemini-image-describer/app/src/test/java/com/semuju/gemini_image_describer/ExampleUnitTest.kt
381672695
package com.semuju.gemini_image_describer import android.graphics.Bitmap import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.ai.client.generativeai.BuildConfig import com.google.ai.client.generativeai.GenerativeModel import com.google.ai.client.generativeai.type.GenerateContentResponse import com.google.ai.client.generativeai.type.content import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch class MainViewModel(): ViewModel() { private val mMainUIState = MutableStateFlow(MainUIState()) val uiState = mMainUIState.asStateFlow() private val geminiModel by lazy { GenerativeModel( modelName = "gemini-pro-vision", apiKey = "YOUR_API_KEY_HERE", ) } fun generateDescription(image: Bitmap) { viewModelScope.launch { mMainUIState.value = mMainUIState.value.copy(isLoading = true) val chunks = mutableListOf<GenerateContentResponse>() var chunksCount = 0 launch{ geminiModel.generateContentStream( content { image(image) text("You are to describe this image in painstaking detail. If the image contains some long string of text, summarize it and provide and explanation for it, also make sure to give your observation about what you think the image means or how the image came about. make sure to put two headings Explanation and Observation for the relevant parts and you MUST answer in markdown") } ).collect{ chunk -> mMainUIState.value = mMainUIState.value.copy( isLoading = false ) chunks.add(chunk) chunksCount++ } } launch { while (mMainUIState.value.isLoading) { delay(200) } var sentChunks = 0 while (sentChunks < chunksCount) { chunks[sentChunks].text?.forEach { mMainUIState.value = mMainUIState.value.copy( explanation = mMainUIState.value.explanation + it ) delay(2) } sentChunks++ } } } } fun clearExplanation() { mMainUIState.value = mMainUIState.value.copy(explanation = "") } } data class MainUIState( val isLoading: Boolean = false, val explanation: String = "", val error: String = "" )
gemini-image-describer/app/src/main/java/com/semuju/gemini_image_describer/MainViewModel.kt
2019345230
package com.semuju.gemini_image_describer.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
gemini-image-describer/app/src/main/java/com/semuju/gemini_image_describer/ui/theme/Color.kt
4050747200
package com.semuju.gemini_image_describer.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun GeminiImageDescriberTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
gemini-image-describer/app/src/main/java/com/semuju/gemini_image_describer/ui/theme/Theme.kt
3010601374
package com.semuju.gemini_image_describer.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
gemini-image-describer/app/src/main/java/com/semuju/gemini_image_describer/ui/theme/Type.kt
334179962
package com.semuju.gemini_image_describer import android.graphics.Bitmap import android.os.Build import android.os.Bundle import android.provider.MediaStore import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.setContent import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.viewModels import androidx.annotation.RequiresApi import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.semuju.gemini_image_describer.ui.theme.GeminiImageDescriberTheme import dev.jeziellago.compose.markdowntext.MarkdownText class MainActivity : ComponentActivity() { @RequiresApi(Build.VERSION_CODES.P) @OptIn(ExperimentalMaterial3Api::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val vm by viewModels<MainViewModel>() setContent { GeminiImageDescriberTheme { Scaffold( topBar = { TopAppBar(title = { Text(text = "Gemini Image Describer") }) } ) { padding -> var bitmap by remember { mutableStateOf<Bitmap?>(null) } val context = LocalContext.current val uiState by vm.uiState.collectAsState() val photoPicker = rememberLauncherForActivityResult(ActivityResultContracts.PickMultipleVisualMedia()) { uris -> uris.forEach { uri -> bitmap = MediaStore.Images.Media.getBitmap( context.contentResolver, uri ) } } Column( modifier = Modifier .fillMaxSize() .padding(padding) .verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally ) { bitmap?.let { Image( bitmap = it.asImageBitmap(), contentDescription = null, modifier = Modifier .padding(16.dp) .clip(RoundedCornerShape(8.dp)) ) Button( onClick = { if (uiState.explanation.isEmpty()) vm.generateDescription(it) else { bitmap = null vm.clearExplanation() } }, modifier = Modifier .padding(horizontal = 16.dp) .fillMaxWidth() ) { if (uiState.isLoading) CircularProgressIndicator( color = MaterialTheme.colorScheme.onPrimary ) else if (uiState.explanation.isEmpty()) Text(text = "Explain Image") else { Text(text = "Clear Everything") } } } ?: run { IconButton( modifier = Modifier .width(300.dp) .height(150.dp), onClick = { photoPicker.launch( PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly) ) } ) { Icon( modifier = Modifier .width(300.dp) .height(150.dp), imageVector = Icons.Filled.Add, contentDescription = null ) } Text(text = "Pick an image", fontSize = 20.sp) } if (uiState.explanation.isNotEmpty()) { Spacer(modifier = Modifier.height(32.dp)) MarkdownText( markdown = uiState.explanation, modifier = Modifier .padding(16.dp) .border( 1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.3f), RoundedCornerShape(8.dp) ) .padding(16.dp) .fillMaxWidth() ) } } } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { GeminiImageDescriberTheme { Greeting("Android") } }
gemini-image-describer/app/src/main/java/com/semuju/gemini_image_describer/MainActivity.kt
1759265996
package dev.anirban.jetchart import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("dev.anirban.jetchart", appContext.packageName) } }
JetChart/app/src/androidTest/java/dev/anirban/jetchart/ExampleInstrumentedTest.kt
854222159
package dev.anirban.jetchart import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
JetChart/app/src/test/java/dev/anirban/jetchart/ExampleUnitTest.kt
1610323590
package dev.anirban.jetchart.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
JetChart/app/src/main/java/dev/anirban/jetchart/ui/theme/Color.kt
2402814916
package dev.anirban.jetchart.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun JetChartTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
JetChart/app/src/main/java/dev/anirban/jetchart/ui/theme/Theme.kt
1712648015
package dev.anirban.jetchart.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import dev.anirban.jetchart.R // Inter Font Family val InterFontFamily = FontFamily( Font(R.font.inter_regular, FontWeight.Normal), Font(R.font.inter_bold, FontWeight.Bold), Font(R.font.inter_semibold, FontWeight.SemiBold), Font(R.font.inter_medium, FontWeight.Medium) ) // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
JetChart/app/src/main/java/dev/anirban/jetchart/ui/theme/Type.kt
4112582173
package dev.anirban.jetchart import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import dev.anirban.jetchart.screens.LibraryUIExample import dev.anirban.jetchart.ui.theme.JetChartTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { JetChartTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { LibraryUIExample() } } } } }
JetChart/app/src/main/java/dev/anirban/jetchart/MainActivity.kt
1829959201
package dev.anirban.jetchart.screens import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.CardDefaults import androidx.compose.material3.ElevatedCard import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp /** * This function is the Card view Template used * * @param modifier To be passed by the Parent Class * @param title This is the title for the card * @param heightBetweenTitleAndBody This is the extra height between the body and the title * @param body The UI which will be drawn inside this card */ @Composable fun CustomCard( modifier: Modifier = Modifier, title: String? = null, heightBetweenTitleAndBody: Dp = 0.dp, body: @Composable () -> Unit ) { // This function draws an elevated Card View ElevatedCard( modifier = modifier .fillMaxWidth() .padding(top = 16.dp, start = 16.dp, end = 16.dp), shape = RoundedCornerShape(8.dp), elevation = CardDefaults.cardElevation(defaultElevation = 4.dp), colors = CardDefaults.elevatedCardColors( containerColor = Color.Transparent ) ) { Box( modifier = Modifier .background(MaterialTheme.colorScheme.surface) .fillMaxWidth() ) { Column( modifier = Modifier .padding(8.dp) ) { if (!title.isNullOrEmpty()) { Text( text = title, modifier = Modifier .fillMaxWidth() .padding(top = 16.dp, start = 16.dp, end = 16.dp), // Text Features textAlign = TextAlign.Start, fontSize = 16.sp, fontWeight = FontWeight.W600, color = MaterialTheme.colorScheme.onSurface, ) // Giving a space between the title and the body of the card Spacer(modifier = Modifier.height(heightBetweenTitleAndBody)) } // Graph Body Function body() } } } Spacer(modifier = Modifier.height(8.dp)) }
JetChart/app/src/main/java/dev/anirban/jetchart/screens/CustomCard.kt
1519913455
package dev.anirban.jetchart.screens import android.content.res.Configuration import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Check import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import dev.anirban.charts.circular.CircularChart import dev.anirban.charts.circular.center.CircularImageCenter import dev.anirban.charts.circular.center.CircularRingTextCenter import dev.anirban.charts.circular.center.CircularTargetTextCenter import dev.anirban.charts.circular.charts.CircularDonutChartColumn import dev.anirban.charts.circular.charts.CircularDonutChartRow import dev.anirban.charts.circular.charts.CircularRingChart import dev.anirban.charts.circular.data.CircularDonutListData import dev.anirban.charts.circular.data.CircularTargetDataBuilder import dev.anirban.charts.circular.foreground.CircularDonutForeground import dev.anirban.charts.circular.foreground.CircularDonutTargetForeground import dev.anirban.charts.linear.LinearChart import dev.anirban.charts.linear.data.LinearStringData import dev.anirban.charts.linear.plots.LinearGradientLinePlot import dev.anirban.charts.util.ChartPoint import dev.anirban.jetchart.ui.theme.JetChartTheme // Preview Composable Function @Preview( "Light", heightDp = 2000, showBackground = true ) @Preview( name = "Dark", heightDp = 2000, uiMode = Configuration.UI_MODE_NIGHT_YES, showBackground = true ) @Composable private fun DefaultPreview() { JetChartTheme { LibraryUIExample() } } @Composable fun LibraryUIExample() { // Example Data Sets val xReadingMarker by remember { mutableStateOf(ChartPoint.pointDataBuilder("A", "B", "C", "D", "E", "F", "G")) } var dataSet1 by remember { mutableStateOf(listOf(ChartPoint.pointDataBuilder(6f, 5f, 4f, 6f, 7.5f, 7f, 6f))) } var dataSet2 by remember { mutableStateOf( listOf( ChartPoint.pointDataBuilder(6f, 5f, 4f, 6f, 7.5f, 7f, 6f), ChartPoint.pointDataBuilder(3f, 6f, 8f, 2f, 3.5f, 3f, 4f) ) ) } var dataSet3 by remember { mutableStateOf( listOf( ChartPoint.pointDataBuilder(6f, 5f, 4f, 6f, 7.5f, 7f, 6f), ChartPoint.pointDataBuilder(3f, 6f, 8f, 2f, 3.5f, 3f, 4f), ChartPoint.pointDataBuilder(1f, 8f, 4f, 3f, 5.9f, 2.9f, 4.7f) ) ) } var dataSet4 by remember { mutableStateOf(listOf(ChartPoint.pointDataBuilder(4f, 0f, 1.7f, 1.9f, 2f, 4f))) } // This variable helps to change data Set when the button is clicked. var onButtonPress by remember { mutableStateOf(false) } // Changing the Data Set here. LaunchedEffect(onButtonPress) { val mutableList1: MutableList<Float> = mutableListOf() val mutableList2: MutableList<Float> = mutableListOf() val mutableList3: MutableList<Float> = mutableListOf() val mutableList4: MutableList<Float> = mutableListOf() for (i in 0..6) { mutableList1.add((1..10).random().toFloat()) mutableList2.add((1..10).random().toFloat()) mutableList3.add((1..10).random().toFloat()) mutableList4.add((0..4).random().toFloat()) } dataSet1 = listOf(ChartPoint.pointDataBuilder(mutableList1)) dataSet2 = listOf( ChartPoint.pointDataBuilder(mutableList1), ChartPoint.pointDataBuilder(mutableList2) ) dataSet3 = listOf( ChartPoint.pointDataBuilder(mutableList1), ChartPoint.pointDataBuilder(mutableList2), ChartPoint.pointDataBuilder(mutableList3) ) dataSet4 = listOf(ChartPoint.pointDataBuilder(mutableList4)) onButtonPress = false } // Main UI Column( modifier = Modifier .verticalScroll(rememberScrollState()) .fillMaxSize() .padding(vertical = 16.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Button( onClick = { onButtonPress = true } ) { Text(text = "Reload DataSet") } // Design Pattern Single Line Chart CustomCard(title = "Single Line Chart") { LinearChart.LineChart( linearData = LinearStringData( yAxisReadings = dataSet1, xAxisReadings = xReadingMarker ) ) } // Design Pattern Double Line Chart CustomCard(title = "Double Line Chart") { LinearChart.LineChart( linearData = LinearStringData( yAxisReadings = dataSet2, xAxisReadings = xReadingMarker ) ) } // Design Pattern Triple Line Chart CustomCard(title = "Multiple Line Chart") { LinearChart.LineChart( linearData = LinearStringData( yAxisReadings = dataSet3, xAxisReadings = xReadingMarker ) ) } // Design Pattern String Marker Line Chart CustomCard(title = "String Marker Chart") { LinearChart.LineChart( linearData = LinearStringData( yAxisReadings = dataSet4, xAxisReadings = xReadingMarker, yMarkerList = ChartPoint.pointDataBuilder( "Very High", "High", "Moderate", "Average", "Bad" ).toMutableList() ) ) } // Design Pattern String Marker Line Chart // CustomCard( // title = "Emoji Marker Chart" // ) { // LinearChart.EmojiLineChart( // linearData = LinearEmojiData( // yAxisReadings = dataSet, // xAxisReadings = xReadingMarker, // yMarkerList = ChartPoint.pointDataBuilder( // getDrawable( // LocalContext.current, // R.drawable.emoji_furious // ) as BitmapDrawable, // getDrawable(LocalContext.current, R.drawable.emoji_angry) as BitmapDrawable, // getDrawable(LocalContext.current, R.drawable.emoji_sad) as BitmapDrawable, // getDrawable( // LocalContext.current, // R.drawable.emoji_depressed // ) as BitmapDrawable, // getDrawable( // LocalContext.current, // R.drawable.emoji_confused // ) as BitmapDrawable, // getDrawable(LocalContext.current, R.drawable.emoji_calm) as BitmapDrawable, // getDrawable(LocalContext.current, R.drawable.emoji_happy) as BitmapDrawable // ).toMutableList() // ) // ) // } // Design Pattern String Marker Gradient Line Chart using plot object CustomCard(title = "Gradient List using Plot Object") { LinearChart.GradientChart( linearData = LinearStringData( yAxisReadings = dataSet4, xAxisReadings = xReadingMarker, yMarkerList = ChartPoint.pointDataBuilder( "Very High", "High", "Moderate", "Average", "Bad" ).toMutableList() ), plot = LinearGradientLinePlot( colorList = listOf( Color(0xFF4999DF).copy(alpha = .5f), Color(0xFF4999DF).copy(alpha = .1f), ) ) ) } // Design Pattern Custom Chart // CustomCard( // title = "Custom Chart" // ) { // // LinearChart.CustomLinearChart( // linearData = LinearEmojiData( // yAxisReadings = listOf( // ChartPoint.pointDataBuilder( // 6f, 4f, 2f, 0f, 3f, 5f, 6f // ) // ), // xAxisReadings = ChartPoint.pointDataBuilder( // "Jan", "Mar", "May", "Jul", "Sep", "Nov", "Dec" // ), // yMarkerList = ChartPoint.pointDataBuilder( // getDrawable( // LocalContext.current, // R.drawable.emoji_furious // ) as BitmapDrawable, // getDrawable(LocalContext.current, R.drawable.emoji_angry) as BitmapDrawable, // getDrawable(LocalContext.current, R.drawable.emoji_sad) as BitmapDrawable, // getDrawable( // LocalContext.current, // R.drawable.emoji_depressed // ) as BitmapDrawable, // getDrawable( // LocalContext.current, // R.drawable.emoji_confused // ) as BitmapDrawable, // getDrawable(LocalContext.current, R.drawable.emoji_calm) as BitmapDrawable, // getDrawable(LocalContext.current, R.drawable.emoji_happy) as BitmapDrawable // ).toMutableList() // ), // plot = LinearGradientLinePlot( // colorList = listOf( // Color(0xFFE5E787).copy(alpha = .6f), // Color(0xFF85DE50).copy(alpha = .6f), // Color(0xFF57D6BF).copy(alpha = .6f), // Color(0xFF43B4E4).copy(alpha = .6f), // Color(0xFF3A60E6).copy(alpha = .6f), // Color(0xFF57D6BF).copy(alpha = .6f), // Color(0xFFD02596).copy(alpha = .6f) // ) // ) // ) // } // Design Pattern Bar Chart CustomCard(title = "Bar Chart") { LinearChart.BarChart( linearData = LinearStringData( yAxisReadings = dataSet1, xAxisReadings = xReadingMarker ) ) } // Design Pattern Emoji Bar Chart // CustomCard( // title = "Emoji Bar Chart" // ) { // // LinearChart.EmojiBarChart( // linearData = LinearEmojiData( // yAxisReadings = dataSet1, // xAxisReadings = xReadingMarker, // yMarkerList = ChartPoint.pointDataBuilder( // getDrawable( // LocalContext.current, // R.drawable.emoji_furious // ) as BitmapDrawable, // getDrawable(LocalContext.current, R.drawable.emoji_angry) as BitmapDrawable, // getDrawable(LocalContext.current, R.drawable.emoji_sad) as BitmapDrawable, // getDrawable( // LocalContext.current, // R.drawable.emoji_depressed // ) as BitmapDrawable, // getDrawable( // LocalContext.current, // R.drawable.emoji_confused // ) as BitmapDrawable, // getDrawable(LocalContext.current, R.drawable.emoji_calm) as BitmapDrawable, // getDrawable(LocalContext.current, R.drawable.emoji_happy) as BitmapDrawable // ).toMutableList() // ) // ) // } // Design Pattern Same row Donut Chart CustomCard(title = " Row Donut Chart") { CircularDonutChartRow.DonutChartRow( circularData = CircularDonutListData( itemsList = listOf( Pair("Fruit", 1500.0f), Pair("Junk Food", 300.0f), Pair("Protein", 500.0f) ), siUnit = "Kcal", cgsUnit = "cal", conversionRate = { it / 1000f } ), circularForeground = CircularDonutForeground( radiusMultiplier = 1.7f, strokeWidth = 15f, startAngle = 30f ) ) } // Design Pattern Different row Donut Chart CustomCard(title = "Column Donut Chart") { CircularDonutChartColumn.DonutChartColumn( circularData = CircularDonutListData( itemsList = listOf( Pair("Study", 450f), Pair("Sport", 180f), Pair("Social", 30f), Pair("Others", 60f) ), siUnit = "Hrs", cgsUnit = "Min", conversionRate = { it / 60f } ) ) } // Design Pattern Target Achieved Donut Chart CustomCard(title = "Target Donut Chart") { CircularDonutChartRow.TargetDonutChart( circularData = CircularTargetDataBuilder( target = 4340f, achieved = 2823f, siUnit = "Km", cgsUnit = "m", conversionRate = { it / 1000f } ), circularCenter = CircularTargetTextCenter( fontSize = 16.sp, fontWeight = FontWeight.W700 ) ) } // Design Pattern Single Ring Chart CustomCard(title = "Single Ring Chart") { CircularRingChart.SingleRingChart( circularData = CircularTargetDataBuilder( target = 500f, achieved = 489f, siUnit = "", cgsUnit = "", conversionRate = { it } ), circularCenter = CircularRingTextCenter( title = "Title 1", centerValue = "value", status = "status Value" ) ) } // Design Pattern Double Ring Chart CustomCard(title = "Double Ring Chart") { CircularRingChart.MultipleRingChart( circularData = listOf( CircularTargetDataBuilder( target = 100f, achieved = 81f, siUnit = "bpm", cgsUnit = "bpm", conversionRate = { it } ), CircularTargetDataBuilder( target = 160f, achieved = 112f, siUnit = "mm", cgsUnit = "mm", conversionRate = { it } ) ), circularCenter = listOf( CircularRingTextCenter( title = "Title 1", centerValue = "center value", status = "Not Good" ), CircularRingTextCenter( title = "Title 2", centerValue = "center value", status = "Great" ) ) ) } CustomCard(title = "Weekly Progress") { Row { listOf("M", "T", "W", "T", "F", "S", "S").forEach { Column( modifier = Modifier .weight(1f), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { CircularChart.DonutChartImage( modifier = Modifier .size(55.dp), circularData = CircularTargetDataBuilder( target = 100f, achieved = 81f, siUnit = "", cgsUnit = "", conversionRate = { it } ), circularCenter = CircularImageCenter( image = Icons.Default.Check, contentDescription = "Achieved" ), circularForeground = CircularDonutTargetForeground(strokeWidth = 10f) ) Text( text = it, // Text Features textAlign = TextAlign.Start, fontSize = 14.sp, fontWeight = FontWeight.W700, color = MaterialTheme.colorScheme.onSurface, ) Spacer(modifier = Modifier.height(8.dp)) } } } } } }
JetChart/app/src/main/java/dev/anirban/jetchart/screens/LibraryUIExamples.kt
2175103987
package dev.anirban.charts.util import androidx.compose.ui.geometry.Offset /** * This class is made to indicate each and every point in the graph along with their coordinates for * placement */ class ChartPoint<T>( val value: T ) { /** * X and Y Coordinate of the points where the value needs to be drawn of plotted */ var xCoordinate: Float = 0f private set var yCoordinate: Float = 0f private set /** * This function is used to set the X - Coordinate of the object */ fun setXCoordinate(xCoordinate: Float) { this.xCoordinate = xCoordinate } /** * This function is used to set the Y - Coordinate of the object */ fun setYCoordinate(yCoordinate: Float) { this.yCoordinate = yCoordinate } /** * This function is used to get the Offset of the object */ fun getOffset(): Offset = Offset(xCoordinate, yCoordinate) companion object { /** * This function makes a List of Points Objects * * This is made to make the creation of Points List easy and less boilerplate code would be * written */ fun <T> pointDataBuilder(vararg points: T): List<ChartPoint<T>> { return points.map { ChartPoint(it) } } /** * This function makes a List of Points Objects * * This is made to make the creation of Points List easy and less boilerplate code would be * written */ fun <T> pointDataBuilder(points: List<T>): List<ChartPoint<T>> { return points.map { ChartPoint(it) } } } }
JetChart/charts/src/main/java/dev/anirban/charts/util/ChartPoint.kt
4185247652
package dev.anirban.charts.linear.decoration import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color /** * This is one of the implementations of the [LinearDecoration] which mostly contains the * decorations stuff like colors and all * * @param textColor this is the text color for all the margins and other things * @param plotPrimaryColor THis is the plot color for all the plotted Lines in the graph * @param plotSecondaryColor These are color for all the circle points in the graph */ class LinearDecoration( val textColor: Color, val plotPrimaryColor: List<Color>, val plotSecondaryColor: List<Color> ) { /** * These function are used to make an object of [LinearDecoration] */ companion object { private val colorYellow = Color(0xFFE2B93B) private val colorBlue = Color(0xFF0088FF) private val colorRed = Color(0xFFEC407A) private val colorGreen = Color(0xFF2AD200) private val colorCyan = Color(0xFF00BCD4) /** * Provides [LinearDecoration] Object for the Line Charts * * Needs a Composable function to get the color from the material Theme since its * a composable function */ @Composable fun lineDecorationColors( textColor: Color = MaterialTheme.colorScheme.onSurface, plotPrimaryColor: List<Color> = listOf(colorBlue, colorGreen, Color.Yellow), plotSecondaryColor: List<Color> = listOf(colorYellow, colorRed, Color.Red) ) = LinearDecoration( textColor = textColor, plotPrimaryColor = plotPrimaryColor, plotSecondaryColor = plotSecondaryColor ) /** * Provides Decoration Object for Bar Charts * * Needs a Composable function to get the color from the material Theme since its * a composable function */ @Composable fun barDecorationColors( textColor: Color = MaterialTheme.colorScheme.onSurface, plotPrimaryColor: List<Color> = listOf(colorBlue, colorCyan), plotSecondaryColor: List<Color> = emptyList() ) = LinearDecoration( textColor = textColor, plotPrimaryColor = plotPrimaryColor, plotSecondaryColor = plotSecondaryColor ) } }
JetChart/charts/src/main/java/dev/anirban/charts/linear/decoration/LinearDecoration.kt
2674905697
package dev.anirban.charts.linear import android.graphics.drawable.BitmapDrawable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.unit.dp import dev.anirban.charts.linear.exceptions.LinearChartTypeMismatch import dev.anirban.charts.linear.exceptions.LinearColorConventionMismatch import dev.anirban.charts.linear.exceptions.LinearDataMismatch import dev.anirban.charts.linear.exceptions.LinearDecorationMismatch import dev.anirban.charts.linear.interfaces.LinearChartExceptionHandler import dev.anirban.charts.linear.interfaces.LinearChartInterface import dev.anirban.charts.linear.interfaces.LinearColorConventionInterface import dev.anirban.charts.linear.interfaces.LinearDataInterface import dev.anirban.charts.linear.interfaces.LinearMarginInterface import dev.anirban.charts.linear.interfaces.LinearPlotInterface import dev.anirban.charts.linear.colorconvention.LinearDefaultColorConvention import dev.anirban.charts.linear.data.LinearEmojiData import dev.anirban.charts.linear.data.LinearStringData import dev.anirban.charts.linear.decoration.LinearDecoration import dev.anirban.charts.linear.margins.LinearEmojiMargin import dev.anirban.charts.linear.margins.LinearStringMargin import dev.anirban.charts.linear.plots.LinearBarPlot import dev.anirban.charts.linear.plots.LinearGradientLinePlot import dev.anirban.charts.linear.plots.LinearLinePlot /** * This is the base class which directly implements the [LinearDataInterface] interfaces. * * @param margin This is the implementation for drawing the Margins * @param decoration This is the implementation for drawing the Decorations * @param linearData This is the implementation for keeping the Linear Chart data and calculations * @param plot This is the implementation for how shall the plotting be drawn on the graph * @param colorConvention This is the implementation for how we are going to draw all the color * conventions in the graph */ open class LinearChart( override val margin: LinearMarginInterface, override val decoration: LinearDecoration, override val linearData: LinearDataInterface, override val plot: LinearPlotInterface, override val colorConvention: LinearColorConventionInterface ) : LinearChartInterface, LinearChartExceptionHandler { /** * This functions validates the [LinearDataInterface] is implemented properly and all the * data is given properly over there */ override fun validateDataInput() { var maxSize = -1 // calculating the number of max Y - Axis Readings in a particular Coordinate set linearData.yAxisReadings.forEach { if (it.size > maxSize) maxSize = it.size } // Comparing the num of max Y - Axis Readings to X - Axis Readings/Markers if (linearData.xAxisReadings.size < maxSize) throw LinearDataMismatch("X - Axis Markers Size is less than Number of Y - Axis Reading") } /** * This function validates the [LinearDecoration] is implemented properly and all the data * needed for the Linear Decoration are provided properly */ override fun validateDecorationInput() { // checking if we have enough Primary Color for the plots if (decoration.plotPrimaryColor.size < linearData.yAxisReadings.size) { if (plot is LinearBarPlot && decoration.plotPrimaryColor.isEmpty()) throw Exception( "plotPrimaryColor for the decoration have 0 Colors whereas at least " + "one color needs to be provided" ) else throw LinearDecorationMismatch( "Need to provide ${linearData.yAxisReadings.size} number of colors for the " + "plotPrimaryColor" ) } // checking if we have enough Secondary Color for the plots if (decoration.plotSecondaryColor.size < linearData.yAxisReadings.size && plot !is LinearBarPlot) throw LinearDecorationMismatch( "Secondary Color of Decoration Class needs " + "${linearData.yAxisReadings.size} colors but it has " + "${decoration.plotSecondaryColor.size} colors" ) } /** * This function validates the [LinearColorConventionInterface] is implemented properly */ override fun validateColorConventionInput() { //Checking if the given textList has more texts than the given yAxisReadings size if (colorConvention.textList.size > linearData.yAxisReadings.size) throw LinearColorConventionMismatch("Texts for Color Lists are More than provided yAxis Coordinate Sets") } /** * This function validates if the margin and the data passed are supported or not so it can give * a meaningful result to the developer */ override fun validateTypeMismatch() { if (linearData is LinearEmojiData && margin !is LinearEmojiMargin) throw LinearChartTypeMismatch( "Need to pass a Margin of Type LinearEmojiMargin for a " + "data of type LinearEmojiData" ) if (margin is LinearEmojiMargin && linearData !is LinearEmojiData) throw LinearChartTypeMismatch( "Need to pass a Data of Type LinearEmojiData for a " + "margin of type LinearEmojiMargin" ) } /** * This function draws the margins according to the margin implementation passed to it */ override fun DrawScope.drawMargin() { margin.apply { drawMargin( linearData = linearData, decoration = decoration ) } } /** * This function draws the plotting of the chart */ override fun DrawScope.plotChart() { plot.apply { plotChart( linearData = linearData, decoration = decoration ) } } /** * This function draws the Color Conventions of the Chart */ @Composable override fun DrawColorConvention() { colorConvention.DrawColorConventions( decoration = decoration ) } /** * This is the Build Function which starts composing the Charts and composes the Charts * * @param modifier This is for default modifications to be passed from the parent Class */ @Composable override fun Build(modifier: Modifier) { // Validating all the Data if there is any exceptions validateDataInput() validateDecorationInput() validateColorConventionInput() Column( modifier = Modifier .fillMaxWidth() .padding(top = 24.dp, start = 24.dp, bottom = 18.dp, end = 24.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Box( modifier = modifier .fillMaxWidth() .height(140.dp) .drawBehind { // Calling all the necessary functions linearData.apply { doCalculations(size = size) } drawMargin() plotChart() } ) // Checking if the implementation is the default one if (colorConvention !is LinearDefaultColorConvention) { Spacer(modifier = Modifier.height(16.dp)) // Draws the color conventions for the chart DrawColorConvention() } } } /** * Builder Composable Functions which makes the objects of [LinearChart] and these are * actually called by the users to make charts */ companion object { /** * This function creates an object of the LinearChart which draws a basic Line chart * It can draw Single Line Charts as well as multiple Line Charts with String Markers * * @param modifier This is to be passed from the Parent Class for the modifications * @param margin This is the implementation for drawing the Margins * @param decoration This is the implementation for drawing the Decorations * @param linearData This is the implementation for keeping the Linear Chart data and calculations * @param plot This is the implementation for how shall the plotting be drawn on the graph * @param colorConvention This is the implementation for how we are going to draw all the * color conventions in the graph */ @Composable fun LineChart( modifier: Modifier = Modifier, margin: LinearStringMargin = LinearStringMargin(), decoration: LinearDecoration = LinearDecoration.lineDecorationColors(), linearData: LinearStringData, plot: LinearLinePlot = LinearLinePlot(), colorConvention: LinearColorConventionInterface = LinearDefaultColorConvention() ) = LinearChart( margin = margin, decoration = decoration, linearData = linearData, plot = plot, colorConvention = colorConvention ).Build(modifier = modifier) /** * This function creates an object of the LinearChart which draws a basic Line chart * It can draw Single Line Charts as well as multiple Line Charts with Drawable Markers or * Emoji Markers but drawables should be converted into [BitmapDrawable] first for this to * work * * Note :- * 1. ContextCompat.getDrawable( * LocalContext.current, * R.drawable.emoji_furious * ) as BitmapDrawable * It is the code to convert a drawable into a Bitmap Drawable * * @param modifier This is to be passed from the Parent Class for the modifications * @param margin This is the implementation for drawing the Margins * @param decoration This is the implementation for drawing the Decorations * @param linearData This is the implementation for keeping the Linear Chart data and calculations * @param plot This is the implementation for how shall the plotting be drawn on the graph * @param colorConvention This is the implementation for how we are going to draw all * the color conventions in the graph */ @Composable fun EmojiLineChart( modifier: Modifier = Modifier, margin: LinearEmojiMargin = LinearEmojiMargin(), decoration: LinearDecoration = LinearDecoration.lineDecorationColors(), linearData: LinearEmojiData, plot: LinearLinePlot = LinearLinePlot(), colorConvention: LinearColorConventionInterface = LinearDefaultColorConvention() ) = LinearChart( margin = margin, decoration = decoration, linearData = linearData, plot = plot, colorConvention = colorConvention ).Build(modifier = modifier) /** * This function creates an object of the LinearChart which draws a basic Line chart * It can draw Single Line Charts as well as multiple Line Charts with String Markers and * a gradient Plotting * * @param modifier This is to be passed from the Parent Class for the modifications * @param margin This is the implementation for drawing the Margins * @param decoration This is the implementation for drawing the Decorations * @param linearData This is the implementation for keeping the Linear Chart data and calculations * @param plot This is the implementation for how shall the plotting be drawn on the graph * @param colorConvention This is the implementation for how we are going to draw all * the color conventions in the graph */ @Composable fun GradientChart( modifier: Modifier = Modifier, margin: LinearStringMargin = LinearStringMargin(), decoration: LinearDecoration = LinearDecoration.lineDecorationColors(), linearData: LinearStringData, plot: LinearGradientLinePlot, colorConvention: LinearColorConventionInterface = LinearDefaultColorConvention() ) = LinearChart( margin = margin, decoration = decoration, linearData = linearData, plot = plot, colorConvention = colorConvention ).Build(modifier = modifier) /** * This function creates an object of the LinearChart which draws a basic Bar chart * * @param modifier This is to be passed from the Parent Class for the modifications * @param margin This is the implementation for drawing the Margins * @param decoration This is the implementation for drawing the Decorations * @param linearData This is the implementation for keeping the Linear Chart data and calculations * @param plot This is the implementation for how shall the plotting be drawn on the graph * @param colorConvention This is the implementation for how we are going to draw all * the color conventions in the graph */ @Composable fun BarChart( modifier: Modifier = Modifier, margin: LinearStringMargin = LinearStringMargin(), decoration: LinearDecoration = LinearDecoration.barDecorationColors(), linearData: LinearStringData, plot: LinearBarPlot = LinearBarPlot(), colorConvention: LinearColorConventionInterface = LinearDefaultColorConvention() ) = LinearChart( margin = margin, decoration = decoration, linearData = linearData, plot = plot, colorConvention = colorConvention ).Build(modifier = modifier) /** * This function creates an object of the LinearChart which draws a basic Bar chart * * @param modifier This is to be passed from the Parent Class for the modifications * @param margin This is the implementation for drawing the Margins * @param decoration This is the implementation for drawing the Decorations * @param linearData This is the implementation for keeping the Linear Chart data and calculations * @param plot This is the implementation for how shall the plotting be drawn on the graph * @param colorConvention This is the implementation for how we are going to draw all * the color conventions in the graph */ @Composable fun EmojiBarChart( modifier: Modifier = Modifier, margin: LinearEmojiMargin = LinearEmojiMargin(), decoration: LinearDecoration = LinearDecoration.barDecorationColors(), linearData: LinearEmojiData, plot: LinearBarPlot = LinearBarPlot(), colorConvention: LinearColorConventionInterface = LinearDefaultColorConvention() ) = LinearChart( margin = margin, decoration = decoration, linearData = linearData, plot = plot, colorConvention = colorConvention ).Build(modifier = modifier) /** * This function creates an object of the LinearChart which draws a basic Line chart * It can draw Single Line Charts as well as multiple Line Charts with custom objects passed * by the developer * * @param modifier This is to be passed from the Parent Class for the modifications * @param margin This is the implementation for drawing the Margins * @param decoration This is the implementation for drawing the Decorations * @param linearData This is the implementation for keeping the Linear Chart data and calculations * @param plot This is the implementation for how shall the plotting be drawn on the graph * @param colorConvention This is the implementation for how we are going to draw all * the color conventions in the graph */ @Composable fun CustomLinearChart( modifier: Modifier = Modifier, margin: LinearMarginInterface = LinearEmojiMargin(), decoration: LinearDecoration = LinearDecoration.lineDecorationColors(), linearData: LinearDataInterface, plot: LinearPlotInterface = LinearLinePlot(), colorConvention: LinearColorConventionInterface = LinearDefaultColorConvention() ) = LinearChart( margin = margin, decoration = decoration, linearData = linearData, plot = plot, colorConvention = colorConvention ).Build(modifier = modifier) } }
JetChart/charts/src/main/java/dev/anirban/charts/linear/LinearChart.kt
3326934312
package dev.anirban.charts.linear.margins import android.graphics.Paint import android.graphics.Rect import android.graphics.Typeface import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.nativeCanvas import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.unit.sp import dev.anirban.charts.linear.decoration.LinearDecoration import dev.anirban.charts.linear.interfaces.LinearDataInterface import dev.anirban.charts.linear.interfaces.LinearMarginInterface /** * This is one of the implementations of the [LinearMarginInterface] and it provides with a implementation * of how we should draw the Margin */ class LinearStringMargin : LinearMarginInterface { /** * This is the function which contains the actual margin implementation * * @param linearData This is the data of the Line Chart * @param decoration THis is the decoration of the function */ override fun DrawScope.drawMargin( linearData: LinearDataInterface, decoration: LinearDecoration ) { linearData.yMarkerList.forEach { point -> val bounds = Rect() val paint = Paint() paint.color = decoration.textColor.toArgb() paint.textSize = 12.sp.toPx() paint.textAlign = Paint.Align.LEFT paint.typeface = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL) paint.getTextBounds(point.value.toString(), 0, point.value.toString().length, bounds) val width = bounds.width() // This draws the String Marker drawContext.canvas.nativeCanvas.drawText( point.value.toString(), point.xCoordinate, point.yCoordinate, paint ) // This draws the Lines for the readings parallel to X Axis drawLine( start = Offset( x = width.toFloat(), y = point.yCoordinate - 12f ), color = decoration.textColor.copy(alpha = 0.8f), end = Offset( x = size.width, y = point.yCoordinate - 12f ), strokeWidth = 1f ) } // This Draws the Y Markers below the Graph linearData.xAxisReadings.forEach { currentMarker -> // This draws the String Marker drawContext.canvas.nativeCanvas.drawText( currentMarker.value.toString(), currentMarker.xCoordinate, currentMarker.yCoordinate, Paint().apply { color = decoration.textColor.toArgb() textSize = 12.sp.toPx() textAlign = Paint.Align.CENTER typeface = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL) } ) } } }
JetChart/charts/src/main/java/dev/anirban/charts/linear/margins/LinearStringMargin.kt
925137620
package dev.anirban.charts.linear.margins import android.graphics.Bitmap import android.graphics.Paint import android.graphics.Typeface import android.graphics.drawable.BitmapDrawable import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.translate import androidx.compose.ui.graphics.nativeCanvas import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.unit.sp import dev.anirban.charts.linear.decoration.LinearDecoration import dev.anirban.charts.linear.interfaces.LinearDataInterface import dev.anirban.charts.linear.interfaces.LinearMarginInterface import dev.anirban.charts.linear.data.LinearEmojiData /** * This is one of the implementations of the [LinearMarginInterface] and it provides with a implementation * of how we should draw the Margin */ class LinearEmojiMargin : LinearMarginInterface { /** * This is the function which contains the actual margin implementation * * @param linearData This is the data of the Line Chart * @param decoration THis is the decoration of the function */ override fun DrawScope.drawMargin( linearData: LinearDataInterface, decoration: LinearDecoration ) { val dimension = (linearData as LinearEmojiData).dimension linearData.yMarkerList.forEach { point -> point.value as BitmapDrawable val resizedBitmap = Bitmap.createScaledBitmap(point.value.bitmap, dimension, dimension, true) val width = resizedBitmap.width translate(point.xCoordinate, point.yCoordinate) { drawImage(image = resizedBitmap.asImageBitmap()) } // This draws the Lines for the readings parallel to X Axis drawLine( start = Offset( x = width.toFloat(), y = point.yCoordinate + (dimension.toFloat() / 2f) ), color = decoration.textColor.copy(alpha = 0.8f), end = Offset( x = size.width, y = point.yCoordinate + (dimension.toFloat() / 2f) ), strokeWidth = 1f ) } // This Draws the Y Markers below the Graph linearData.xAxisReadings.forEach { currentMarker -> // This draws the String Marker drawContext.canvas.nativeCanvas.drawText( currentMarker.value, currentMarker.xCoordinate, currentMarker.yCoordinate, Paint().apply { color = decoration.textColor.toArgb() textSize = 12.sp.toPx() textAlign = Paint.Align.CENTER typeface = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL) } ) } } }
JetChart/charts/src/main/java/dev/anirban/charts/linear/margins/LinearEmojiMargin.kt
619378315
package dev.anirban.charts.linear.exceptions import dev.anirban.charts.linear.interfaces.LinearDataInterface /** * This exception is thrown when the X - Axis Readings array [LinearDataInterface.xAxisReadings] * contains less text than the list of Y - Axis Readings [LinearDataInterface.yAxisReadings] */ class LinearDataMismatch(message: String?) : Exception(message)
JetChart/charts/src/main/java/dev/anirban/charts/linear/exceptions/LinearDataMismatch.kt
1837974592
package dev.anirban.charts.linear.exceptions import dev.anirban.charts.linear.decoration.LinearDecoration import dev.anirban.charts.linear.interfaces.LinearDataInterface /** * This exception is thrown when the color array [LinearDecoration.plotPrimaryColor] and * [LinearDecoration.plotSecondaryColor] contains less color than the list of Y - Axis Readings at * data class [LinearDataInterface.yAxisReadings] */ class LinearDecorationMismatch(message: String?) : Exception(message)
JetChart/charts/src/main/java/dev/anirban/charts/linear/exceptions/LinearDecorationMismatch.kt
368924210
package dev.anirban.charts.linear.exceptions import dev.anirban.charts.linear.decoration.LinearDecoration import dev.anirban.charts.linear.interfaces.LinearColorConventionInterface /** * This exception is thrown when the Text List array [LinearColorConventionInterface.textList] * contains more text than the list of primary color at decoration class * [LinearDecoration.plotPrimaryColor] */ class LinearColorConventionMismatch(message: String?) : Exception(message)
JetChart/charts/src/main/java/dev/anirban/charts/linear/exceptions/LinearColorConventionMismatch.kt
1091189150
package dev.anirban.charts.linear.exceptions /** * This exception will be thrown when there will be a type mismatch between the data class object and * the margin class object which is not supported */ class LinearChartTypeMismatch(message: String?) : Exception(message)
JetChart/charts/src/main/java/dev/anirban/charts/linear/exceptions/LinearChartTypeMismatch.kt
83292362
package dev.anirban.charts.linear.data import android.graphics.Paint import android.graphics.Rect import android.graphics.Typeface import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.unit.sp import dev.anirban.charts.linear.interfaces.LinearDataInterface import dev.anirban.charts.util.ChartPoint /** * This is one of the implementation for storing and calculating the data in the chart. It * Implements the [LinearDataInterface] Interface * * @param xAxisReadings These are the readings of the X - Axis * @param yAxisReadings These are the readings of the Y - Axis * @param yMarkerList This is the list of marker which are present in the Y - Axis * @param numOfYMarkers These are teh num of markers in Y-axis * * @param numOfYMarkers This Is useless when a yMarkerList is passed to the Class constructor */ class LinearStringData( override val yAxisReadings: List<List<ChartPoint<Float>>>, override val xAxisReadings: List<ChartPoint<String>>, override var yMarkerList: MutableList<ChartPoint<*>> = mutableListOf(), override var numOfYMarkers: Int = 5 ) : LinearDataInterface { /** * These are the num of markers in X-Axis */ override val numOfXMarkers: Int = xAxisReadings.size /** * Upper Y - Axis Reading or the Maximum Reading of the Graph */ private var yUpperReading: Int = Int.MIN_VALUE /** * Lower Y - Axis Reading or the Maximum Reading of the Graph */ private var yLowerReading: Int = Int.MAX_VALUE /** * It is the difference of the Upper and Lower Markers divided by the Markers count */ private var yDividend: Int init { // Checking if the markers are provided or we need to calculate if (yMarkerList.isNotEmpty()) { numOfYMarkers = yMarkerList.size // Storing the upper Bound and Lower bound of Y Markers yUpperReading = yMarkerList.size - 1 yLowerReading = 0 // Difference between each Y Markers yDividend = 1 } else { // Maximum and minimum value provided is calculated val yMax = yAxisReadings.maxOf { it.maxOf { point -> point.value } } val yMin = yAxisReadings.minOf { it.minOf { point -> point.value } } // Storing the upper Bound and Lower bound of Y Markers yUpperReading = if (yMax % (numOfYMarkers - 1) != 0.0f) yMax.toInt() + ((numOfYMarkers - 1) - (yMax.toInt() % (numOfYMarkers - 1))) else yMax.toInt() yLowerReading = if (yMin.toInt() % (numOfYMarkers - 1) == 0) { yMin.toInt() - (numOfYMarkers - 1) } else { yMin.toInt() - (yMin.toInt() % (numOfYMarkers - 1)) } // Difference between each Y Markers yDividend = (yUpperReading - yLowerReading) / (numOfYMarkers - 1) // Calculating the points for Y - Axis markers for (index in 0 until numOfYMarkers) { // This is the value of the current Y Axis Marker val currentYMarker = yUpperReading - (index) * yDividend yMarkerList.add(index, ChartPoint(currentYMarker)) } } } /** * This is the function which is responsible for the calculations of all the graph related stuff * * @param size This is the size of the whole canvas which also haves the componentSize in it */ override fun DrawScope.doCalculations(size: Size) { // Scale of Y - Axis of the Graph val yScale = size.height / numOfYMarkers // maximum Width of the Y - Markers val yMarkerMaxWidth = calculateYMarkersCoordinates(yScale = yScale) // X - Axis Scale val xScale = (size.width - yMarkerMaxWidth) / numOfXMarkers // This function calculates the Coordinates for the Readings calculateReadingsCoordinates( xScale = xScale, yScale = yScale, yMarkerMaxWidth = yMarkerMaxWidth ) // This function calculates the Coordinates for the X - Markers calculateXMarkersCoordinates( size = size, xScale = xScale, yMarkerMaxWidth = yMarkerMaxWidth ) } /** * This function calculates the Y - Axis Markers Coordinates * * @param yScale This is the scale for the Y - Axis */ private fun DrawScope.calculateYMarkersCoordinates(yScale: Float): Int { var yMarkerMaxWidth = 0 // Calculating all the chart Y - Axis markers in the chart along with their coordinates yMarkerList.forEachIndexed { index, point -> val bounds = Rect() val paint = Paint() paint.textSize = 12.sp.toPx() paint.textAlign = Paint.Align.LEFT paint.typeface = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL) paint.getTextBounds(point.value.toString(), 0, point.value.toString().length, bounds) // Current Y Coordinate for the point val currentYCoordinate = (yScale * index) + 12f // Setting the calculated graph coordinates to the object point.setXCoordinate(-24f) point.setYCoordinate(currentYCoordinate) val width = bounds.width() yMarkerMaxWidth = if (yMarkerMaxWidth < width) width else yMarkerMaxWidth } return yMarkerMaxWidth } /** * This function calculates the Coordinates for the Readings * * @param xScale This is the scale for the X - Axis * @param yScale This is the scale for the Y - Axis * @param yMarkerMaxWidth This is the maximum width of the Y - Markers */ private fun calculateReadingsCoordinates(xScale: Float, yScale: Float, yMarkerMaxWidth: Int) { // Taking all the points given and calculating where they will stay in the graph yAxisReadings.forEach { pointSet -> pointSet.forEachIndexed { index, point -> val currentYCoordinate = (yUpperReading - point.value) * yScale / yDividend val currentXCoordinate = 48f + (index * xScale) + yMarkerMaxWidth // Setting the calculated graph coordinates to the object point.setXCoordinate(currentXCoordinate) point.setYCoordinate(currentYCoordinate) } } } /** * This Function calculates the coordinates for the X Markers * * @param size This is the size of the canvas * @param xScale This is the scale for the X - Axis * @param yMarkerMaxWidth This is the maximum width of the Y - Markers */ private fun calculateXMarkersCoordinates(size: Size, xScale: Float, yMarkerMaxWidth: Int) { // Calculating all the chart X - Axis markers coordinates xAxisReadings.forEachIndexed { index, currentMarker -> val xCoordinate = (xScale * index) + 48f + yMarkerMaxWidth val yCoordinate = size.height // Setting the calculated graph coordinates to the object currentMarker.setXCoordinate(xCoordinate) currentMarker.setYCoordinate(yCoordinate) } } }
JetChart/charts/src/main/java/dev/anirban/charts/linear/data/LinearStringData.kt
2102730992
package dev.anirban.charts.linear.data import android.graphics.Bitmap import android.graphics.drawable.BitmapDrawable import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.drawscope.DrawScope import dev.anirban.charts.linear.interfaces.LinearDataInterface import dev.anirban.charts.util.ChartPoint /** * This is one of the implementation for storing and calculating the data in the chart. It * Implements the [LinearDataInterface] Interface * * @param xAxisReadings These are the readings of the X - Axis * @param yAxisReadings These are the readings of the Y - Axis * @param yMarkerList This is the list of marker which are present in the Y - Axis */ class LinearEmojiData( override val yAxisReadings: List<List<ChartPoint<Float>>>, override val xAxisReadings: List<ChartPoint<String>>, override var yMarkerList: MutableList<ChartPoint<*>> = mutableListOf(), val dimension: Int = 50 ) : LinearDataInterface { /** * These are the num of markers in X-Axis */ override val numOfXMarkers: Int = xAxisReadings.size override var numOfYMarkers: Int = yMarkerList.size /** * Upper Y - Axis Reading or the Maximum Reading of the Graph */ private var yUpperReading: Int = Int.MIN_VALUE /** * Lower Y - Axis Reading or the Maximum Reading of the Graph */ private var yLowerReading: Int = Int.MAX_VALUE /** * It is the difference of the Upper and Lower Markers divided by the Markers count */ private var yDividend: Int init { // Storing the upper Bound and Lower bound of Y Markers yUpperReading = yMarkerList.size - 1 yLowerReading = 0 // Difference between each Y Markers yDividend = 1 } /** * This is the function which is responsible for the calculations of all the graph related stuff * * @param size This is the size of the whole canvas which also haves the componentSize in it */ override fun DrawScope.doCalculations(size: Size) { // Scale of Y - Axis of the Graph val yScale = size.height / numOfYMarkers // maximum Width of the Y - Markers val yMarkerMaxWidth = calculateYMarkersCoordinates(yScale = yScale) // X - Axis Scale val xScale = (size.width - yMarkerMaxWidth) / numOfXMarkers // This function calculates the Coordinates for the Readings calculateReadingsCoordinates( xScale = xScale, yScale = yScale, yMarkerMaxWidth = yMarkerMaxWidth ) // This function calculates the Coordinates for the X - Markers calculateXMarkersCoordinates( size = size, xScale = xScale, yMarkerMaxWidth = yMarkerMaxWidth ) } /** * This function calculates the Y - Axis Markers Coordinates * * @param yScale This is the scale for the Y - Axis */ private fun calculateYMarkersCoordinates(yScale: Float): Int { var maxDimension = 0 // Calculating all the chart Y - Axis markers in the chart along with their coordinates yMarkerList.forEachIndexed { index, point -> point.value as BitmapDrawable // Current Y Coordinate for the point val currentYCoordinate = (yScale * index) - (dimension.toFloat() / 2f) val resizedBitmap = Bitmap.createScaledBitmap(point.value.bitmap, dimension, dimension, true) if (resizedBitmap.width > maxDimension) maxDimension = resizedBitmap.width // Setting the calculated graph coordinates to the object point.setXCoordinate(-24f) point.setYCoordinate(currentYCoordinate) } return maxDimension } /** * This function calculates the Coordinates for the Readings * * @param xScale This is the scale for the X - Axis * @param yScale This is the scale for the Y - Axis * @param yMarkerMaxWidth This is the maximum width of the Y - Markers */ private fun calculateReadingsCoordinates(xScale: Float, yScale: Float, yMarkerMaxWidth: Int) { // Taking all the points given and calculating where they will stay in the graph yAxisReadings.forEach { pointSet -> pointSet.forEachIndexed { index, point -> val currentYCoordinate = (yUpperReading - point.value) * yScale / yDividend val currentXCoordinate = 48f + (index * xScale) + yMarkerMaxWidth // Setting the calculated graph coordinates to the object point.setXCoordinate(currentXCoordinate) point.setYCoordinate(currentYCoordinate) } } } /** * This Function calculates the coordinates for the X Markers * * @param size This is the size of the canvas * @param xScale This is the scale for the X - Axis * @param yMarkerMaxWidth This is the maximum width of the Y - Markers */ private fun calculateXMarkersCoordinates(size: Size, xScale: Float, yMarkerMaxWidth: Int) { // Calculating all the chart X - Axis markers coordinates xAxisReadings.forEachIndexed { index, currentMarker -> val xCoordinate = (xScale * index) + 48f + yMarkerMaxWidth val yCoordinate = size.height // Setting the calculated graph coordinates to the object currentMarker.setXCoordinate(xCoordinate) currentMarker.setYCoordinate(yCoordinate) } } }
JetChart/charts/src/main/java/dev/anirban/charts/linear/data/LinearEmojiData.kt
1174186599
package dev.anirban.charts.linear.colorconvention import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import dev.anirban.charts.linear.decoration.LinearDecoration import dev.anirban.charts.linear.interfaces.LinearColorConventionInterface /** * This class is the implementation of [LinearColorConventionInterface] which provides the * implementations for drawing the color conventions in the canvas * * @param textList This contains the list of strings which needs to be drawn in the Chart * @param fontSize This defines the size of the font * @param fontWeight This Defines the weight of the font */ class LinearGridColorConvention( override val textList: List<String>, private val fontSize: TextUnit = 14.sp, private val fontWeight: FontWeight = FontWeight.W500 ) : LinearColorConventionInterface { /** * This function draws the individual chart details or we can say the color codes along with * the text. * * @param text This is the text that would be shown before the value * @param color to be shown for this color convention * @param textColor This is the color of the text * */ @Composable fun ChartDetail( text: String, color: Color, textColor: Color ) { Row( modifier = Modifier .padding(bottom = 4.dp), verticalAlignment = Alignment.CenterVertically ) { // Drawing the small circles(color codes) Canvas( modifier = Modifier .padding(4.dp) .size(20.dp) ) { drawRoundRect( color = color, cornerRadius = CornerRadius(12f) ) } Spacer(modifier = Modifier.width(4.dp)) // Item Value Text( text = text, // Text Features textAlign = TextAlign.Center, fontSize = fontSize, fontWeight = fontWeight, color = textColor ) } } /** * This function draws the color conventions in the canvas * * @param decoration THis object contains the decorations of the graph */ @Composable override fun DrawColorConventions( decoration: LinearDecoration ) { Row( modifier = Modifier .fillMaxWidth(), horizontalArrangement = Arrangement.Start ) { // This contains the Color Conventions in the left side Column( modifier = Modifier .weight(1f), verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.Start ) { // Drawing Left column with the conventions for (index in textList.indices step 2) { // This function draws one of the color code Item details ChartDetail( text = textList[index], color = decoration.plotPrimaryColor[index], textColor = decoration.textColor ) } } // This contains the Color Conventions in the right side Column( modifier = Modifier .weight(1f), verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.Start ) { // Drawing Right column with the conventions for (index in 1 until textList.size step 2) { // This function draws one of the color code Item details ChartDetail( text = textList[index], color = decoration.plotPrimaryColor[index], textColor = decoration.textColor ) } } } } }
JetChart/charts/src/main/java/dev/anirban/charts/linear/colorconvention/LinearGridColorConvention.kt
1610506061
package dev.anirban.charts.linear.colorconvention import androidx.compose.runtime.Composable import dev.anirban.charts.linear.decoration.LinearDecoration import dev.anirban.charts.linear.interfaces.LinearColorConventionInterface /** * This class is the implementation of [LinearColorConventionInterface] which provides the * implementations for drawing the color conventions in the canvas * * @property textList This contains the list of strings which needs to be drawn in the Chart */ class LinearDefaultColorConvention : LinearColorConventionInterface { override val textList: List<String> = emptyList() /** * This function draws the color conventions. In this case this draws nothing in the Chart */ @Composable override fun DrawColorConventions( decoration: LinearDecoration ) { // Do Nothing } }
JetChart/charts/src/main/java/dev/anirban/charts/linear/colorconvention/LinearDefaultColorConvention.kt
3419198755
package dev.anirban.charts.linear.plots import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.TileMode import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Stroke import dev.anirban.charts.linear.data.LinearEmojiData import dev.anirban.charts.linear.decoration.LinearDecoration import dev.anirban.charts.linear.interfaces.LinearDataInterface import dev.anirban.charts.linear.interfaces.LinearPlotInterface /** * This is the Line Plot class which implements the [LinearPlotInterface] Interface and makes a Line * Chart * * @param lineStroke This defines the stroke of the line * @param circleRadius This defines the radius of curve of the Circle * @param colorList This is the list of colors for the gradient */ class LinearGradientLinePlot( private val lineStroke: Float = 3f, private val circleRadius: Float = 6f, private val colorList: List<Color> ) : LinearPlotInterface { /** * This is the function which contains the actual margin implementation * * @param linearData This is the data of the Line Chart * @param decoration THis is the decoration of the function */ override fun DrawScope.plotChart( linearData: LinearDataInterface, decoration: LinearDecoration ) { // Padding Offset that would be negated from the bar height to make it align with the chart var paddingOffset = 12f // If the data are in form of emoji's then the padding offset will change if (linearData is LinearEmojiData) { paddingOffset = -(linearData.dimension.toFloat() / 2f) } // Drawing the Lines and the linear Gradient in this Iteration linearData.yAxisReadings.forEachIndexed { i, coordinateSet -> // Path Variable val path = Path() // Moving to the (0,0) Origin Of the Graph path.moveTo( linearData.xAxisReadings.first().xCoordinate, linearData.yMarkerList.last().yCoordinate - paddingOffset ) // Defining the Brush val brush = Brush.horizontalGradient( colors = colorList, startX = linearData.xAxisReadings.first().xCoordinate, endX = linearData.xAxisReadings.last().xCoordinate, tileMode = TileMode.Clamp ) // joining all the lines in the Graph to each other in sequence coordinateSet.forEach { point -> // Current Line Point Added path.lineTo( x = point.xCoordinate, y = point.yCoordinate ) } // Adding the (Max , 0) point to finish the gradient in a proper sequence path.lineTo( linearData.xAxisReadings.last().xCoordinate, linearData.yMarkerList.last().yCoordinate - paddingOffset ) // Drawing the Lines of the graph drawPath( path = path, color = decoration.plotPrimaryColor[i], style = Stroke( width = lineStroke ) ) // Drawing the gradient of the graph drawPath( path = path, brush = brush ) } // Drawing all the Circles in this pass linearData.yAxisReadings.forEachIndexed { index, linearPoints -> linearPoints.forEach { point -> // This function draws the Circle points drawCircle( color = decoration.plotSecondaryColor[index], radius = circleRadius, center = point.getOffset() ) } } } }
JetChart/charts/src/main/java/dev/anirban/charts/linear/plots/LinearGradientLinePlot.kt
2001402432
package dev.anirban.charts.linear.plots import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.drawscope.DrawScope import dev.anirban.charts.linear.data.LinearEmojiData import dev.anirban.charts.linear.decoration.LinearDecoration import dev.anirban.charts.linear.interfaces.LinearDataInterface import dev.anirban.charts.linear.interfaces.LinearPlotInterface /** * This is the Line Plot class which implements the [LinearPlotInterface] Interface and makes a bar * Chart * * @param barWidth This defines the width of the bars of the bar Chart * @param cornerRadius This defines the radius of curve of the corners of the bars */ class LinearBarPlot( private val barWidth: Float = 30f, private val cornerRadius: Float = 12f ) : LinearPlotInterface { /** * This function plots the Bar Chart in the canvas * * @param linearData This is the data object which contains the data of the whole graph * @param decoration This object contains the decorations for the chart */ override fun DrawScope.plotChart( linearData: LinearDataInterface, decoration: LinearDecoration ) { // Padding Offset that would be negated from the bar height to make it align with the chart var paddingOffset = 12f // If the data are in form of emoji's then the padding offset will change if (linearData is LinearEmojiData) { paddingOffset = -(linearData.dimension.toFloat() / 2f) } // Adding the Offsets to the Variable linearData.yAxisReadings.forEach { coordinateSet -> coordinateSet.forEach { point -> // This function draws the Bars drawRoundRect( brush = Brush.verticalGradient( listOf( decoration.plotPrimaryColor.first(), decoration.plotPrimaryColor.last() ) ), topLeft = Offset( x = point.xCoordinate - barWidth / 2f, y = point.yCoordinate ), size = Size( width = barWidth, height = linearData.yMarkerList.last().yCoordinate - point.yCoordinate - paddingOffset ), cornerRadius = CornerRadius(cornerRadius) ) } } } }
JetChart/charts/src/main/java/dev/anirban/charts/linear/plots/LinearBarPlot.kt
2948474335
package dev.anirban.charts.linear.plots import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Stroke import dev.anirban.charts.linear.decoration.LinearDecoration import dev.anirban.charts.linear.interfaces.LinearDataInterface import dev.anirban.charts.linear.interfaces.LinearPlotInterface /** * This is the Line Plot class which implements the [LinearPlotInterface] Interface and makes a Line * Chart * * @param lineStroke This defines the stroke of the line * @param circleRadius This defines the radius of curve of the Circle */ class LinearLinePlot( private val lineStroke: Float = 3f, private val circleRadius: Float = 6f ) : LinearPlotInterface { /** * This is the function which contains the actual margin implementation * * @param linearData This is the data of the Line Chart * @param decoration THis is the decoration of the function */ override fun DrawScope.plotChart( linearData: LinearDataInterface, decoration: LinearDecoration ) { // This loop makes the curved line between two points linearData.yAxisReadings.forEachIndexed { coordinateSetIndex, coordinateSet -> // Path Variable val path = Path() // Moving to the start path of the the coordinate set to start making the Curved lines path.moveTo( coordinateSet[0].xCoordinate, coordinateSet[0].yCoordinate ) // Inner Loop which draws the Lines from point to point of a single coordinate sets for (index in 0 until coordinateSet.size - 1) { // Points needed val currentPoint = coordinateSet[index] val nextPoint = coordinateSet[index + 1] // Control Points val control1X = (currentPoint.xCoordinate + nextPoint.xCoordinate) / 2f val control1Y = currentPoint.yCoordinate val control2X = (currentPoint.xCoordinate + nextPoint.xCoordinate) / 2f val control2Y = nextPoint.yCoordinate // Defining the path from the last stayed to the next point path.cubicTo( x1 = control1X, y1 = control1Y, x2 = control2X, y2 = control2Y, x3 = nextPoint.xCoordinate, y3 = nextPoint.yCoordinate ) } // Drawing path after defining all the points of a single coordinate set in the path drawPath( path = path, color = decoration.plotPrimaryColor[coordinateSetIndex], style = Stroke( width = lineStroke ) ) } // This loop draws the circles or the points of the coordinates1 linearData.yAxisReadings.forEachIndexed { index, offsets -> offsets.forEach { // This function draws the Circle points drawCircle( color = decoration.plotSecondaryColor[index], radius = circleRadius, center = it.getOffset() ) } } } }
JetChart/charts/src/main/java/dev/anirban/charts/linear/plots/LinearLinePlot.kt
605779703
package dev.anirban.charts.linear.interfaces import dev.anirban.charts.linear.decoration.LinearDecoration /** * This implementation is for handling all the possible exceptions that may cause while running the * library and hence I made custom Exceptions for the ease of developers to understand the * exceptions and fix them accordingly * * @property validateDataInput This functions validates the [LinearDataInterface] is implemented * properly and all the data is given properly over there * @property validateDecorationInput This function validates the [LinearDecoration] is implemented * properly and all the data needed for the Linear Decoration are provided properly * @property validateColorConventionInput This function validates the [LinearColorConventionInterface] * is implemented properly * @property validateTypeMismatch This function validates if the margin and the data passed are * supported or not so it can give a meaningful result to the developer */ interface LinearChartExceptionHandler { fun validateDataInput() fun validateDecorationInput() fun validateColorConventionInput() fun validateTypeMismatch() }
JetChart/charts/src/main/java/dev/anirban/charts/linear/interfaces/LinearChartExceptionHandler.kt
1062089473
package dev.anirban.charts.linear.interfaces import androidx.compose.runtime.Composable import dev.anirban.charts.linear.decoration.LinearDecoration import dev.anirban.charts.linear.colorconvention.* /** * This implementation shall be implemented by all the classes which are making color convention * implementation * * Implementations for this interface are :- [LinearDefaultColorConvention], * [LinearGridColorConvention] * * @property DrawColorConventions THis function draws the desired color Convention */ interface LinearColorConventionInterface { /** * This variable contains the list of strings which needs to be drawn in the color convention */ val textList: List<String> /** * This is the function which draws all the color convention */ @Composable fun DrawColorConventions(decoration: LinearDecoration) }
JetChart/charts/src/main/java/dev/anirban/charts/linear/interfaces/LinearColorConventionInterface.kt
3066486409
package dev.anirban.charts.linear.interfaces import androidx.compose.ui.graphics.drawscope.DrawScope import dev.anirban.charts.linear.decoration.LinearDecoration import dev.anirban.charts.linear.margins.LinearStringMargin /** * This is the interface which defines that all the Implementation for the Drawing of the margins * need to implement this interface. * * Implementations for this interface are :- [LinearStringMargin] * */ interface LinearMarginInterface { /** * This function draws the margins in the graph according to the implementation passed * * @param linearData This is the data for the graph * @param decoration This is the decoration for the graph */ fun DrawScope.drawMargin( linearData: LinearDataInterface, decoration: LinearDecoration ) }
JetChart/charts/src/main/java/dev/anirban/charts/linear/interfaces/LinearMarginInterface.kt
67023961
package dev.anirban.charts.linear.interfaces import androidx.compose.ui.graphics.drawscope.DrawScope import dev.anirban.charts.linear.decoration.LinearDecoration import dev.anirban.charts.linear.plots.* /** * This is the interface which needs to be every graph plot logic to work in the Library * * Implementations for this interface are :- [LinearBarPlot] , [LinearLinePlot] */ interface LinearPlotInterface { /** * This function plots the graph points */ fun DrawScope.plotChart( linearData: LinearDataInterface, decoration: LinearDecoration ) }
JetChart/charts/src/main/java/dev/anirban/charts/linear/interfaces/LinearPlotInterface.kt
1599791491
package dev.anirban.charts.linear.interfaces import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.drawscope.DrawScope import dev.anirban.charts.linear.decoration.LinearDecoration import dev.anirban.charts.linear.LinearChart /** * This interface in the interface which every Linear Chart Implementation has to implement for the * Library to work * * Implementations for this interface are :- [LinearChart] * */ interface LinearChartInterface { /** * This is the implementation of the [LinearMarginInterface]. The margins will be drawn in the graph * according to the implementation * * @see LinearMarginInterface */ val margin: LinearMarginInterface /** * This is the implementation of the [LinearDecoration]. The decoration will be drawn * in the graph according to the implementation * * @see LinearDecoration */ val decoration: LinearDecoration /** * This is the implementation of the [LinearDataInterface]. The data will be calculated according * to this business Login * * @see LinearDataInterface */ val linearData: LinearDataInterface /** * This is the implementation of the [LinearPlotInterface]. The plot will be drawn in the graph * according to the implementation * * @see LinearPlotInterface */ val plot: LinearPlotInterface /** * This is the implementation of [LinearColorConventionInterface]. This provides an implementation for * drawing the color conventions in the chart */ val colorConvention: LinearColorConventionInterface /** * This function draws the margin according to the implementation provided to it */ fun DrawScope.drawMargin() /** * This function draws the plot according to the plot implementation provided to us */ fun DrawScope.plotChart() /** * This function calls the color convention implementation and draws the color conventions */ @Composable fun DrawColorConvention() /** * This is the Build Function which starts composing the Charts and composes the Charts * * @param modifier This is for default modifications to be passed from the parent Class */ @Composable fun Build(modifier: Modifier) }
JetChart/charts/src/main/java/dev/anirban/charts/linear/interfaces/LinearChartInterface.kt
2871041799
package dev.anirban.charts.linear.interfaces import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.drawscope.DrawScope import dev.anirban.charts.linear.data.LinearStringData import dev.anirban.charts.util.ChartPoint /** * This is the Data Interface which has to be implemented by the class which makes a new * Implementation for the handling of data and calculations in the graph * * Implementations for this interface are :- [LinearStringData] */ interface LinearDataInterface { /** * These are the readings of the Y - Axis */ val yAxisReadings: List<List<ChartPoint<*>>> /** * These are the readings of the X - Axis */ val xAxisReadings: List<ChartPoint<*>> /** * These are the markers needed in X Axis */ val numOfXMarkers: Int /** * These are teh num of markers in Y-axis */ val numOfYMarkers: Int /** * List of all the markers in the Y - Axis */ var yMarkerList: MutableList<ChartPoint<*>> /** * THis is the function which contains most of the calculation logic of the graph */ fun DrawScope.doCalculations(size: Size) }
JetChart/charts/src/main/java/dev/anirban/charts/linear/interfaces/LinearDataInterface.kt
3487414443
package dev.anirban.charts.circular.decoration import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color /** * This is the class which contains the circular decoration data * * @param textColor Color of all the texts in the chart * @param colorList Primary Color list or the color list of the canvas arc in order */ class CircularDecoration( val textColor: Color, val colorList: List<Color> ) { /** * These function are used to make an object of [CircularDecoration] */ companion object { private val colorBlue = Color(0xFF0088FF) private val colorGreen = Color(0xFF2AD200) private val colorYellow = Color(0xFFEEE73B) private val colorRed = Color(0xFFFF2E2E) private val ringChartColors = listOf( Color(0xFFD74719).copy(alpha = .66f), Color(0xFFE8661D).copy(alpha = .66f), Color(0xFFD8DB31).copy(alpha = .66f), Color(0xFF3CC641).copy(alpha = .66f), Color(0xFF83D5E0).copy(alpha = .66f), Color(0xFFAB51CA).copy(alpha = .66f), Color(0xFFEA0EC6).copy(alpha = .66f) ) /** * Provides [CircularDecoration] Objects for the circular Donut Charts * * Needs a Composable function to get the color from the material Theme since its * a composable function * * @param textColor Color of all the texts in the chart * @param colorList Primary Color list or the color list of the canvas arc in order */ @Composable fun donutChartDecorations( textColor: Color = MaterialTheme.colorScheme.onSurface, colorList: List<Color> = listOf( colorBlue, colorGreen, colorYellow, colorRed ) ) = CircularDecoration( textColor = textColor, colorList = colorList ) /** * Provides [CircularDecoration] Objects for the circular Ring Charts * * Needs a Composable function to get the color from the material Theme since its * a composable function * * @param textColor Color of all the texts in the chart * @param colorList Primary Color list or the color list of the canvas arc in order */ @Composable fun ringChartDecoration( textColor: Color = MaterialTheme.colorScheme.onSurface, colorList: List<Color> = ringChartColors ) = CircularDecoration( textColor = textColor, colorList = colorList ) } }
JetChart/charts/src/main/java/dev/anirban/charts/circular/decoration/CircularDecoration.kt
1153639548
package dev.anirban.charts.circular import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.unit.dp import dev.anirban.charts.circular.center.CircularImageCenter import dev.anirban.charts.circular.colorconvention.CircularDefaultColorConvention import dev.anirban.charts.circular.data.CircularTargetDataBuilder import dev.anirban.charts.circular.exceptions.CircularDecorationMismatch import dev.anirban.charts.circular.foreground.CircularDonutTargetForeground import dev.anirban.charts.circular.interfaces.CircularCenterInterface import dev.anirban.charts.circular.interfaces.CircularChartInterface import dev.anirban.charts.circular.interfaces.CircularColorConventionInterface import dev.anirban.charts.circular.interfaces.CircularDataInterface import dev.anirban.charts.circular.interfaces.CircularExceptionHandler import dev.anirban.charts.circular.interfaces.CircularForegroundInterface import dev.anirban.charts.circular.decoration.CircularDecoration import dev.anirban.charts.circular.foreground.CircularRingForeground /** * This class extends from the [CircularChartInterface] which means its the root level class and it * also implements [CircularExceptionHandler] implementation which provides an implementation for * handling all the Exceptions * * @property circularCenter Implementation for the center of the chart * @property circularData Implementation for the data of the chart * @property circularDecoration Implementation for the decoration of the chart * @property circularForeground Implementation for the foreground of the chart * @property circularColorConvention Implementation for the color convention of the chart * * @property DrawCenter This function draws the center of the chart * @property doCalculations This function does the calculation of the chart * @property drawForeground This function draws the foreground of the chart * @property DrawColorConventions This function draws the Color Convention of the chart * @property Build This function starts building the circular Chart */ open class CircularChart( override val circularCenter: CircularCenterInterface, override val circularData: CircularDataInterface, override val circularDecoration: CircularDecoration, override val circularForeground: CircularForegroundInterface, override val circularColorConvention: CircularColorConventionInterface ) : CircularChartInterface, CircularExceptionHandler { /** * This validates that the decoration stuffs are given correctly or not */ override fun validateDecoration() { if (circularForeground !is CircularRingForeground) { if (circularDecoration.colorList.size < circularData.itemsList.size) throw CircularDecorationMismatch( "Need at least ${circularData.itemsList.size} amount" + " of Colors for ${circularData.itemsList.size} number of Items in List" + " where only ${circularDecoration.colorList.size} is passed" ) } else { if (circularDecoration.colorList.isEmpty()) throw CircularDecorationMismatch("Need at least two color for the Ring Chart Gradients") } } /** * This checks and validates all the Exceptions and see if all of them are okay before letting * the user run further for decreasing unnecessary confusion in finding the Exceptions */ override fun validateAll() { validateDecoration() } /** * Function to draw something on the center */ @Composable override fun DrawCenter() { circularCenter.DrawCenter( circularData = circularData, decoration = circularDecoration ) } /** * This function does mostly handle business and calculation related */ override fun doCalculations() { circularData.doCalculations() } /** * This function draws the foreground */ override fun DrawScope.drawForeground() { circularForeground.apply { drawForeground( circularData = circularData, decoration = circularDecoration ) } } /** * This function draws the Color Convention in the chart */ @Composable override fun DrawColorConventions() { circularColorConvention.DrawColorConventions( circularData = circularData, decoration = circularDecoration ) } /** * This is the Build Function which starts composing the Charts and composes the Charts * * @param modifier This is for default modifications to be passed from the parent Class */ @Composable override fun Build(modifier: Modifier) { // Validating the Inputs validateAll() // Donut Chart Column( modifier = Modifier .fillMaxWidth(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Box( modifier = modifier .size(300.dp) .drawBehind { // Calling all the necessary functions doCalculations() drawForeground() }, contentAlignment = Alignment.Center ) { // Draws the Center of the chart DrawCenter() } // This function draws the color convention DrawColorConventions() } } /** * Builder Composable Functions which makes the objects of [CircularChart] and these are * actually called by the users to make charts */ companion object { /** * This function creates an object of the [CircularChart] which draws a basic * donut chart with its color conventions drawn at side but the data is in the form of * Target and Achieved * * @param modifier THis is made so that modifications can be passed from the parent function * @param circularCenter This is the implementation which draws the center of the circle * @param circularData This is the data class implementation which handles the data * @param circularDecoration This is the decorations for the Circular Chart * @param circularForeground This is the implementation which draws the foreground of the chart * @param circularColorConvention This is the color Convention implementation of the chart */ @Composable fun DonutChartImage( modifier: Modifier = Modifier, circularCenter: CircularCenterInterface = CircularImageCenter(), circularData: CircularTargetDataBuilder, circularDecoration: CircularDecoration = CircularDecoration.donutChartDecorations(), circularForeground: CircularForegroundInterface = CircularDonutTargetForeground(), circularColorConvention: CircularColorConventionInterface = CircularDefaultColorConvention() ) = CircularChart( circularCenter = circularCenter, circularData = circularData.toCircularDonutTargetData(), circularDecoration = circularDecoration, circularForeground = circularForeground, circularColorConvention = circularColorConvention ).Build(modifier = modifier) } }
JetChart/charts/src/main/java/dev/anirban/charts/circular/CircularChart.kt
737088785
package dev.anirban.charts.circular.foreground import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Stroke import dev.anirban.charts.circular.decoration.CircularDecoration import dev.anirban.charts.circular.interfaces.CircularDataInterface import dev.anirban.charts.circular.interfaces.CircularForegroundInterface /** * This class implements the [CircularForegroundInterface] which is responsible for making the * foreground reading of the chart * * @param radiusMultiplier This is the multiplier to radius of the circle to make the Arcs a bit * bigger... Note :- Higher this value bigger the radius * @param strokeWidth This is the width of the stroke of the Arc * @param startAngle This defines the starting angle of the Chart Arc */ class CircularDonutForeground( private val radiusMultiplier: Float = 1.4f, private val strokeWidth: Float = 45f, private val startAngle: Float = 270f ) : CircularForegroundInterface { /** * This is the function which draws all the readings * * @param circularData This is the data of the chart * @param decoration This is the decoration of the chart */ override fun DrawScope.drawForeground( circularData: CircularDataInterface, decoration: CircularDecoration ) { val centerX = size.width / 2 val centerY = size.height / 2 val radius = (size.width / 4).coerceAtMost(size.height / 4) * radiusMultiplier val arcRect = Rect( centerX - radius, centerY - radius, centerX + radius, centerY + radius ) // This is used to define the sweep angle of each and every Floating Data var currentSweepAngle = startAngle // Drawing all the arcs circularData.sweepAngles.forEachIndexed { index, fl -> //This function draws the Arc drawArc( color = decoration.colorList[index], startAngle = currentSweepAngle, sweepAngle = fl, useCenter = false, size = arcRect.size, style = Stroke( width = strokeWidth ), topLeft = arcRect.topLeft ) // Marking the sweep angle for the next Floating Item currentSweepAngle += fl + 4f } } }
JetChart/charts/src/main/java/dev/anirban/charts/circular/foreground/CircularDonutForeground.kt
3704436577
package dev.anirban.charts.circular.foreground import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Stroke import dev.anirban.charts.circular.decoration.CircularDecoration import dev.anirban.charts.circular.interfaces.CircularDataInterface import dev.anirban.charts.circular.interfaces.CircularForegroundInterface /** * This class implements the [CircularForegroundInterface] which is responsible for making the * foreground reading of the chart * * @param radiusMultiplier This is the multiplier to radius of the circle to make the Arcs a bit * bigger... Note :- Higher this value bigger the radius * @param strokeWidth This is the width of the stroke of the Arc * @param startAngle This defines the starting angle of the Chart Arc */ class CircularRingForeground( private val radiusMultiplier: Float = 1.5f, private val strokeWidth: Float = 30f, private val startAngle: Float = 120f ) : CircularForegroundInterface { /** * This is the function which draws all the readings * * @param circularData This is the data of the chart * @param decoration This is the decoration of the chart */ override fun DrawScope.drawForeground( circularData: CircularDataInterface, decoration: CircularDecoration ) { val centerX = size.width / 2 val centerY = size.height / 2 val radius = (size.width / 4).coerceAtMost(size.height / 4) * radiusMultiplier val arcRect = Rect( centerX - radius, centerY - radius, centerX + radius, centerY + radius ) //This function draws the Background Arc drawArc( color = Color.LightGray.copy(alpha = .2f), startAngle = startAngle, sweepAngle = 300f, useCenter = false, size = arcRect.size, style = Stroke( width = strokeWidth, cap = StrokeCap.Round ), topLeft = arcRect.topLeft ) //This function draws the Foreground Arc drawArc( brush = Brush.linearGradient( colors = decoration.colorList, start = arcRect.bottomLeft, end = arcRect.topRight ), startAngle = startAngle, sweepAngle = circularData.sweepAngles.first(), useCenter = false, size = arcRect.size, style = Stroke( width = strokeWidth, cap = StrokeCap.Round ), topLeft = arcRect.topLeft ) } }
JetChart/charts/src/main/java/dev/anirban/charts/circular/foreground/CircularRingForeground.kt
627980004
package dev.anirban.charts.circular.foreground import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.drawscope.Stroke import dev.anirban.charts.circular.decoration.CircularDecoration import dev.anirban.charts.circular.interfaces.CircularDataInterface import dev.anirban.charts.circular.interfaces.CircularForegroundInterface /** * This class implements the [CircularForegroundInterface] which is responsible for making the * foreground reading of the chart * * @param radiusMultiplier This is the multiplier to radius of the circle to make the Arcs a bit * bigger... Note :- Higher this value bigger the radius * @param strokeWidth This is the width of the stroke of the Arc * @param startAngle This defines the starting angle of the Chart Arc */ class CircularDonutTargetForeground( private val radiusMultiplier: Float = 1.4f, private val strokeWidth: Float = 45f, private val startAngle: Float = 270f ) : CircularForegroundInterface { /** * This is the function which draws all the readings * * @param circularData This is the data of the chart * @param decoration This is the decoration of the chart */ override fun DrawScope.drawForeground( circularData: CircularDataInterface, decoration: CircularDecoration ) { val centerX = size.width / 2 val centerY = size.height / 2 val radius = (size.width / 4).coerceAtMost(size.height / 4) * radiusMultiplier val arcRect = Rect( centerX - radius, centerY - radius, centerX + radius, centerY + radius ) //This function draws the Background Arc drawArc( color = Color.LightGray.copy(alpha = .2f), startAngle = startAngle, sweepAngle = 360f, useCenter = false, size = arcRect.size, style = Stroke( width = strokeWidth ), topLeft = arcRect.topLeft ) // This is used to define the sweep angle of each and every Floating Data var currentSweepAngle = startAngle // Drawing all the arcs circularData.sweepAngles.forEachIndexed { index, fl -> //This function draws the Foreground Arc drawArc( color = decoration.colorList[index], startAngle = currentSweepAngle, sweepAngle = fl, useCenter = false, size = arcRect.size, style = Stroke( width = strokeWidth ), topLeft = arcRect.topLeft ) // Marking the sweep angle for the next Floating Item currentSweepAngle += fl + 4f } } }
JetChart/charts/src/main/java/dev/anirban/charts/circular/foreground/CircularDonutTargetForeground.kt
3024636557
package dev.anirban.charts.circular.center import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import dev.anirban.charts.circular.decoration.CircularDecoration import dev.anirban.charts.circular.interfaces.CircularCenterInterface import dev.anirban.charts.circular.interfaces.CircularDataInterface /** * This class is the implementation of [CircularCenterInterface] which focuses on providing an * implementation to draw 3 texts in the center of the Ring Chart * * This Class in particular is the implementation to draw texts * * @param title This is the first Text and the title of the Text shown in the Center * @param centerValue This is the text which contains the value and shown in the middle * @param status This contains the status message fpr the user */ class CircularRingTextCenter( private val title: String, private val centerValue: String, private val status: String ) : CircularCenterInterface { /** * This function draws 3 Text Composable functions as an implementation for the * Center of the Chart * * @param circularData This object contains the data of the graph * @param decoration THis object contains the decorations of the graph */ @Composable override fun DrawCenter( circularData: CircularDataInterface, decoration: CircularDecoration ) { // Holds all the texts composable Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { // Title Text( text = title, modifier = Modifier .padding(vertical = 2.dp), // Text Features textAlign = TextAlign.Center, fontSize = 12.sp, fontWeight = FontWeight.W400, color = decoration.textColor ) // Item and Value Text( text = centerValue, modifier = Modifier .padding(vertical = 2.dp), // Text Features textAlign = TextAlign.Center, fontSize = 14.sp, fontWeight = FontWeight.W800, color = decoration.textColor ) // Item and Value Text( text = status, modifier = Modifier .padding(vertical = 2.dp), // Text Features textAlign = TextAlign.Center, fontSize = 12.sp, fontWeight = FontWeight.W400, color = decoration.textColor ) } } }
JetChart/charts/src/main/java/dev/anirban/charts/circular/center/CircularRingTextCenter.kt
3782726533
package dev.anirban.charts.circular.center import androidx.compose.foundation.layout.padding import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import dev.anirban.charts.circular.decoration.CircularDecoration import dev.anirban.charts.circular.interfaces.CircularCenterInterface import dev.anirban.charts.circular.interfaces.CircularDataInterface import java.text.DecimalFormat /** * This class is the implementation of [CircularCenterInterface] which focuses on providing an * implementation to draw something on the center of the Circular Chart * * This Class in particular is the implementation to draw texts * * @param fontSize This defines the size of the font * @param fontWeight This Defines the weight of the font */ class CircularTargetTextCenter( private val fontSize: TextUnit = 12.sp, private val fontWeight: FontWeight = FontWeight.W500 ) : CircularCenterInterface { /** * This function Draws the % achieved in the Center of the Chart * * @param circularData This is the data object which contains all the data about the Chart * @param decoration This is the decoration which contains all the decorations of the Chart */ @Composable override fun DrawCenter( circularData: CircularDataInterface, decoration: CircularDecoration ) { // Percentage to be shown var percentage = circularData.itemsList[1].second / circularData.itemsList[0].second * 100 if (percentage.isNaN()) percentage = 0f if (percentage > 100f) percentage = 100f // Item and Value Text( text = "${DecimalFormat("#.##").format(percentage)} %", modifier = Modifier .padding(vertical = 4.dp), // Text Features fontSize = fontSize, fontWeight = fontWeight, color = decoration.textColor ) } }
JetChart/charts/src/main/java/dev/anirban/charts/circular/center/CircularTargetTextCenter.kt
4198983769
package dev.anirban.charts.circular.center import androidx.compose.runtime.Composable import dev.anirban.charts.circular.decoration.CircularDecoration import dev.anirban.charts.circular.interfaces.CircularCenterInterface import dev.anirban.charts.circular.interfaces.CircularDataInterface /** * This class is the implementation of [CircularCenterInterface] which focuses on providing an * opportunity to the developer to provide his own custom implementation for the Center * * This Class in particular is the implementation to draw texts * * @param body This contains the Composable function passed by the Dev to draw his custom * implementation for the Circle Chart Center */ class CircularCustomCenter( private val body: @Composable () -> Unit ) : CircularCenterInterface { /** * This function uses the implementation of UI given by developer and draws the Center * * @param circularData This object contains the data of the graph * @param decoration THis object contains the decorations of the graph */ @Composable override fun DrawCenter( circularData: CircularDataInterface, decoration: CircularDecoration ) { body() } }
JetChart/charts/src/main/java/dev/anirban/charts/circular/center/CircularCustomCenter.kt
1904598709
package dev.anirban.charts.circular.center import androidx.compose.runtime.Composable import dev.anirban.charts.circular.decoration.CircularDecoration import dev.anirban.charts.circular.interfaces.CircularCenterInterface import dev.anirban.charts.circular.interfaces.CircularDataInterface /** * This class is the implementation of [CircularCenterInterface] which focuses on providing an * implementation to draw something on the center of the Circular Chart * * This Class in particular is the implementation to draw nothing and it is served as a Default * implementation */ class CircularDefaultCenter : CircularCenterInterface { /** * This function does nothing which is fine since we want the default Circle Center to be nothing */ @Composable override fun DrawCenter( circularData: CircularDataInterface, decoration: CircularDecoration ) { // Does Nothing } }
JetChart/charts/src/main/java/dev/anirban/charts/circular/center/CircularDefaultCenter.kt
2631876721
package dev.anirban.charts.circular.center import androidx.compose.foundation.layout.size import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Check import androidx.compose.material3.Icon import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.dp import dev.anirban.charts.circular.decoration.CircularDecoration import dev.anirban.charts.circular.interfaces.CircularCenterInterface import dev.anirban.charts.circular.interfaces.CircularDataInterface /** * This class is the implementation of [CircularCenterInterface] which focuses on providing an * implementation to draw an image on the Chart * * This Class in particular is the implementation to draw texts * * @param */ class CircularImageCenter( private val image: ImageVector = Icons.Default.Check, private val contentDescription: String? = null ) : CircularCenterInterface { /** * This function draws an Image (by default a Tick Mark) in the center of the chart * * @param circularData This object contains the data of the graph * @param decoration THis object contains the decorations of the graph */ @Composable override fun DrawCenter( circularData: CircularDataInterface, decoration: CircularDecoration ) { // Percentage to be shown var percentage = circularData.itemsList[1].second / circularData.itemsList[0].second * 100 if (percentage.isNaN()) percentage = 0f if (percentage >= 100f) { Icon( imageVector = image, contentDescription = contentDescription, modifier = Modifier .size(24.dp) ) } } }
JetChart/charts/src/main/java/dev/anirban/charts/circular/center/CircularImageCenter.kt
4125540115
package dev.anirban.charts.circular.charts import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.unit.dp import dev.anirban.charts.circular.colorconvention.CircularTargetColorConvention import dev.anirban.charts.circular.CircularChart import dev.anirban.charts.circular.center.CircularDefaultCenter import dev.anirban.charts.circular.center.CircularTargetTextCenter import dev.anirban.charts.circular.colorconvention.CircularListColorConvention import dev.anirban.charts.circular.data.CircularTargetDataBuilder import dev.anirban.charts.circular.decoration.CircularDecoration import dev.anirban.charts.circular.foreground.CircularDonutForeground import dev.anirban.charts.circular.foreground.CircularDonutTargetForeground import dev.anirban.charts.circular.interfaces.CircularCenterInterface import dev.anirban.charts.circular.interfaces.CircularColorConventionInterface import dev.anirban.charts.circular.interfaces.CircularDataInterface import dev.anirban.charts.circular.interfaces.CircularForegroundInterface /** * This class is the sub - class of [CircularChart] class which is the root parent class of the * circular charts. * * This class in general provides an implementation for a donut chart which has its color conventions * in the same row as itself. * * @param circularCenter This is the implementation which draws the center of the circle * @param circularData This is the data class implementation which handles the data * @param circularDecoration This is the decorations for the Circular Chart * @param circularForeground This is the implementation which draws the foreground of the chart * @param circularColorConvention This is the color Convention implementation of the chart */ open class CircularDonutChartRow( override val circularCenter: CircularCenterInterface, override val circularData: CircularDataInterface, override val circularDecoration: CircularDecoration, override val circularForeground: CircularForegroundInterface, override val circularColorConvention: CircularColorConventionInterface ) : CircularChart( circularCenter, circularData, circularDecoration, circularForeground, circularColorConvention ) { /** * This is the Build Function which starts composing the Charts and composes the Charts * * @param modifier This is for default modifications to be passed from the parent Class */ @Composable override fun Build(modifier: Modifier) { // Validating the Inputs super.validateAll() // Making a row to fit the canvas and the color conventions Column( modifier = Modifier .fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { // Donut Chart Box( modifier = modifier .weight(1f) .size(180.dp) .drawBehind { // Calling all the necessary functions doCalculations() drawForeground() }, contentAlignment = Alignment.Center ) { // Draws the center of the chart DrawCenter() } // Color Conventions Box( modifier = Modifier .padding(end = 8.dp) .weight(1f), contentAlignment = Alignment.TopCenter ) { // Calling all the necessary functions super.DrawColorConventions() } } } } /** * Builder Composable Functions which makes the objects of [CircularDonutChartRow] and these are * actually called by the users to make charts */ companion object { /** * This function creates an object of the [CircularDonutChartRow] which draws a basic * donut chart with its color conventions drawn at side * * @param modifier THis is made so that modifications can be passed from the parent function * @param circularCenter This is the implementation which draws the center of the circle * @param circularData This is the data class implementation which handles the data * @param circularDecoration This is the decorations for the Circular Chart * @param circularForeground This is the implementation which draws the foreground of the chart * @param circularColorConvention This is the color Convention implementation of the chart */ @Composable fun DonutChartRow( modifier: Modifier = Modifier, circularCenter: CircularCenterInterface = CircularDefaultCenter(), circularData: CircularDataInterface, circularDecoration: CircularDecoration = CircularDecoration.donutChartDecorations(), circularForeground: CircularForegroundInterface = CircularDonutForeground(), circularColorConvention: CircularColorConventionInterface = CircularListColorConvention() ) = CircularDonutChartRow( circularCenter = circularCenter, circularData = circularData, circularDecoration = circularDecoration, circularForeground = circularForeground, circularColorConvention = circularColorConvention ).Build(modifier = modifier) /** * This function creates an object of the [CircularDonutChartRow] which draws a basic * donut chart with its color conventions drawn at side but the data is in the form of * Target and Achieved * * @param modifier THis is made so that modifications can be passed from the parent function * @param circularCenter This is the implementation which draws the center of the circle * @param circularData This is the data class implementation which handles the data * @param circularDecoration This is the decorations for the Circular Chart * @param circularForeground This is the implementation which draws the foreground of the chart * @param circularColorConvention This is the color Convention implementation of the chart */ @Composable fun TargetDonutChart( modifier: Modifier = Modifier, circularCenter: CircularCenterInterface = CircularTargetTextCenter(), circularData: CircularTargetDataBuilder, circularDecoration: CircularDecoration = CircularDecoration.donutChartDecorations(), circularForeground: CircularForegroundInterface = CircularDonutTargetForeground(), circularColorConvention: CircularColorConventionInterface = CircularTargetColorConvention() ) = CircularDonutChartRow( circularCenter = circularCenter, circularData = circularData.toCircularDonutTargetData(), circularDecoration = circularDecoration, circularForeground = circularForeground, circularColorConvention = circularColorConvention ).Build(modifier = modifier) } }
JetChart/charts/src/main/java/dev/anirban/charts/circular/charts/CircularDonutChartRow.kt
3377290578
package dev.anirban.charts.circular.charts import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.unit.dp import dev.anirban.charts.circular.CircularChart import dev.anirban.charts.circular.center.CircularDefaultCenter import dev.anirban.charts.circular.colorconvention.CircularGridColorConvention import dev.anirban.charts.circular.decoration.CircularDecoration import dev.anirban.charts.circular.foreground.CircularDonutForeground import dev.anirban.charts.circular.interfaces.CircularCenterInterface import dev.anirban.charts.circular.interfaces.CircularColorConventionInterface import dev.anirban.charts.circular.interfaces.CircularDataInterface import dev.anirban.charts.circular.interfaces.CircularForegroundInterface /** * This class is the sub - class of [CircularChart] class which is the root parent class of the * circular charts. * * This class in general provides an implementation for a donut chart which has its color conventions * in the same row as itself. * * @param circularCenter This is the implementation which draws the center of the circle * @param circularData This is the data class implementation which handles the data * @param circularDecoration This is the decorations for the Circular Chart * @param circularForeground This is the implementation which draws the foreground of the chart * @param circularColorConvention This is the color Convention implementation of the chart */ class CircularDonutChartColumn( override val circularCenter: CircularCenterInterface, override val circularData: CircularDataInterface, override val circularDecoration: CircularDecoration, override val circularForeground: CircularForegroundInterface, override val circularColorConvention: CircularColorConventionInterface ) : CircularChart( circularCenter, circularData, circularDecoration, circularForeground, circularColorConvention ) { /** * This is the Build Function which starts composing the Charts and composes the Charts * * @param modifier This is for default modifications to be passed from the parent Class */ @Composable override fun Build(modifier: Modifier) { // Making a row to fit the canvas and the color conventions Column( modifier = Modifier .fillMaxWidth(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { // Validating the Inputs super.validateAll() // Donut Chart Box( modifier = modifier .size(180.dp) .drawBehind { // Calling all the necessary functions doCalculations() drawForeground() }, contentAlignment = Alignment.Center ) { // Draws the Center of the chart DrawCenter() } // Color Conventions Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp), horizontalArrangement = Arrangement.SpaceEvenly ) { // Calling all the necessary functions super.DrawColorConventions() } } } /** * Builder Composable Functions which makes the objects of [CircularDonutChartColumn] and these are * actually called by the users to make charts */ companion object { /** * This function creates an object of the [CircularDonutChartColumn] which draws a basic * donut chart with its color conventions drawn at bottom * * @param modifier This is for modifications to be passed from the Parent Function * @param circularCenter This is the implementation which draws the center of the circle * @param circularData This is the data class implementation which handles the data * @param circularDecoration This is the decorations for the Circular Chart * @param circularForeground This is the implementation which draws the foreground of the chart * @param circularColorConvention This is the color Convention implementation of the chart */ @Composable fun DonutChartColumn( modifier: Modifier = Modifier, circularCenter: CircularCenterInterface = CircularDefaultCenter(), circularData: CircularDataInterface, circularDecoration: CircularDecoration = CircularDecoration.donutChartDecorations(), circularForeground: CircularForegroundInterface = CircularDonutForeground(), circularColorConvention: CircularColorConventionInterface = CircularGridColorConvention() ) { CircularDonutChartColumn( circularCenter = circularCenter, circularData = circularData, circularForeground = circularForeground, circularDecoration = circularDecoration, circularColorConvention = circularColorConvention ).Build(modifier = modifier) } } }
JetChart/charts/src/main/java/dev/anirban/charts/circular/charts/CircularDonutChartColumn.kt
2371685650
package dev.anirban.charts.circular.charts import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.unit.dp import dev.anirban.charts.circular.CircularChart import dev.anirban.charts.circular.center.CircularRingTextCenter import dev.anirban.charts.circular.colorconvention.CircularDefaultColorConvention import dev.anirban.charts.circular.data.CircularTargetDataBuilder import dev.anirban.charts.circular.decoration.CircularDecoration import dev.anirban.charts.circular.foreground.CircularRingForeground import dev.anirban.charts.circular.interfaces.CircularCenterInterface import dev.anirban.charts.circular.interfaces.CircularColorConventionInterface import dev.anirban.charts.circular.interfaces.CircularDataInterface import dev.anirban.charts.circular.interfaces.CircularForegroundInterface /** * This class is the sub - class of [CircularChart] class which is the root parent class of the * circular charts. * * This class in general provides an implementation for a ring chart. * * @param circularCenter This is the implementation which draws the center of the circle * @param circularData This is the data class implementation which handles the data * @param circularDecoration This is the decorations for the Circular Chart * @param circularForeground This is the implementation which draws the foreground of the chart * @param circularColorConvention This is the color Convention implementation of the chart */ class CircularRingChart( override val circularCenter: CircularCenterInterface, override val circularData: CircularDataInterface, override val circularDecoration: CircularDecoration, override val circularForeground: CircularForegroundInterface, override val circularColorConvention: CircularColorConventionInterface ) : CircularChart( circularCenter, circularData, circularDecoration, circularForeground, circularColorConvention ) { /** * This is the Build Function which starts composing the Charts and composes the Charts * * @param modifier This is for default modifications to be passed from the parent Class */ @Composable override fun Build(modifier: Modifier) { // Validating the Inputs super.validateAll() // Donut Chart Column( modifier = Modifier .fillMaxWidth(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Box( modifier = modifier .size(300.dp) .drawBehind { // Calling all the necessary functions doCalculations() drawForeground() }, contentAlignment = Alignment.Center ) { // Draws the Center of the chart DrawCenter() } // This function draws the color convention DrawColorConventions() } } /** * Builder Composable Functions which makes the objects of [CircularDonutChartRow] and these are * actually called by the users to make charts */ companion object { /** * This function creates an object of the [CircularRingChart] which draws a basic single ring chart * * @param modifier modifier to be passed down from the parent function * @param circularCenter This is the implementation which draws the center of the circle * @param circularData This is the data class implementation which handles the data * @param circularDecoration This is the decorations for the Circular Chart * @param circularForeground This is the implementation which draws the foreground of the chart * @param circularColorConvention This is the color Convention implementation of the chart */ @Composable fun SingleRingChart( modifier: Modifier = Modifier, circularCenter: CircularCenterInterface = CircularRingTextCenter("", "", ""), circularData: CircularTargetDataBuilder, circularDecoration: CircularDecoration = CircularDecoration.ringChartDecoration(), circularForeground: CircularForegroundInterface = CircularRingForeground(), circularColorConvention: CircularColorConventionInterface = CircularDefaultColorConvention() ) = CircularRingChart( circularCenter, circularData.toCircularRingTargetData(), circularDecoration, circularForeground, circularColorConvention ).Build(modifier = modifier) /** * This function creates an object of the [CircularRingChart] which draws a basic multiple ring chart * * @param modifier modifier to be passed down from the parent function * @param circularCenter This is the implementation which draws the center of the circle * @param circularData This is the data class implementation which handles the data * @param circularDecoration This is the decorations for the Circular Chart * @param circularForeground This is the implementation which draws the foreground of the chart * @param circularColorConvention This is the color Convention implementation of the chart */ @Composable fun MultipleRingChart( modifier: List<Modifier> = listOf(Modifier, Modifier), circularCenter: List<CircularCenterInterface> = listOf( CircularRingTextCenter("", "", ""), CircularRingTextCenter("", "", "") ), circularData: List<CircularTargetDataBuilder>, circularDecoration: List<CircularDecoration> = listOf( CircularDecoration.ringChartDecoration(), CircularDecoration.ringChartDecoration() ), circularForeground: List<CircularForegroundInterface> = listOf( CircularRingForeground(), CircularRingForeground() ), circularColorConvention: List<CircularColorConventionInterface> = listOf( CircularDefaultColorConvention(), CircularDefaultColorConvention() ) ) { Row( modifier = Modifier .fillMaxWidth(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { circularData.forEachIndexed { index, circularRingData -> Box( modifier = Modifier .weight(1f), contentAlignment = Alignment.Center ) { CircularRingChart( circularCenter[index], circularRingData.toCircularRingTargetData(), circularDecoration[index], circularForeground[index], circularColorConvention[index] ).Build(modifier = modifier[index].size(250.dp)) } } } } } }
JetChart/charts/src/main/java/dev/anirban/charts/circular/charts/CircularRingChart.kt
4217197910
package dev.anirban.charts.circular.exceptions import dev.anirban.charts.circular.decoration.CircularDecoration import dev.anirban.charts.circular.interfaces.CircularDataInterface /** * This class is used to throw an exception when the [CircularDecoration.colorList] size is lesser * than the [CircularDataInterface.itemsList] size */ class CircularDecorationMismatch(message: String?) : Exception(message)
JetChart/charts/src/main/java/dev/anirban/charts/circular/exceptions/CircularDecorationMismatch.kt
3753833233
package dev.anirban.charts.circular.data import dev.anirban.charts.circular.interfaces.CircularDataInterface /** * This class is the implementation of [CircularDataInterface] class which is responsible for * providing the implementation of business login and calculation logic behind the chart * * @param siUnit This is the SI Unit text * @param cgsUnit This is the CGS Unit text * @param conversionRate This is the conversion rate according to which the CGS values can be * transformed into SI Unit * * @property sweepAngles This is the list of sweep angles which could be calculated * */ class CircularRingTargetData( override val itemsList: List<Pair<String, Float>>, override val siUnit: String, override val cgsUnit: String, override val conversionRate: (Float) -> Float, ) : CircularDataInterface { override var sweepAngles: MutableList<Float> = mutableListOf() /** * This function calculates the sweep Angles */ override fun doCalculations() { // Percentage of the target achieved by the user var percentage = itemsList[1].second / itemsList[0].second // Checking if the percentage is above 100 % or not if (percentage > 1) percentage = 1f val angle = percentage * 300f // Adding the angle to the sweepAngle list sweepAngles = mutableListOf(angle) } }
JetChart/charts/src/main/java/dev/anirban/charts/circular/data/CircularRingTargetData.kt
2043144984
package dev.anirban.charts.circular.data import dev.anirban.charts.circular.interfaces.CircularDataInterface /** * This class is the implementation of [CircularDataInterface] class which is responsible for * providing the implementation of business login and calculation logic behind the chart * * @param itemsList This is the List of items to be shown in the chart * @param siUnit This is the SI Unit text * @param cgsUnit This is the CGS Unit text * @param conversionRate This is the conversion rate according to which the CGS values can be * transformed into SI Unit * * @property sweepAngles This is the list of sweep angles which could be calculated */ class CircularDonutListData( override val itemsList: List<Pair<String, Float>>, override val siUnit: String, override val cgsUnit: String, override val conversionRate: (Float) -> Float ) : CircularDataInterface { override var sweepAngles: MutableList<Float> = mutableListOf() /** * This function calculates the sweep Angles */ override fun doCalculations() { // Extracting the Floating values from the given list val dataList = itemsList.map { it.second } // Stores the sum of all the items in the list val sum = dataList.sum() /** * some value is subtracted because according to the UI there shall be some free space * between each graph. * * Free Space = Some Angles shall be subtracted so that * * We are taking a 4f minus between each and every Floating Data */ sweepAngles = dataList.map { (it / sum) * (360f - (dataList.size * 4f)) }.toMutableList() } }
JetChart/charts/src/main/java/dev/anirban/charts/circular/data/CircularDonutListData.kt
1259946651
package dev.anirban.charts.circular.data /** * This data class helps building the target and achieved data type by being a wrapper class and * letting us formulate data to the respective class after turing the data into List * * @param target This is the target variable * @param achieved This variable denotes the amount achieved * @param siUnit This is the SI Unit text * @param cgsUnit This is the CGS Unit text * @param conversionRate This is the conversion rate according to which the CGS values can be * transformed into SI Unit */ class CircularTargetDataBuilder( private var target: Float, private var achieved: Float, private val siUnit: String, private val cgsUnit: String, private val conversionRate: (Float) -> Float ) { /** * This function converts the [CircularTargetDataBuilder] class object into [CircularDonutTargetData] object */ fun toCircularDonutTargetData() = CircularDonutTargetData( itemsList = listOf( Pair("Target", target), Pair("Achieved", achieved) ), siUnit = siUnit, cgsUnit = cgsUnit, conversionRate = conversionRate ) /** * This function converts the [CircularTargetDataBuilder] class object into [CircularRingTargetData] class object */ fun toCircularRingTargetData() = CircularRingTargetData( itemsList = listOf( Pair("Target", target), Pair("Achieved", achieved) ), siUnit = siUnit, cgsUnit = cgsUnit, conversionRate = conversionRate ) }
JetChart/charts/src/main/java/dev/anirban/charts/circular/data/CircularTargetDataBuilder.kt
3183667553
package dev.anirban.charts.circular.data import dev.anirban.charts.circular.interfaces.CircularDataInterface /** * This class is the implementation of [CircularDataInterface] class which is responsible for * providing the implementation of business login and calculation logic behind the chart * * @param siUnit This is the SI Unit text * @param cgsUnit This is the CGS Unit text * @param conversionRate This is the conversion rate according to which the CGS values can be * transformed into SI Unit * * @property sweepAngles This is the list of sweep angles which could be calculated */ class CircularDonutTargetData( override val itemsList: List<Pair<String, Float>>, override val siUnit: String, override val cgsUnit: String, override val conversionRate: (Float) -> Float ) : CircularDataInterface { override var sweepAngles: MutableList<Float> = mutableListOf() /** * This function calculates the sweep Angles */ override fun doCalculations() { // Percentage of the target achieved by the user var percentage = itemsList[1].second / itemsList[0].second // Checking if the percentage is above 100 % or not if (percentage > 1) percentage = 1f val angle = percentage * 360f // Adding the angle to the sweepAngle list sweepAngles = mutableListOf(angle) } }
JetChart/charts/src/main/java/dev/anirban/charts/circular/data/CircularDonutTargetData.kt
1795297354