content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
/** * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Simple app to demonstrate CameraX Video capturing with Recorder ( to local files ), with the * following simple control follow: * - user starts capture. * - this app disables all UI selections. * - this app enables capture run-time UI (pause/resume/stop). * - user controls recording with run-time UI, eventually tap "stop" to end. * - this app informs CameraX recording to stop with recording.stop() (or recording.close()). * - CameraX notify this app that the recording is indeed stopped, with the Finalize event. * - this app starts VideoViewer fragment to view the captured result. */ package com.example.android.camerax.video.fragments import android.annotation.SuppressLint import android.content.ContentValues import android.content.res.Configuration import java.text.SimpleDateFormat import android.os.Bundle import android.provider.MediaStore import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.NavController import androidx.navigation.Navigation import com.example.android.camerax.video.R import com.example.android.camerax.video.databinding.FragmentCaptureBinding import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.core.CameraSelector import androidx.camera.core.Preview import androidx.camera.video.* import androidx.concurrent.futures.await import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import androidx.core.util.Consumer import androidx.core.view.updateLayoutParams import androidx.lifecycle.MutableLiveData import androidx.lifecycle.whenCreated import androidx.recyclerview.widget.LinearLayoutManager import com.example.android.camera.utils.GenericListAdapter import com.example.android.camerax.video.extensions.getAspectRatio import com.example.android.camerax.video.extensions.getAspectRatioString import com.example.android.camerax.video.extensions.getNameString import kotlinx.coroutines.* import java.util.* class CaptureFragment : Fragment() { // UI with ViewBinding private var _captureViewBinding: FragmentCaptureBinding? = null private val captureViewBinding get() = _captureViewBinding!! private val captureLiveStatus = MutableLiveData<String>() /** Host's navigation controller */ private val navController: NavController by lazy { Navigation.findNavController(requireActivity(), R.id.fragment_container) } private val cameraCapabilities = mutableListOf<CameraCapability>() private lateinit var videoCapture: VideoCapture<Recorder> private var currentRecording: Recording? = null private lateinit var recordingState:VideoRecordEvent // Camera UI states and inputs enum class UiState { IDLE, // Not recording, all UI controls are active. RECORDING, // Camera is recording, only display Pause/Resume & Stop button. FINALIZED, // Recording just completes, disable all RECORDING UI controls. RECOVERY // For future use. } private var cameraIndex = 0 private var qualityIndex = DEFAULT_QUALITY_IDX private var audioEnabled = false private val mainThreadExecutor by lazy { ContextCompat.getMainExecutor(requireContext()) } private var enumerationDeferred:Deferred<Unit>? = null // main cameraX capture functions /** * Always bind preview + video capture use case combinations in this sample * (VideoCapture can work on its own). The function should always execute on * the main thread. */ private suspend fun bindCaptureUsecase() { val cameraProvider = ProcessCameraProvider.getInstance(requireContext()).await() val cameraSelector = getCameraSelector(cameraIndex) // create the user required QualitySelector (video resolution): we know this is // supported, a valid qualitySelector will be created. val quality = cameraCapabilities[cameraIndex].qualities[qualityIndex] val qualitySelector = QualitySelector.from(quality) captureViewBinding.previewView.updateLayoutParams<ConstraintLayout.LayoutParams> { val orientation = [email protected] dimensionRatio = quality.getAspectRatioString(quality, (orientation == Configuration.ORIENTATION_PORTRAIT)) } val preview = Preview.Builder() .setTargetAspectRatio(quality.getAspectRatio(quality)) .build().apply { setSurfaceProvider(captureViewBinding.previewView.surfaceProvider) } // build a recorder, which can: // - record video/audio to MediaStore(only shown here), File, ParcelFileDescriptor // - be used create recording(s) (the recording performs recording) val recorder = Recorder.Builder() .setQualitySelector(qualitySelector) .build() videoCapture = VideoCapture.withOutput(recorder) try { cameraProvider.unbindAll() cameraProvider.bindToLifecycle( viewLifecycleOwner, cameraSelector, videoCapture, preview ) } catch (exc: Exception) { // we are on main thread, let's reset the controls on the UI. Log.e(TAG, "Use case binding failed", exc) resetUIandState("bindToLifecycle failed: $exc") } enableUI(true) } /** * Kick start the video recording * - config Recorder to capture to MediaStoreOutput * - register RecordEvent Listener * - apply audio request from user * - start recording! * After this function, user could start/pause/resume/stop recording and application listens * to VideoRecordEvent for the current recording status. */ @SuppressLint("MissingPermission") private fun startRecording() { // create MediaStoreOutputOptions for our recorder: resulting our recording! val name = "CameraX-recording-" + SimpleDateFormat(FILENAME_FORMAT, Locale.US) .format(System.currentTimeMillis()) + ".mp4" val contentValues = ContentValues().apply { put(MediaStore.Video.Media.DISPLAY_NAME, name) } val mediaStoreOutput = MediaStoreOutputOptions.Builder( requireActivity().contentResolver, MediaStore.Video.Media.EXTERNAL_CONTENT_URI) .setContentValues(contentValues) .build() // configure Recorder and Start recording to the mediaStoreOutput. currentRecording = videoCapture.output .prepareRecording(requireActivity(), mediaStoreOutput) .apply { if (audioEnabled) withAudioEnabled() } .start(mainThreadExecutor, captureListener) Log.i(TAG, "Recording started") } /** * CaptureEvent listener. */ private val captureListener = Consumer<VideoRecordEvent> { event -> // cache the recording state if (event !is VideoRecordEvent.Status) recordingState = event updateUI(event) if (event is VideoRecordEvent.Finalize) { // display the captured video lifecycleScope.launch { navController.navigate( CaptureFragmentDirections.actionCaptureToVideoViewer( event.outputResults.outputUri ) ) } } } /** * Retrieve the asked camera's type(lens facing type). In this sample, only 2 types: * idx is even number: CameraSelector.LENS_FACING_BACK * odd number: CameraSelector.LENS_FACING_FRONT */ private fun getCameraSelector(idx: Int) : CameraSelector { if (cameraCapabilities.size == 0) { Log.i(TAG, "Error: This device does not have any camera, bailing out") requireActivity().finish() } return (cameraCapabilities[idx % cameraCapabilities.size].camSelector) } data class CameraCapability(val camSelector: CameraSelector, val qualities:List<Quality>) /** * Query and cache this platform's camera capabilities, run only once. */ init { enumerationDeferred = lifecycleScope.async { whenCreated { val provider = ProcessCameraProvider.getInstance(requireContext()).await() provider.unbindAll() for (camSelector in arrayOf( CameraSelector.DEFAULT_BACK_CAMERA, CameraSelector.DEFAULT_FRONT_CAMERA )) { try { // just get the camera.cameraInfo to query capabilities // we are not binding anything here. if (provider.hasCamera(camSelector)) { val camera = provider.bindToLifecycle(requireActivity(), camSelector) QualitySelector .getSupportedQualities(camera.cameraInfo) .filter { quality -> listOf(Quality.UHD, Quality.FHD, Quality.HD, Quality.SD) .contains(quality) }.also { cameraCapabilities.add(CameraCapability(camSelector, it)) } } } catch (exc: java.lang.Exception) { Log.e(TAG, "Camera Face $camSelector is not supported") } } } } } /** * One time initialize for CameraFragment (as a part of fragment layout's creation process). * This function performs the following: * - initialize but disable all UI controls except the Quality selection. * - set up the Quality selection recycler view. * - bind use cases to a lifecycle camera, enable UI controls. */ private fun initCameraFragment() { initializeUI() viewLifecycleOwner.lifecycleScope.launch { if (enumerationDeferred != null) { enumerationDeferred!!.await() enumerationDeferred = null } initializeQualitySectionsUI() bindCaptureUsecase() } } /** * Initialize UI. Preview and Capture actions are configured in this function. * Note that preview and capture are both initialized either by UI or CameraX callbacks * (except the very 1st time upon entering to this fragment in onCreateView() */ @SuppressLint("ClickableViewAccessibility", "MissingPermission") private fun initializeUI() { captureViewBinding.cameraButton.apply { setOnClickListener { cameraIndex = (cameraIndex + 1) % cameraCapabilities.size // camera device change is in effect instantly: // - reset quality selection // - restart preview qualityIndex = DEFAULT_QUALITY_IDX initializeQualitySectionsUI() enableUI(false) viewLifecycleOwner.lifecycleScope.launch { bindCaptureUsecase() } } isEnabled = false } // audioEnabled by default is disabled. captureViewBinding.audioSelection.isChecked = audioEnabled captureViewBinding.audioSelection.setOnClickListener { audioEnabled = captureViewBinding.audioSelection.isChecked } // React to user touching the capture button captureViewBinding.captureButton.apply { setOnClickListener { if (!this@CaptureFragment::recordingState.isInitialized || recordingState is VideoRecordEvent.Finalize) { enableUI(false) // Our eventListener will turn on the Recording UI. startRecording() } else { when (recordingState) { is VideoRecordEvent.Start -> { currentRecording?.pause() captureViewBinding.stopButton.visibility = View.VISIBLE } is VideoRecordEvent.Pause -> currentRecording?.resume() is VideoRecordEvent.Resume -> currentRecording?.pause() else -> throw IllegalStateException("recordingState in unknown state") } } } isEnabled = false } captureViewBinding.stopButton.apply { setOnClickListener { // stopping: hide it after getting a click before we go to viewing fragment captureViewBinding.stopButton.visibility = View.INVISIBLE if (currentRecording == null || recordingState is VideoRecordEvent.Finalize) { return@setOnClickListener } val recording = currentRecording if (recording != null) { recording.stop() currentRecording = null } captureViewBinding.captureButton.setImageResource(R.drawable.ic_start) } // ensure the stop button is initialized disabled & invisible visibility = View.INVISIBLE isEnabled = false } captureLiveStatus.observe(viewLifecycleOwner) { captureViewBinding.captureStatus.apply { post { text = it } } } captureLiveStatus.value = getString(R.string.Idle) } /** * UpdateUI according to CameraX VideoRecordEvent type: * - user starts capture. * - this app disables all UI selections. * - this app enables capture run-time UI (pause/resume/stop). * - user controls recording with run-time UI, eventually tap "stop" to end. * - this app informs CameraX recording to stop with recording.stop() (or recording.close()). * - CameraX notify this app that the recording is indeed stopped, with the Finalize event. * - this app starts VideoViewer fragment to view the captured result. */ private fun updateUI(event: VideoRecordEvent) { val state = if (event is VideoRecordEvent.Status) recordingState.getNameString() else event.getNameString() when (event) { is VideoRecordEvent.Status -> { // placeholder: we update the UI with new status after this when() block, // nothing needs to do here. } is VideoRecordEvent.Start -> { showUI(UiState.RECORDING, event.getNameString()) } is VideoRecordEvent.Finalize-> { showUI(UiState.FINALIZED, event.getNameString()) } is VideoRecordEvent.Pause -> { captureViewBinding.captureButton.setImageResource(R.drawable.ic_resume) } is VideoRecordEvent.Resume -> { captureViewBinding.captureButton.setImageResource(R.drawable.ic_pause) } } val stats = event.recordingStats val size = stats.numBytesRecorded / 1000 val time = java.util.concurrent.TimeUnit.NANOSECONDS.toSeconds(stats.recordedDurationNanos) var text = "${state}: recorded ${size}KB, in ${time}second" if(event is VideoRecordEvent.Finalize) text = "${text}\nFile saved to: ${event.outputResults.outputUri}" captureLiveStatus.value = text Log.i(TAG, "recording event: $text") } /** * Enable/disable UI: * User could select the capture parameters when recording is not in session * Once recording is started, need to disable able UI to avoid conflict. */ private fun enableUI(enable: Boolean) { arrayOf(captureViewBinding.cameraButton, captureViewBinding.captureButton, captureViewBinding.stopButton, captureViewBinding.audioSelection, captureViewBinding.qualitySelection).forEach { it.isEnabled = enable } // disable the camera button if no device to switch if (cameraCapabilities.size <= 1) { captureViewBinding.cameraButton.isEnabled = false } // disable the resolution list if no resolution to switch if (cameraCapabilities[cameraIndex].qualities.size <= 1) { captureViewBinding.qualitySelection.apply { isEnabled = false } } } /** * initialize UI for recording: * - at recording: hide audio, qualitySelection,change camera UI; enable stop button * - otherwise: show all except the stop button */ private fun showUI(state: UiState, status:String = "idle") { captureViewBinding.let { when(state) { UiState.IDLE -> { it.captureButton.setImageResource(R.drawable.ic_start) it.stopButton.visibility = View.INVISIBLE it.cameraButton.visibility= View.VISIBLE it.audioSelection.visibility = View.VISIBLE it.qualitySelection.visibility=View.VISIBLE } UiState.RECORDING -> { it.cameraButton.visibility = View.INVISIBLE it.audioSelection.visibility = View.INVISIBLE it.qualitySelection.visibility = View.INVISIBLE it.captureButton.setImageResource(R.drawable.ic_pause) it.captureButton.isEnabled = true it.stopButton.visibility = View.VISIBLE it.stopButton.isEnabled = true } UiState.FINALIZED -> { it.captureButton.setImageResource(R.drawable.ic_start) it.stopButton.visibility = View.INVISIBLE } else -> { val errorMsg = "Error: showUI($state) is not supported" Log.e(TAG, errorMsg) return } } it.captureStatus.text = status } } /** * ResetUI (restart): * in case binding failed, let's give it another change for re-try. In future cases * we might fail and user get notified on the status */ private fun resetUIandState(reason: String) { enableUI(true) showUI(UiState.IDLE, reason) cameraIndex = 0 qualityIndex = DEFAULT_QUALITY_IDX audioEnabled = false captureViewBinding.audioSelection.isChecked = audioEnabled initializeQualitySectionsUI() } /** * initializeQualitySectionsUI(): * Populate a RecyclerView to display camera capabilities: * - one front facing * - one back facing * User selection is saved to qualityIndex, will be used * in the bindCaptureUsecase(). */ private fun initializeQualitySectionsUI() { val selectorStrings = cameraCapabilities[cameraIndex].qualities.map { it.getNameString() } // create the adapter to Quality selection RecyclerView captureViewBinding.qualitySelection.apply { layoutManager = LinearLayoutManager(context) adapter = GenericListAdapter( selectorStrings, itemLayoutId = R.layout.video_quality_item ) { holderView, qcString, position -> holderView.apply { findViewById<TextView>(R.id.qualityTextView)?.text = qcString // select the default quality selector isSelected = (position == qualityIndex) } holderView.setOnClickListener { view -> if (qualityIndex == position) return@setOnClickListener captureViewBinding.qualitySelection.let { // deselect the previous selection on UI. it.findViewHolderForAdapterPosition(qualityIndex) ?.itemView ?.isSelected = false } // turn on the new selection on UI. view.isSelected = true qualityIndex = position // rebind the use cases to put the new QualitySelection in action. enableUI(false) viewLifecycleOwner.lifecycleScope.launch { bindCaptureUsecase() } } } isEnabled = false } } // System function implementations override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _captureViewBinding = FragmentCaptureBinding.inflate(inflater, container, false) return captureViewBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initCameraFragment() } override fun onDestroyView() { _captureViewBinding = null super.onDestroyView() } companion object { // default Quality selection if no input from UI const val DEFAULT_QUALITY_IDX = 0 val TAG:String = CaptureFragment::class.java.simpleName private const val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS" } }
OKCameraXVideo/app/src/main/java/com/example/android/camerax/video/fragments/CaptureFragment.kt
154117838
/** * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.camerax.video.extensions import androidx.camera.core.AspectRatio import androidx.camera.video.Quality /** * a helper function to retrieve the aspect ratio from a QualitySelector enum. */ fun Quality.getAspectRatio(quality: Quality): Int { return when { arrayOf(Quality.UHD, Quality.FHD, Quality.HD) .contains(quality) -> AspectRatio.RATIO_16_9 (quality == Quality.SD) -> AspectRatio.RATIO_4_3 else -> throw UnsupportedOperationException() } } /** * a helper function to retrieve the aspect ratio string from a Quality enum. */ fun Quality.getAspectRatioString(quality: Quality, portraitMode:Boolean) :String { val hdQualities = arrayOf(Quality.UHD, Quality.FHD, Quality.HD) val ratio = when { hdQualities.contains(quality) -> Pair(16, 9) quality == Quality.SD -> Pair(4, 3) else -> throw UnsupportedOperationException() } return if (portraitMode) "V,${ratio.second}:${ratio.first}" else "H,${ratio.first}:${ratio.second}" } /** * Get the name (a string) from the given Video.Quality object. */ fun Quality.getNameString() :String { return when (this) { Quality.UHD -> "QUALITY_UHD(2160p)" Quality.FHD -> "QUALITY_FHD(1080p)" Quality.HD -> "QUALITY_HD(720p)" Quality.SD -> "QUALITY_SD(480p)" else -> throw IllegalArgumentException("Quality $this is NOT supported") } } /** * Translate Video.Quality name(a string) to its Quality object. */ fun Quality.getQualityObject(name:String) : Quality { return when (name) { Quality.UHD.getNameString() -> Quality.UHD Quality.FHD.getNameString() -> Quality.FHD Quality.HD.getNameString() -> Quality.HD Quality.SD.getNameString() -> Quality.SD else -> throw IllegalArgumentException("Quality string $name is NOT supported") } }
OKCameraXVideo/app/src/main/java/com/example/android/camerax/video/extensions/VideoQualityExt.kt
3164576559
/** * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.camerax.video.extensions import androidx.camera.video.VideoRecordEvent /** * A helper extended function to get the name(string) for the VideoRecordEvent. */ fun VideoRecordEvent.getNameString() : String { return when (this) { is VideoRecordEvent.Status -> "Status" is VideoRecordEvent.Start -> "Started" is VideoRecordEvent.Finalize-> "Finalized" is VideoRecordEvent.Pause -> "Paused" is VideoRecordEvent.Resume -> "Resumed" else -> throw IllegalArgumentException("Unknown VideoRecordEvent: $this") } }
OKCameraXVideo/app/src/main/java/com/example/android/camerax/video/extensions/VideoRecordEventExt.kt
1298668593
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.camerax.video import android.app.Application import android.util.Log import androidx.camera.camera2.Camera2Config import androidx.camera.core.CameraXConfig /** * Set CameraX logging level to Log.ERROR to avoid excessive logcat messages. * Refer to https://developer.android.com/reference/androidx/camera/core/CameraXConfig.Builder#setMinimumLoggingLevel(int) * for details. */ class MainApplication : Application(), CameraXConfig.Provider { override fun getCameraXConfig(): CameraXConfig { return CameraXConfig.Builder.fromConfig(Camera2Config.defaultConfig()) .setMinimumLoggingLevel(Log.ERROR).build() } }
OKCameraXVideo/app/src/main/java/com/example/android/camerax/video/MainApplication.kt
318548658
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.camera.utils import android.graphics.Point import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.params.StreamConfigurationMap import android.util.Size import android.view.Display import kotlin.math.max import kotlin.math.min /** Helper class used to pre-compute shortest and longest sides of a [Size] */ class SmartSize(width: Int, height: Int) { var size = Size(width, height) var long = max(size.width, size.height) var short = min(size.width, size.height) override fun toString() = "SmartSize(${long}x${short})" } /** Standard High Definition size for pictures and video */ val SIZE_1080P: SmartSize = SmartSize(1920, 1080) /** Returns a [SmartSize] object for the given [Display] */ fun getDisplaySmartSize(display: Display): SmartSize { val outPoint = Point() display.getRealSize(outPoint) return SmartSize(outPoint.x, outPoint.y) } /** * Returns the largest available PREVIEW size. For more information, see: * https://d.android.com/reference/android/hardware/camera2/CameraDevice and * https://developer.android.com/reference/android/hardware/camera2/params/StreamConfigurationMap */ fun <T>getPreviewOutputSize( display: Display, characteristics: CameraCharacteristics, targetClass: Class<T>, format: Int? = null ): Size { // Find which is smaller: screen or 1080p val screenSize = getDisplaySmartSize(display) val hdScreen = screenSize.long >= SIZE_1080P.long || screenSize.short >= SIZE_1080P.short val maxSize = if (hdScreen) SIZE_1080P else screenSize // If image format is provided, use it to determine supported sizes; else use target class val config = characteristics.get( CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)!! if (format == null) assert(StreamConfigurationMap.isOutputSupportedFor(targetClass)) else assert(config.isOutputSupportedFor(format)) val allSizes = if (format == null) config.getOutputSizes(targetClass) else config.getOutputSizes(format) // Get available sizes and sort them by area from largest to smallest val validSizes = allSizes .sortedWith(compareBy { it.height * it.width }) .map { SmartSize(it.width, it.height) }.reversed() // Then, get the largest output size that is smaller or equal than our max size return validSizes.first { it.long <= maxSize.long && it.short <= maxSize.short }.size }
OKCameraXVideo/utils/src/main/java/com/example/android/camera/utils/CameraSizes.kt
3467346831
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.camera.utils import android.graphics.Bitmap import android.graphics.Matrix import android.util.Log import androidx.exifinterface.media.ExifInterface private const val TAG: String = "ExifUtils" /** Transforms rotation and mirroring information into one of the [ExifInterface] constants */ fun computeExifOrientation(rotationDegrees: Int, mirrored: Boolean) = when { rotationDegrees == 0 && !mirrored -> ExifInterface.ORIENTATION_NORMAL rotationDegrees == 0 && mirrored -> ExifInterface.ORIENTATION_FLIP_HORIZONTAL rotationDegrees == 180 && !mirrored -> ExifInterface.ORIENTATION_ROTATE_180 rotationDegrees == 180 && mirrored -> ExifInterface.ORIENTATION_FLIP_VERTICAL rotationDegrees == 270 && mirrored -> ExifInterface.ORIENTATION_TRANSVERSE rotationDegrees == 90 && !mirrored -> ExifInterface.ORIENTATION_ROTATE_90 rotationDegrees == 90 && mirrored -> ExifInterface.ORIENTATION_TRANSPOSE rotationDegrees == 270 && mirrored -> ExifInterface.ORIENTATION_ROTATE_270 rotationDegrees == 270 && !mirrored -> ExifInterface.ORIENTATION_TRANSVERSE else -> ExifInterface.ORIENTATION_UNDEFINED } /** * Helper function used to convert an EXIF orientation enum into a transformation matrix * that can be applied to a bitmap. * * @return matrix - Transformation required to properly display [Bitmap] */ fun decodeExifOrientation(exifOrientation: Int): Matrix { val matrix = Matrix() // Apply transformation corresponding to declared EXIF orientation when (exifOrientation) { ExifInterface.ORIENTATION_NORMAL -> Unit ExifInterface.ORIENTATION_UNDEFINED -> Unit ExifInterface.ORIENTATION_ROTATE_90 -> matrix.postRotate(90F) ExifInterface.ORIENTATION_ROTATE_180 -> matrix.postRotate(180F) ExifInterface.ORIENTATION_ROTATE_270 -> matrix.postRotate(270F) ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.postScale(-1F, 1F) ExifInterface.ORIENTATION_FLIP_VERTICAL -> matrix.postScale(1F, -1F) ExifInterface.ORIENTATION_TRANSPOSE -> { matrix.postScale(-1F, 1F) matrix.postRotate(270F) } ExifInterface.ORIENTATION_TRANSVERSE -> { matrix.postScale(-1F, 1F) matrix.postRotate(90F) } // Error out if the EXIF orientation is invalid else -> Log.e(TAG, "Invalid orientation: $exifOrientation") } // Return the resulting matrix return matrix }
OKCameraXVideo/utils/src/main/java/com/example/android/camera/utils/ExifUtils.kt
4135360234
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.camera.utils import android.content.Context import android.util.AttributeSet import android.util.Log import android.view.SurfaceView import kotlin.math.roundToInt /** * A [SurfaceView] that can be adjusted to a specified aspect ratio and * performs center-crop transformation of input frames. */ class AutoFitSurfaceView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyle: Int = 0 ) : SurfaceView(context, attrs, defStyle) { private var aspectRatio = 0f /** * Sets the aspect ratio for this view. The size of the view will be * measured based on the ratio calculated from the parameters. * * @param width Camera resolution horizontal size * @param height Camera resolution vertical size */ fun setAspectRatio(width: Int, height: Int) { require(width > 0 && height > 0) { "Size cannot be negative" } aspectRatio = width.toFloat() / height.toFloat() holder.setFixedSize(width, height) requestLayout() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val width = MeasureSpec.getSize(widthMeasureSpec) val height = MeasureSpec.getSize(heightMeasureSpec) if (aspectRatio == 0f) { setMeasuredDimension(width, height) } else { // Performs center-crop transformation of the camera frames val newWidth: Int val newHeight: Int val actualRatio = if (width > height) aspectRatio else 1f / aspectRatio if (width < height * actualRatio) { newHeight = height newWidth = (height * actualRatio).roundToInt() } else { newWidth = width newHeight = (width / actualRatio).roundToInt() } Log.d(TAG, "Measured dimensions set: $newWidth x $newHeight") setMeasuredDimension(newWidth, newHeight) } } companion object { private val TAG = AutoFitSurfaceView::class.java.simpleName } }
OKCameraXVideo/utils/src/main/java/com/example/android/camera/utils/AutoFitSurfaceView.kt
3597863441
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.camera.utils import android.content.Context import android.graphics.Bitmap import android.graphics.ImageFormat import android.media.Image import android.renderscript.Allocation import android.renderscript.Element import android.renderscript.RenderScript import android.renderscript.ScriptIntrinsicYuvToRGB import android.renderscript.Type import java.nio.ByteBuffer /** * Helper class used to convert a [Image] object from * [ImageFormat.YUV_420_888] format to an RGB [Bitmap] object, it has equivalent * functionality to https://github * .com/androidx/androidx/blob/androidx-main/camera/camera-core/src/main/java/androidx/camera/core/ImageYuvToRgbConverter.java * * NOTE: This has been tested in a limited number of devices and is not * considered production-ready code. It was created for illustration purposes, * since this is not an efficient camera pipeline due to the multiple copies * required to convert each frame. For example, this * implementation * (https://stackoverflow.com/questions/52726002/camera2-captured-picture-conversion-from-yuv-420-888-to-nv21/52740776#52740776) * might have better performance. */ class YuvToRgbConverter(context: Context) { private val rs = RenderScript.create(context) private val scriptYuvToRgb = ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs)) // Do not add getters/setters functions to these private variables // because yuvToRgb() assume they won't be modified elsewhere private var yuvBits: ByteBuffer? = null private var bytes: ByteArray = ByteArray(0) private var inputAllocation: Allocation? = null private var outputAllocation: Allocation? = null @Synchronized fun yuvToRgb(image: Image, output: Bitmap) { val yuvBuffer = YuvByteBuffer(image, yuvBits) yuvBits = yuvBuffer.buffer if (needCreateAllocations(image, yuvBuffer)) { val yuvType = Type.Builder(rs, Element.U8(rs)) .setX(image.width) .setY(image.height) .setYuvFormat(yuvBuffer.type) inputAllocation = Allocation.createTyped( rs, yuvType.create(), Allocation.USAGE_SCRIPT ) bytes = ByteArray(yuvBuffer.buffer.capacity()) val rgbaType = Type.Builder(rs, Element.RGBA_8888(rs)) .setX(image.width) .setY(image.height) outputAllocation = Allocation.createTyped( rs, rgbaType.create(), Allocation.USAGE_SCRIPT ) } yuvBuffer.buffer.get(bytes) inputAllocation!!.copyFrom(bytes) // Convert NV21 or YUV_420_888 format to RGB inputAllocation!!.copyFrom(bytes) scriptYuvToRgb.setInput(inputAllocation) scriptYuvToRgb.forEach(outputAllocation) outputAllocation!!.copyTo(output) } private fun needCreateAllocations(image: Image, yuvBuffer: YuvByteBuffer): Boolean { return (inputAllocation == null || // the very 1st call inputAllocation!!.type.x != image.width || // image size changed inputAllocation!!.type.y != image.height || inputAllocation!!.type.yuv != yuvBuffer.type || // image format changed bytes.size == yuvBuffer.buffer.capacity()) } }
OKCameraXVideo/utils/src/main/java/com/example/android/camera/utils/YuvToRgbConverter.kt
4264940611
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.camera.utils import android.content.Context import android.hardware.camera2.CameraCharacteristics import android.view.OrientationEventListener import android.view.Surface import androidx.lifecycle.LiveData /** * Calculates closest 90-degree orientation to compensate for the device * rotation relative to sensor orientation, i.e., allows user to see camera * frames with the expected orientation. */ class OrientationLiveData( context: Context, characteristics: CameraCharacteristics ): LiveData<Int>() { private val listener = object : OrientationEventListener(context.applicationContext) { override fun onOrientationChanged(orientation: Int) { val rotation = when { orientation <= 45 -> Surface.ROTATION_0 orientation <= 135 -> Surface.ROTATION_90 orientation <= 225 -> Surface.ROTATION_180 orientation <= 315 -> Surface.ROTATION_270 else -> Surface.ROTATION_0 } val relative = computeRelativeRotation(characteristics, rotation) if (relative != value) postValue(relative) } } override fun onActive() { super.onActive() listener.enable() } override fun onInactive() { super.onInactive() listener.disable() } companion object { /** * Computes rotation required to transform from the camera sensor orientation to the * device's current orientation in degrees. * * @param characteristics the [CameraCharacteristics] to query for the sensor orientation. * @param surfaceRotation the current device orientation as a Surface constant * @return the relative rotation from the camera sensor to the current device orientation. */ @JvmStatic private fun computeRelativeRotation( characteristics: CameraCharacteristics, surfaceRotation: Int ): Int { val sensorOrientationDegrees = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION)!! val deviceOrientationDegrees = when (surfaceRotation) { Surface.ROTATION_0 -> 0 Surface.ROTATION_90 -> 90 Surface.ROTATION_180 -> 180 Surface.ROTATION_270 -> 270 else -> 0 } // Reverse device orientation for front-facing cameras val sign = if (characteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT) 1 else -1 // Calculate desired JPEG orientation relative to camera orientation to make // the image upright relative to the device orientation return (sensorOrientationDegrees - (deviceOrientationDegrees * sign) + 360) % 360 } } }
OKCameraXVideo/utils/src/main/java/com/example/android/camera/utils/OrientationLiveData.kt
2570073423
package com.example.android.camera.utils import android.graphics.ImageFormat import android.media.Image import androidx.annotation.IntDef import java.nio.ByteBuffer /* This file is converted from part of https://github.com/gordinmitya/yuv2buf. Follow the link to find demo app, performance benchmarks and unit tests. Intro to YUV image formats: YUV_420_888 - is a generic format that can be represented as I420, YV12, NV21, and NV12. 420 means that for each 4 luminosity pixels we have 2 chroma pixels: U and V. * I420 format represents an image as Y plane followed by U then followed by V plane without chroma channels interleaving. For example: Y Y Y Y Y Y Y Y U U V V * NV21 format represents an image as Y plane followed by V and U interleaved. First V then U. For example: Y Y Y Y Y Y Y Y V U V U * YV12 and NV12 are the same as previous formats but with swapped order of V and U. (U then V) Visualization of these 4 formats: https://user-images.githubusercontent.com/9286092/89119601-4f6f8100-d4b8-11ea-9a51-2765f7e513c2.jpg It's guaranteed that image.getPlanes() always returns planes in order Y U V for YUV_420_888. https://developer.android.com/reference/android/graphics/ImageFormat#YUV_420_888 Because I420 and NV21 are more widely supported (RenderScript, OpenCV, MNN) the conversion is done into these formats. More about each format: https://www.fourcc.org/yuv.php */ @kotlin.annotation.Retention(AnnotationRetention.SOURCE) @IntDef(ImageFormat.NV21, ImageFormat.YUV_420_888) annotation class YuvType class YuvByteBuffer(image: Image, dstBuffer: ByteBuffer? = null) { @YuvType val type: Int val buffer: ByteBuffer init { val wrappedImage = ImageWrapper(image) type = if (wrappedImage.u.pixelStride == 1) { ImageFormat.YUV_420_888 } else { ImageFormat.NV21 } val size = image.width * image.height * 3 / 2 buffer = if ( dstBuffer == null || dstBuffer.capacity() < size || dstBuffer.isReadOnly || !dstBuffer.isDirect ) { ByteBuffer.allocateDirect(size) } else { dstBuffer } buffer.rewind() removePadding(wrappedImage) } // Input buffers are always direct as described in // https://developer.android.com/reference/android/media/Image.Plane#getBuffer() private fun removePadding(image: ImageWrapper) { val sizeLuma = image.y.width * image.y.height val sizeChroma = image.u.width * image.u.height if (image.y.rowStride > image.y.width) { removePaddingCompact(image.y, buffer, 0) } else { buffer.position(0) buffer.put(image.y.buffer) } if (type == ImageFormat.YUV_420_888) { if (image.u.rowStride > image.u.width) { removePaddingCompact(image.u, buffer, sizeLuma) removePaddingCompact(image.v, buffer, sizeLuma + sizeChroma) } else { buffer.position(sizeLuma) buffer.put(image.u.buffer) buffer.position(sizeLuma + sizeChroma) buffer.put(image.v.buffer) } } else { if (image.u.rowStride > image.u.width * 2) { removePaddingNotCompact(image, buffer, sizeLuma) } else { buffer.position(sizeLuma) var uv = image.v.buffer val properUVSize = image.v.height * image.v.rowStride - 1 if (uv.capacity() > properUVSize) { uv = clipBuffer(image.v.buffer, 0, properUVSize) } buffer.put(uv) val lastOne = image.u.buffer[image.u.buffer.capacity() - 1] buffer.put(buffer.capacity() - 1, lastOne) } } buffer.rewind() } private fun removePaddingCompact( plane: PlaneWrapper, dst: ByteBuffer, offset: Int ) { require(plane.pixelStride == 1) { "use removePaddingCompact with pixelStride == 1" } val src = plane.buffer val rowStride = plane.rowStride var row: ByteBuffer dst.position(offset) for (i in 0 until plane.height) { row = clipBuffer(src, i * rowStride, plane.width) dst.put(row) } } private fun removePaddingNotCompact( image: ImageWrapper, dst: ByteBuffer, offset: Int ) { require(image.u.pixelStride == 2) { "use removePaddingNotCompact pixelStride == 2" } val width = image.u.width val height = image.u.height val rowStride = image.u.rowStride var row: ByteBuffer dst.position(offset) for (i in 0 until height - 1) { row = clipBuffer(image.v.buffer, i * rowStride, width * 2) dst.put(row) } row = clipBuffer(image.u.buffer, (height - 1) * rowStride - 1, width * 2) dst.put(row) } private fun clipBuffer(buffer: ByteBuffer, start: Int, size: Int): ByteBuffer { val duplicate = buffer.duplicate() duplicate.position(start) duplicate.limit(start + size) return duplicate.slice() } private class ImageWrapper(image:Image) { val width= image.width val height = image.height val y = PlaneWrapper(width, height, image.planes[0]) val u = PlaneWrapper(width / 2, height / 2, image.planes[1]) val v = PlaneWrapper(width / 2, height / 2, image.planes[2]) // Check this is a supported image format // https://developer.android.com/reference/android/graphics/ImageFormat#YUV_420_888 init { require(y.pixelStride == 1) { "Pixel stride for Y plane must be 1 but got ${y.pixelStride} instead." } require(u.pixelStride == v.pixelStride && u.rowStride == v.rowStride) { "U and V planes must have the same pixel and row strides " + "but got pixel=${u.pixelStride} row=${u.rowStride} for U " + "and pixel=${v.pixelStride} and row=${v.rowStride} for V" } require(u.pixelStride == 1 || u.pixelStride == 2) { "Supported" + " pixel strides for U and V planes are 1 and 2" } } } private class PlaneWrapper(width: Int, height: Int, plane: Image.Plane) { val width = width val height = height val buffer: ByteBuffer = plane.buffer val rowStride = plane.rowStride val pixelStride = plane.pixelStride } }
OKCameraXVideo/utils/src/main/java/com/example/android/camera/utils/Yuv.kt
1219240727
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.camera.utils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView /** Type helper used for the callback triggered once our view has been bound */ typealias BindCallback<T> = (view: View, data: T, position: Int) -> Unit /** List adapter for generic types, intended used for small-medium lists of data */ class GenericListAdapter<T>( private val dataset: List<T>, private val itemLayoutId: Int? = null, private val itemViewFactory: (() -> View)? = null, private val onBind: BindCallback<T> ) : RecyclerView.Adapter<GenericListAdapter.GenericListViewHolder>() { class GenericListViewHolder(val view: View) : RecyclerView.ViewHolder(view) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = GenericListViewHolder(when { itemViewFactory != null -> itemViewFactory.invoke() itemLayoutId != null -> { LayoutInflater.from(parent.context) .inflate(itemLayoutId, parent, false) } else -> { throw IllegalStateException( "Either the layout ID or the view factory need to be non-null") } }) override fun onBindViewHolder(holder: GenericListViewHolder, position: Int) { if (position < 0 || position > dataset.size) return onBind(holder.view, dataset[position], position) } override fun getItemCount() = dataset.size }
OKCameraXVideo/utils/src/main/java/com/example/android/camera/utils/GenericListAdapter.kt
559361102
fun main(args: Array<String>) { println("Digite um numero: ") val x: Int? = readLine()?.toInt() for (i in 1..x!!){ println(i) } }
TEpraticaKotlin/ex5.kt
1807275471
fun ex1() = println("Olá, mundo!") fun main(args: Array<String>) { var max = 99 var cont = 0 do { ex1() cont++ } while (cont < max) }
TEpraticaKotlin/ex1.kt
615168437
fun main(args: Array<String>) { for (i in 1..9){ println("O numero atual é $i") } }
TEpraticaKotlin/ex4.kt
2627399699
data class Pessoa (val nome : String, val idade : Int, val cidade : String) fun main(args: Array<String>) { val pessoa = Pessoa("Andrew", 18, "Farroupilha") println("${pessoa.nome} da cidade de ${pessoa.cidade} tem a idade ${pessoa.idade}") }
TEpraticaKotlin/ex9.kt
903100326
data class Aluno (val nome : String, val pontuacao : Long) fun main(args: Array<String>) { val aluno = Aluno("Andrew", 80) when { aluno.pontuacao <= 59 -> print("f") aluno.pontuacao <= 69 -> print("d") aluno.pontuacao <= 79 -> print("c") aluno.pontuacao <= 89 -> print("b") aluno.pontuacao <= 100 -> print("a") } }
TEpraticaKotlin/ex8.kt
1550276214
fun main(args: Array<String>) { val list = 1..10 for (i in list){ print(i) } }
TEpraticaKotlin/ex3.kt
2500130505
fun main(args: Array<String>) { println("Digite um numero: ") val x: Int? = readLine()?.toInt() if (x!! % 2 == 0) { println("O numero é par") } else { println("O numero é impar") } }
TEpraticaKotlin/ex7.kt
590565002
fun main(args: Array<String>) { testaPrimo(18) testaPrimo(17) } fun testaPrimo(numero :Int){ for (i in 2 until numero) { if (numero % i == 0) { println("o numero $numero não é primo") return } } println("o numero $numero é primo") }
TEpraticaKotlin/ex6.kt
1160774836
fun main(args: Array<String>) { val nome = "Jonatan" val idade = 18 val estudante = false println("A pessoa $nome, de idade $idade, está declarado como $estudante no quesito de ser estudante") }
TEpraticaKotlin/ex2.kt
2384745789
import androidx.compose.runtime.Composable import app.kotleni.pomodoro.ui.main.MainScreen import app.kotleni.pomodoro.ui.theme.AppTheme import cafe.adriel.voyager.navigator.Navigator import org.jetbrains.compose.resources.ExperimentalResourceApi @OptIn(ExperimentalResourceApi::class) @Composable fun App() { AppTheme { Navigator(MainScreen()) } } enum class PlatformType { DESKTOP, ANDROID, IOS } expect fun getPatformType(): PlatformType
PomodoroTracker-MP/shared/src/commonMain/kotlin/App.kt
350368454
import app.kotleni.pomodoro.CoroutineTimer import app.kotleni.pomodoro.Timer import app.kotleni.pomodoro.TimerListener import app.kotleni.pomodoro.TimerService import app.kotleni.pomodoro.TimerStage import app.kotleni.pomodoro.TimerState import org.koin.core.component.KoinComponent class TimerServiceImpl : TimerService, KoinComponent { private var coroutineTimer: CoroutineTimer = CoroutineTimer() private var listener: TimerListener? = null private var state = TimerState.STOPPED private var stage = TimerStage.WORK private var currentSeconds = 0 private var timer: Timer? = null init { coroutineTimer.scheduled(0, 1_000) { onTimerTick() } coroutineTimer.run() } private fun onTimerTick() { if(state == TimerState.STARTED && currentSeconds > 0) { currentSeconds -= 1 // val timeName = if(stage == TimerStage.WORK) "Work time" else "Break time" //notificationsHelper?.showPermanentNotification(timeName, "Time left ${currentSeconds.toTimeString()}") notifyTimeChanged() if(currentSeconds == 0) { stop() // notificationsHelper?.closePermanentNotification() // notificationsHelper?.showAlarmNotification("$timeName is ended", "Press here to open app") } } } private fun notifyStateChanged() { timer?.let { listener?.onStateUpdated(it, state) } } private fun notifyStageChanged() { timer?.let { listener?.onStageUpdated(it, stage) } } private fun notifyTimeChanged() { timer?.let { listener?.onTimeUpdated(it, currentSeconds) } } private fun resetTime() { val currentStartTime = (if(stage == TimerStage.WORK) timer?.workTime else timer?.shortBreakTime) ?: 0 currentSeconds = currentStartTime.toInt() notifyTimeChanged() } override fun stop() { state = TimerState.STOPPED notifyStateChanged() // notificationsHelper?.closePermanentNotification() } override fun start() { resetTime() state = TimerState.STARTED notifyStateChanged() } override fun pause() { state = TimerState.PAUSED notifyStateChanged() // notificationsHelper?.closePermanentNotification() } override fun resume() { state = TimerState.STARTED notifyStateChanged() } override fun setTimer(timer: Timer?) { this.timer = timer if(timer != null) { // Notify all updated data notifyStageChanged() notifyStateChanged() resetTime() } } override fun setStage(stage: TimerStage) { if(state != TimerState.STOPPED) stop() this.stage = stage resetTime() notifyStageChanged() } override fun setListener(listener: TimerListener?) { this.listener = listener } override fun getTimer(): Timer? { return timer } }
PomodoroTracker-MP/shared/src/commonMain/kotlin/TimerServiceImpl.kt
2430624230
package app.kotleni.pomodoro.ui.timer import PlatformType import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.Canvas 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.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.SuggestionChip import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState 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.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.TextUnitType import androidx.compose.ui.unit.dp import app.kotleni.pomodoro.TimerStage import app.kotleni.pomodoro.TimerState import app.kotleni.pomodoro.stateMachine import app.kotleni.pomodoro.toTimeString import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.currentOrThrow import getPatformType class TimerScreen(val timerId: Int) : Screen { @OptIn(ExperimentalMaterial3Api::class) @Composable override fun Content() { val navigator = LocalNavigator.currentOrThrow val viewModel = stateMachine<TimerViewModel>() val uiState by viewModel.uiState.collectAsState() var isShowWarningDialog by remember { mutableStateOf(false) } val currentStartTime = (if(uiState.timerStage == TimerStage.WORK) uiState.timer?.workTime else uiState.timer?.shortBreakTime) ?: 1 val animatedPercentage by animateFloatAsState( targetValue = (uiState.currentSeconds.toFloat() / currentStartTime.toFloat()) * 100f, animationSpec = tween(), label = "animatedPercentage" ) val timeName = if(uiState.timerStage == TimerStage.WORK) "Work time" else "Break time" if(isShowWarningDialog) { TimerExitWarningDialog( onPositive = { viewModel.resetServiceIsNotStarted() navigator.pop() //rootNavController.popBackStack() }, onNegative = { isShowWarningDialog = false } ) } Scaffold( topBar = { TopAppBar( title = { Text(text = uiState.timer?.name ?: "Timer") }, navigationIcon = { IconButton(onClick = { if(uiState.timerState == TimerState.PAUSED) { isShowWarningDialog = true } else { viewModel.resetServiceIsNotStarted() navigator.pop() //rootNavController.popBackStack() } }) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = "" ) } } ) } ) { paddingValues -> Column( modifier = Modifier .fillMaxSize() .padding(paddingValues), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { val lineColorBg = MaterialTheme.colorScheme.onSecondary val lineColorFg = MaterialTheme.colorScheme.secondary Box(modifier = Modifier, contentAlignment = Alignment.Center) { Canvas( modifier = Modifier .fillMaxWidth() .height(300.dp) ) { val canvasSize = size.minDimension val radius = canvasSize / 2.5f val centerX = size.width / 2 val centerY = size.height / 2 val strokeWidth = if(getPatformType() == PlatformType.DESKTOP) 8f else 18f // Calculate the start and sweep angles val startAngle = 0f val sweepAngle = (360f / 100f) * animatedPercentage //180f * (percentage / 100f) drawArc( color = lineColorBg, startAngle = 0f, sweepAngle = 360f, useCenter = false, topLeft = Offset(centerX - radius, centerY - radius), size = Size(radius * 2, radius * 2), style = Stroke(strokeWidth) // Adjust the stroke width as needed ) drawArc( color = lineColorFg, startAngle = startAngle, sweepAngle = sweepAngle, useCenter = false, topLeft = Offset(centerX - radius, centerY - radius), size = Size(radius * 2, radius * 2), style = Stroke(strokeWidth) // Adjust the stroke width as needed ) } Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = uiState.currentSeconds.toTimeString(), fontWeight = FontWeight.Bold, fontSize = TextUnit(36f, TextUnitType.Sp) ) Text( text = timeName, fontSize = TextUnit(24f, TextUnitType.Sp) ) } } Row { when(uiState.timerState) { TimerState.STOPPED -> { Button(modifier = Modifier.padding(8.dp), onClick = { viewModel.start() }) { Text(text = "Start") } } TimerState.PAUSED -> { Button(modifier = Modifier.padding(8.dp), onClick = { viewModel.resume() }) { Text(text = "Resume") } } TimerState.STARTED -> { Button(modifier = Modifier.padding(8.dp), onClick = { viewModel.pause() }) { Text(text = "Pause") } } } Button(modifier = Modifier.padding(8.dp), onClick = { viewModel.nextTimerStage() }) { Text(text = "Skip") } } Spacer(modifier = Modifier.height(8.dp)) if(uiState.timer != null) { Column { SuggestionChip(onClick = { }, label = { Text(text = "Total work time: ${uiState.timer!!.totalWorkTime / 60} min") }) SuggestionChip(onClick = { }, label = { Text(text = "Total break time: ${uiState.timer!!.totalBreakTime / 60} min") }) } } } } LaunchedEffect(key1 = timerId) { viewModel.loadTimer(timerId.toLong()) } } }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/ui/timer/TimerScreen.kt
3463691319
package app.kotleni.pomodoro.ui.timer import androidx.compose.material3.AlertDialog import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable @OptIn(ExperimentalMaterial3Api::class) @Composable fun TimerExitWarningDialog(onPositive: () -> Unit, onNegative: () -> Unit) { AlertDialog( title = { Text(text = "Paused timer") }, text = { Text(text = "Do you want stop timer?") }, onDismissRequest = { onNegative() }, confirmButton = { TextButton( onClick = { onPositive() } ) { Text("Confirm") } }, dismissButton = { TextButton( onClick = { onNegative() } ) { Text("Dismiss") } } ) }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/ui/timer/TimerExitWarningDialog.kt
2112197789
package app.kotleni.pomodoro.ui.timer import TimerServiceImpl import app.kotleni.pomodoro.Timer import app.kotleni.pomodoro.TimerListener import app.kotleni.pomodoro.TimerService import app.kotleni.pomodoro.TimerStage import app.kotleni.pomodoro.TimerState import app.kotleni.pomodoro.ViewModel import app.kotleni.pomodoro.usecases.LoadTimerByIdUseCase import app.kotleni.pomodoro.usecases.UpdateTimerUseCase import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.koin.core.component.KoinComponent data class TimerUIState( val timer: Timer? = null, val timerStage: TimerStage = TimerStage.WORK, val timerState: TimerState = TimerState.STOPPED, val currentSeconds: Int = 0 ) class TimerViewModel( private val loadTimerByIdUseCase: LoadTimerByIdUseCase, private val updateTimerUseCase: UpdateTimerUseCase ) : ViewModel(), KoinComponent, TimerListener { private val _uiState: MutableStateFlow<TimerUIState> = MutableStateFlow(TimerUIState()) val uiState: StateFlow<TimerUIState> = _uiState private var service: TimerService = TimerServiceImpl() override fun onTimeUpdated(timer: Timer, secs: Int) { _uiState.update { it.copy(currentSeconds = secs) } } override fun onStateUpdated(timer: Timer, state: TimerState) { _uiState.update { it.copy(timerState = state) } when(state) { TimerState.STOPPED -> { val timerStage = uiState.value.timerStage val currentStartTime = (if(timerStage == TimerStage.WORK) timer.workTime else timer.shortBreakTime) adjustTimerStats(timerStage, currentStartTime.toInt()) nextTimerStage() } TimerState.PAUSED -> {} TimerState.STARTED -> {} } } override fun onStageUpdated(timer: Timer, stage: TimerStage) { _uiState.update { it.copy(timerStage = stage) } } fun resetServiceIsNotStarted() { if(uiState.value.timerState != TimerState.STARTED) { // Remove listener first, because events not needed service.setListener(null) service.stop() service.setTimer(null) } } private fun bindToService() { service.setListener(this) service.setTimer(uiState.value.timer) } fun loadTimer(timerId: Long) = viewModelScope.launch { loadTimerByIdUseCase(timerId) { newTimer -> _uiState.update { it.copy(timer = newTimer) } bindToService() } } fun nextTimerStage() { val timerStage = uiState.value.timerStage service.setStage(if(timerStage == TimerStage.WORK) TimerStage.BREAK else TimerStage.WORK) } private fun adjustTimerStats(stage: TimerStage, seconds: Int) = viewModelScope.launch { val currentTimer = uiState.value.timer if (currentTimer != null) { val updatedTimer = when (stage) { TimerStage.WORK -> currentTimer.copy(totalWorkTime = currentTimer.totalWorkTime + seconds) TimerStage.BREAK -> currentTimer.copy(totalBreakTime = currentTimer.totalBreakTime + seconds) } _uiState.update { it.copy(timer = updatedTimer) } updateTimerUseCase(updatedTimer) } } fun start() = service.start() fun resume() = service.resume() fun pause() = service.pause() }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/ui/timer/TimerViewModel.kt
364375531
package app.kotleni.pomodoro.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable 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) 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 AppTheme( 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 ) }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/ui/theme/AppTheme.kt
1266120319
package app.kotleni.pomodoro.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 ) */ )
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/ui/theme/Typography.kt
2483282842
package app.kotleni.pomodoro.ui.main import TimerServiceImpl import app.kotleni.pomodoro.Timer import app.kotleni.pomodoro.TimerService import app.kotleni.pomodoro.ViewModel import app.kotleni.pomodoro.usecases.CreateTimerUseCase import app.kotleni.pomodoro.usecases.FetchTimersUseCase import app.kotleni.pomodoro.usecases.RemoveTimerUseCase import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.koin.core.component.KoinComponent data class MainUIState( val timers: List<Timer> = listOf(), val activeTimer: Timer? = null ) class MainViewModel( private val createTimerUseCase: CreateTimerUseCase, private val removeTimerUseCase: RemoveTimerUseCase, private val fetchTimersUseCase: FetchTimersUseCase ) : ViewModel(), KoinComponent { private val _uiState: MutableStateFlow<MainUIState> = MutableStateFlow(MainUIState()) val uiState: StateFlow<MainUIState> = _uiState private var service: TimerService = TimerServiceImpl() fun loadTimers() = viewModelScope.launch { fetchTimersUseCase { newTimers -> _uiState.update { it.copy(timers = newTimers) } } } fun bindToService() { loadActiveTimer() } fun loadActiveTimer() { _uiState.update { it.copy(activeTimer = service.getTimer()) } } fun createTimer(name: String, iconId: Int, workTime: Int, sbrakeTime: Int, lbrakeTime: Int) = viewModelScope.launch { createTimerUseCase( name, iconId, workTime, sbrakeTime, lbrakeTime, ::loadTimers ) } fun removeTimer(timer: Timer) = viewModelScope.launch { removeTimerUseCase( timer, ::loadTimers ) } }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/ui/main/MainViewModel.kt
1103261111
package app.kotleni.pomodoro.ui.main import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Delete import androidx.compose.material3.DismissDirection import androidx.compose.material3.DismissValue import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.SwipeToDismiss import androidx.compose.material3.Text import androidx.compose.material3.rememberDismissState import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import app.kotleni.pomodoro.Timer import app.kotleni.pomodoro.defaultTimerIcons @OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class) @Composable fun TimerItem(timer: Timer, isActive: Boolean, onItemSelected: () -> Unit, onItemRemoved: () -> Unit) { val dismissState = rememberDismissState( initialValue = DismissValue.Default, confirmValueChange = { if (it == DismissValue.DismissedToStart && !isActive) { onItemRemoved() } false } ) SwipeToDismiss( state = dismissState, background = { val color = when (dismissState.dismissDirection) { DismissDirection.EndToStart -> MaterialTheme.colorScheme.error else -> Color.Transparent } Box( modifier = Modifier .fillMaxSize() .background(color) .padding(8.dp) ) { Column(modifier = Modifier.align(Alignment.CenterEnd)) { Icon( imageVector = Icons.Default.Delete, contentDescription = null, tint = Color.White, modifier = Modifier.align(Alignment.CenterHorizontally) ) } } }, directions = setOf(DismissDirection.EndToStart), dismissContent = { Box( modifier = Modifier .fillMaxWidth() .background(MaterialTheme.colorScheme.background) .clip(RectangleShape) ) { Row( modifier = Modifier .clickable { onItemSelected() } .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Box( modifier = Modifier.padding(start = 16.dp, top = 0.dp, bottom = 0.dp, end = 8.dp) ) { Image( modifier = Modifier .clip(RoundedCornerShape(8.dp)) .background(MaterialTheme.colorScheme.primaryContainer) .padding(8.dp), imageVector = defaultTimerIcons[timer.iconId.toInt()], contentDescription = "", colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.onPrimaryContainer) ) } Column( modifier = Modifier.padding(8.dp) ) { Row { Text(modifier = Modifier.padding(0.dp), text = timer.name, fontWeight = FontWeight.Bold) if(isActive) Text(modifier = Modifier.padding(start = 8.dp), text = "Active", color = MaterialTheme.colorScheme.primary) } Text(modifier = Modifier.padding(0.dp), text = "Work ${timer.workTime / 60} min and brake ${timer.shortBreakTime / 60} min") } } } } ) }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/ui/main/TimerItem.kt
3869725229
package app.kotleni.pomodoro.ui.main 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.text.KeyboardOptions import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf 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.text.input.KeyboardType import androidx.compose.ui.unit.dp import app.kotleni.pomodoro.defaultTimerIcons import app.kotleni.pomodoro.isDigitsOnly @OptIn(ExperimentalMaterial3Api::class) @Composable fun CreateTimerDialog(onCreate: (name: String, iconId: Int, workTime: Int, sbrakeTime: Int, lbrakeTime: Int) -> Unit, onDismiss: () -> Unit) { var name: String by remember { mutableStateOf("") } var iconId: Int by remember { mutableIntStateOf(0) } var workTime: String by remember { mutableStateOf("30") } var sbrakeTime: String by remember { mutableStateOf("5") } var lbrakeTime: String by remember { mutableStateOf("15") } PlatformSpecificModal( onDismissRequest = onDismiss ) { //TopAppBar(title = { Text(text = "New timer") }) Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { OutlinedTextField( modifier = Modifier .padding(start = 16.dp, top = 8.dp, bottom = 8.dp, end = 16.dp) .fillMaxWidth(), value = name, label = { Text(text = "Name") }, onValueChange = { name = it } ) Row( modifier = Modifier.padding(start = 8.dp, top = 0.dp, bottom = 0.dp, end = 8.dp) ) { OutlinedTextField( modifier = Modifier .padding(8.dp) .fillMaxWidth() .weight(1f), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal), value = workTime, label = { Text(text = "Work time") }, suffix = { Text(text = " min") }, onValueChange = { workTime = it } ) OutlinedTextField( modifier = Modifier .padding(8.dp) .fillMaxWidth() .weight(1f), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal), value = sbrakeTime, label = { Text(text = "Break time") }, suffix = { Text(text = " min") }, onValueChange = { sbrakeTime = it } ) } IconSelector( defaultTimerIcons, onSelected = { index, _ -> iconId = index } ) Row( modifier = Modifier.padding(start = 8.dp, top = 0.dp, bottom = 0.dp, end = 8.dp) ) { OutlinedButton(modifier = Modifier .padding(8.dp) .fillMaxWidth() .weight(1f), onClick = onDismiss) { Text(text = "Cancel") } Button(modifier = Modifier .padding(8.dp) .fillMaxWidth() .weight(1f), onClick = { if(workTime.isDigitsOnly() && sbrakeTime.isDigitsOnly() && lbrakeTime.isDigitsOnly()) { onCreate(name, iconId, workTime.toInt(), sbrakeTime.toInt(), lbrakeTime.toInt()) } }) { Text(text = "Create") } } } } }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/ui/main/CreateTimerDialog.kt
3851511999
package app.kotleni.pomodoro.ui.main import androidx.compose.foundation.background import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AlertDialog import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.SheetState import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.unit.dp import getPatformType @OptIn(ExperimentalMaterial3Api::class) @Composable fun PlatformSpecificModal( modifier: Modifier = Modifier, onDismissRequest: () -> Unit, content: @Composable () -> Unit ) { if(getPatformType() == PlatformType.DESKTOP) { AlertDialog( modifier = modifier .clip(RoundedCornerShape(28.dp)) .background(MaterialTheme.colorScheme.background) .padding(16.dp), onDismissRequest = onDismissRequest, content = content ) } else { ModalBottomSheet( sheetState = SheetState(skipPartiallyExpanded = true), onDismissRequest = onDismissRequest, content = { content() } ) } }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/ui/main/PlatformSpecificModal.kt
3297048763
package app.kotleni.pomodoro.ui.main import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.dp @Composable fun IconSelectorItem(icon: ImageVector, isSelected: Boolean, onSelected: () -> Unit) { Box( modifier = Modifier .padding(8.dp) ) { Box( modifier = Modifier .clip(RoundedCornerShape(8.dp)) .background(if (!isSelected) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.primary) .clickable { onSelected() } ) { Image( modifier = Modifier .padding(16.dp), imageVector = icon, contentDescription = "", colorFilter = ColorFilter.tint(if (!isSelected) MaterialTheme.colorScheme.onPrimaryContainer else MaterialTheme.colorScheme.onPrimary) ) } } }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/ui/main/IconSelectorItem.kt
310029215
package app.kotleni.pomodoro.ui.main import PlatformType import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.unit.dp import getPatformType @Composable fun IconSelector(icons: List<ImageVector>, onSelected: (index: Int, icon: ImageVector) -> Unit) { var selectedIndex by remember { mutableIntStateOf(0) } if(getPatformType() == PlatformType.DESKTOP) { LazyVerticalGrid( columns = GridCells.Fixed(5), modifier = Modifier .fillMaxWidth() .padding(8.dp) ) { items(icons.size) { index -> IconSelectorItem(icons[index], selectedIndex == index, onSelected = { selectedIndex = index onSelected(index, icons[index]) }) } } } else { LazyRow ( modifier = Modifier .fillMaxWidth() .padding(start = 0.dp, top = 8.dp, bottom = 8.dp, end = 0.dp) ) { item { Spacer(modifier = Modifier.width(8.dp)) } items(icons.size) { index -> IconSelectorItem(icons[index], selectedIndex == index, onSelected = { selectedIndex = index onSelected(index, icons[index]) }) } item { Spacer(modifier = Modifier.width(8.dp)) } } } }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/ui/main/IconSelector.kt
3839328524
package app.kotleni.pomodoro.ui.main import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.FloatingActionButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.LargeTopAppBar import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.SideEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import app.kotleni.pomodoro.stateMachine import app.kotleni.pomodoro.ui.timer.TimerScreen import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.currentOrThrow class MainScreen : Screen { @OptIn(ExperimentalMaterial3Api::class) @Composable override fun Content() { val navigator = LocalNavigator.currentOrThrow val viewModel = stateMachine<MainViewModel>() val uiState by viewModel.uiState.collectAsState() var isShowCreateDialog by remember { mutableStateOf(false) } val lazyListState = rememberLazyListState() Scaffold( modifier = Modifier, topBar = { LargeTopAppBar(title = { Text(text = "Timers") } ) }, floatingActionButton = { FloatingActionButton(onClick = { isShowCreateDialog = true }, elevation = FloatingActionButtonDefaults.elevation(0.dp, 0.dp, 0.dp, 0.dp)) { Icon(imageVector = Icons.Default.Add, contentDescription = "") } }, ) { paddingValues -> Column( modifier = Modifier .fillMaxSize() .padding(paddingValues) ) { /// IndexOfBoundsException LazyColumn( state = lazyListState, ) { items(uiState.timers, key = { it.id }) { TimerItem( timer = it, isActive = it.id == uiState.activeTimer?.id, onItemSelected = { navigator.push(TimerScreen(it.id.toInt())) }, onItemRemoved = { viewModel.removeTimer(it) } ) } } if(isShowCreateDialog) { CreateTimerDialog( onCreate = { name, iconId, workTime, sbrakeTime, lbrakeTime -> if(name.isNotEmpty() && workTime > 0 && sbrakeTime > 0 && lbrakeTime > 0) { viewModel.createTimer(name, iconId, workTime, sbrakeTime, lbrakeTime) isShowCreateDialog = false } }, onDismiss = { isShowCreateDialog = false } ) } } } SideEffect { viewModel.loadActiveTimer() } LaunchedEffect(key1 = "main") { viewModel.bindToService() viewModel.loadTimers() } } }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/ui/main/MainScreen.kt
4256604671
package app.kotleni.pomodoro.di import app.kotleni.pomodoro.repositories.TimersRepository import app.kotleni.pomodoro.repositories.TimersRepositoryImpl import app.kotleni.pomodoro.ui.main.MainViewModel import app.kotleni.pomodoro.ui.timer.TimerViewModel import app.kotleni.pomodoro.usecases.* import org.koin.core.module.Module import org.koin.core.module.dsl.singleOf import org.koin.dsl.bind import org.koin.dsl.module val commonModule: Module = module { singleOf(::MainViewModel) singleOf(::TimerViewModel) singleOf(::TimersRepositoryImpl) bind TimersRepository::class singleOf(::CreateTimerUseCase) singleOf(::RemoveTimerUseCase) singleOf(::FetchTimersUseCase) singleOf(::LoadTimerByIdUseCase) singleOf(::UpdateTimerUseCase) }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/di/sharedModule.kt
3216336550
package app.kotleni.pomodoro.di import org.koin.core.context.startKoin import org.koin.core.module.Module val koinModules = listOf(commonModule, platformModule()) expect fun platformModule(): Module //fun initKoin() { // startKoin { // modules(modules) // } //}
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/di/koin.kt
1437372145
package app.kotleni.pomodoro interface TimerListener { fun onTimeUpdated(timer: Timer, secs: Int) fun onStateUpdated(timer: Timer, state: TimerState) fun onStageUpdated(timer: Timer, stage: TimerStage) }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/TimerListener.kt
594384384
package app.kotleni.pomodoro import kotlinx.coroutines.CoroutineScope expect open class ViewModel() { val viewModelScope: CoroutineScope }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/ViewModel.kt
1210546730
package app.kotleni.pomodoro import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Build import androidx.compose.material.icons.filled.DateRange import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.Home import androidx.compose.material.icons.filled.LocationOn import androidx.compose.material.icons.filled.ShoppingCart import androidx.compose.material.icons.filled.Star val defaultTimerIcons = listOf( Icons.Default.Favorite, Icons.Default.Star, Icons.Default.Build, Icons.Default.LocationOn, Icons.Default.Home, Icons.Default.ShoppingCart, Icons.Default.DateRange, ) fun Int.toTimeString(): String { val minutes = this / 60 val seconds = this % 60 return "$minutes:${if(seconds.toString().length > 1) seconds else "0$seconds"}" } fun String.isDigitsOnly(): Boolean { return this.matches(Regex("\\d+")) }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/utils.kt
2125423189
package app.kotleni.pomodoro import app.cash.sqldelight.db.SqlDriver expect class DatabaseDriverFactory { fun createDriver(): SqlDriver }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/DatabaseDriverFactory.kt
2013719029
package app.kotleni.pomodoro import androidx.compose.runtime.Composable import org.koin.core.parameter.ParametersDefinition /** * Creates and returns an instance of the specified state machine using the provided factory. * * @param TSM The reified type of the state machine. * @param TState The type of the state in the state machine. * @param TEvent The type of the events in the state machine. * @param TEffect The type of the effects in the state machine. * @return The created instance of the state machine. */ @Composable expect inline fun <reified TSM : ViewModel> stateMachine( noinline parameters: ParametersDefinition? = null, ): TSM
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/stateMachine.kt
4187225654
package app.kotleni.pomodoro.repositories import app.kotleni.pomodoro.Database import app.kotleni.pomodoro.DatabaseDriverFactory import app.kotleni.pomodoro.Timer import org.koin.core.component.KoinComponent interface TimersRepository { suspend fun fetchTimers(): List<Timer> suspend fun addTimer(timer: Timer) suspend fun updateTimer(timer: Timer) suspend fun removeTimer(timer: Timer) } class TimersRepositoryImpl(databaseDriverFactory: DatabaseDriverFactory) : KoinComponent, TimersRepository { private val database = Database(databaseDriverFactory.createDriver()) private val dbQuery = database.timerQueries override suspend fun fetchTimers(): List<Timer> { return dbQuery.selectAllTimers().executeAsList() } override suspend fun addTimer(timer: Timer) { dbQuery.insertTimer( name = timer.name, iconId = timer.iconId, totalWorkTime = timer.totalWorkTime, totalBreakTime = timer.totalBreakTime, shortBreakTime = timer.shortBreakTime, longBreakTime = timer.longBreakTime, workTime = timer.workTime ) } override suspend fun updateTimer(timer: Timer) { dbQuery.updateTimer( name = timer.name, iconId = timer.iconId, totalWorkTime = timer.totalWorkTime, totalBreakTime = timer.totalBreakTime, shortBreakTime = timer.shortBreakTime, longBreakTime = timer.longBreakTime, workTime = timer.workTime, id = timer.id ) } override suspend fun removeTimer(timer: Timer) { dbQuery.deleteTimer(timer.id) } }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/repositories/TimersRepository.kt
3518981492
package app.kotleni.pomodoro enum class TimerState { STOPPED, PAUSED, STARTED }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/TimerState.kt
782417978
package app.kotleni.pomodoro enum class TimerStage { WORK, BREAK }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/TimerStage.kt
4183376130
package app.kotleni.pomodoro import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch /*** * Multiplatform implementation of interval timer */ class CoroutineTimer { private val coroutineContext = CoroutineScope(Dispatchers.Default) private var job: Job? = null private var callback: (() -> Unit)? = null private var startDelay: Long = 0 private var period: Long = 0 /*** * Prepare timer to scheduled work * @param delay - Start delay in ms * @param period - Callback invoke period in ms * @param callback - Callback-listener for timer tick */ fun scheduled(delay: Long, period: Long, callback: () -> Unit) { this.startDelay = delay this.period = period this.callback = callback } /*** * Run timer */ fun run() { job = coroutineContext.launch { delay(startDelay) while(isActive) { callback?.invoke() delay(period) } } } /*** * Stop timer */ fun stop() { job?.cancel() } }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/CoroutineTimer.kt
2893065979
package app.kotleni.pomodoro interface TimerService { fun stop() fun start() fun pause() fun resume() fun setTimer(timer: Timer?) fun setStage(stage: TimerStage) fun setListener(listener: TimerListener?) fun getTimer(): Timer? } // expect class TimerServiceImpl : TimerService
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/TimerService.kt
3642038571
package app.kotleni.pomodoro.usecases import app.kotleni.pomodoro.Timer import app.kotleni.pomodoro.repositories.TimersRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class LoadTimerByIdUseCase( private val timersRepository: TimersRepository ) { suspend operator fun invoke(timerId: Long, finishCallback: (Timer) -> Unit) { val timer = withContext(Dispatchers.IO) { timersRepository.fetchTimers().find { it.id == timerId } } ?: return finishCallback(timer) } }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/usecases/LoadTimerByIdUseCase.kt
2696865995
package app.kotleni.pomodoro.usecases import app.kotleni.pomodoro.Timer import app.kotleni.pomodoro.repositories.TimersRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class RemoveTimerUseCase( private val timersRepository: TimersRepository ) { suspend operator fun invoke(timer: Timer, finishCallback: () -> Unit) { withContext(Dispatchers.IO) { timersRepository.removeTimer(timer) } finishCallback() } }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/usecases/RemoveTimerUseCase.kt
1659456625
package app.kotleni.pomodoro.usecases import app.kotleni.pomodoro.Timer import app.kotleni.pomodoro.repositories.TimersRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlin.random.Random class CreateTimerUseCase( private val timersRepository: TimersRepository ) { suspend operator fun invoke(name: String, iconId: Int, workTime: Int, sbrakeTime: Int, lbrakeTime: Int, finishCallback: () -> Unit) { // Debug purpose, if started with prefix 'debug: ' use seconds instead of minutes val isDebugSecs = name.startsWith("debug: ") withContext(Dispatchers.IO) { val timer = Timer( name = name.removePrefix("debug: "), iconId = iconId.toLong(), totalWorkTime = if(isDebugSecs) Random.nextLong(0, 9999) else 0, totalBreakTime = if(isDebugSecs) Random.nextLong(0, 999) else 0, workTime = (if(isDebugSecs) workTime else workTime * 60).toLong(), // in minutes shortBreakTime = (if(isDebugSecs) sbrakeTime else sbrakeTime * 60).toLong(), // in minutes longBreakTime = (if(isDebugSecs) lbrakeTime else lbrakeTime * 60).toLong(), // in minutes id = 0 // automatic ) timersRepository.addTimer(timer) } finishCallback() } }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/usecases/CreateTimerUseCase.kt
1894412095
package app.kotleni.pomodoro.usecases import app.kotleni.pomodoro.Timer import app.kotleni.pomodoro.repositories.TimersRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class UpdateTimerUseCase( private val timersRepository: TimersRepository ) { suspend operator fun invoke(updatedTimer: Timer) { withContext(Dispatchers.IO) { timersRepository.updateTimer(updatedTimer) } } }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/usecases/UpdateTimerUseCase.kt
1569340862
package app.kotleni.pomodoro.usecases import app.kotleni.pomodoro.Timer import app.kotleni.pomodoro.repositories.TimersRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class FetchTimersUseCase( private val timersRepository: TimersRepository ) { suspend operator fun invoke(finishCallback: (timers: List<Timer>) -> Unit) { val timers = withContext(Dispatchers.IO) { timersRepository.fetchTimers() } finishCallback(timers) } }
PomodoroTracker-MP/shared/src/commonMain/kotlin/app/kotleni/pomodoro/usecases/FetchTimersUseCase.kt
3920494393
package app.kotleni.pomodoro.di import org.koin.core.module.Module actual fun platformModule(): Module { return desktopModule }
PomodoroTracker-MP/shared/src/desktopMain/kotlin/app/kotleni/pomodoro/di/koin.desktop.kt
3411502068
package app.kotleni.pomodoro.di import org.koin.core.module.Module import org.koin.dsl.module import app.kotleni.pomodoro.DatabaseDriverFactory val desktopModule: Module = module { factory { DatabaseDriverFactory() } }
PomodoroTracker-MP/shared/src/desktopMain/kotlin/app/kotleni/pomodoro/di/desktopModule.kt
1399238916
package app.kotleni.pomodoro import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers actual open class ViewModel { actual val viewModelScope: CoroutineScope = CoroutineScope(Dispatchers.Default) }
PomodoroTracker-MP/shared/src/desktopMain/kotlin/app/kotleni/pomodoro/ViewModel.kt
4173749193
package app.kotleni.pomodoro import app.cash.sqldelight.db.SqlDriver import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver import java.io.File actual class DatabaseDriverFactory { actual fun createDriver(): SqlDriver { return JdbcSqliteDriver("jdbc:sqlite:local.db") .also { if(!File("local.db").exists()) Database.Schema.create(it) } } }
PomodoroTracker-MP/shared/src/desktopMain/kotlin/app/kotleni/pomodoro/DatabaseDriverFactory.kt
3000924706
package app.kotleni.pomodoro import androidx.compose.runtime.Composable import org.koin.compose.koinInject import org.koin.core.parameter.ParametersDefinition @Composable actual inline fun <reified TSM : ViewModel> stateMachine( noinline parameters: ParametersDefinition?, ): TSM = koinInject<TSM>( parameters = parameters, )
PomodoroTracker-MP/shared/src/desktopMain/kotlin/app/kotleni/pomodoro/stateMachine.kt
3555359792
import androidx.compose.desktop.ui.tooling.preview.Preview import androidx.compose.runtime.Composable @Composable fun MainView() = App() actual fun getPatformType(): PlatformType { return PlatformType.DESKTOP }
PomodoroTracker-MP/shared/src/desktopMain/kotlin/main.desktop.kt
2835333685
import androidx.compose.runtime.Composable @Composable fun MainView() = App() actual fun getPatformType(): PlatformType { return PlatformType.ANDROID }
PomodoroTracker-MP/shared/src/androidMain/kotlin/main.android.kt
200500566
package app.kotleni.pomodoro.di import org.koin.android.ext.koin.androidContext import org.koin.core.module.Module import org.koin.dsl.module import app.kotleni.pomodoro.DatabaseDriverFactory val androidModule: Module = module { factory { DatabaseDriverFactory(androidContext()) } }
PomodoroTracker-MP/shared/src/androidMain/kotlin/app/kotleni/pomodoro/di/androidModule.kt
195964217
package app.kotleni.pomodoro.di import org.koin.core.module.Module actual fun platformModule(): Module { return androidModule }
PomodoroTracker-MP/shared/src/androidMain/kotlin/app/kotleni/pomodoro/di/koin.android.kt
2663952840
package app.kotleni.pomodoro import androidx.lifecycle.ViewModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers actual open class ViewModel : ViewModel() { actual val viewModelScope: CoroutineScope = CoroutineScope(Dispatchers.Main) }
PomodoroTracker-MP/shared/src/androidMain/kotlin/app/kotleni/pomodoro/ViewModel.kt
3691388623
package app.kotleni.pomodoro import android.content.Context import app.cash.sqldelight.db.SqlDriver import app.cash.sqldelight.driver.android.AndroidSqliteDriver actual class DatabaseDriverFactory(private val context: Context) { actual fun createDriver(): SqlDriver { return AndroidSqliteDriver(Database.Schema, context, "local.db") } }
PomodoroTracker-MP/shared/src/androidMain/kotlin/app/kotleni/pomodoro/DatabaseDriverFactory.kt
2882037993
package app.kotleni.pomodoro import androidx.compose.runtime.Composable import androidx.lifecycle.ViewModelStoreOwner import androidx.lifecycle.viewmodel.CreationExtras import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner import org.koin.androidx.compose.defaultExtras import org.koin.androidx.viewmodel.resolveViewModel import org.koin.compose.LocalKoinScope import org.koin.core.annotation.KoinInternalApi import org.koin.core.parameter.ParametersDefinition import org.koin.core.qualifier.Qualifier import org.koin.core.scope.Scope /** * Creates and returns an instance of the specified state machine using the provided factory. * * @param TSM The reified type of the state machine. * @param TState The type of the state in the state machine. * @param TEvent The type of the events in the state machine. * @param TEffect The type of the effects in the state machine. * @param factory The factory to create the state machine instance. * @return The created instance of the state machine. */ @Composable actual inline fun <reified TSM : ViewModel> stateMachine( noinline parameters: ParametersDefinition?, ) = koinVM<TSM>(parameters = parameters) @OptIn(KoinInternalApi::class) @PublishedApi @Composable internal inline fun <reified T : ViewModel> koinVM( qualifier: Qualifier? = null, viewModelStoreOwner: ViewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) { "No ViewModelStoreOwner was provided via LocalViewModelStoreOwner" }, key: String? = null, extras: CreationExtras = defaultExtras(viewModelStoreOwner), scope: Scope = LocalKoinScope.current, noinline parameters: ParametersDefinition? = null, ): T { return resolveViewModel( T::class, viewModelStoreOwner.viewModelStore, key, extras, qualifier, scope, parameters ) }
PomodoroTracker-MP/shared/src/androidMain/kotlin/app/kotleni/pomodoro/stateMachine.kt
2573939067
import androidx.compose.ui.Alignment import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Window import androidx.compose.ui.window.WindowPosition import androidx.compose.ui.window.application import androidx.compose.ui.window.rememberWindowState import app.kotleni.pomodoro.di.koinModules import org.koin.core.context.startKoin fun main() = application { startKoin { modules(koinModules) } val state = rememberWindowState( size = DpSize(420.dp, 700.dp), position = WindowPosition(Alignment.Center) ) Window( onCloseRequest = ::exitApplication, title = "PomodoroTracker", state = state ) { MainView() } }
PomodoroTracker-MP/desktopApp/src/jvmMain/kotlin/main.kt
4027795409
package com.myapplication import MainView import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import app.kotleni.pomodoro.di.koinModules import org.koin.android.ext.koin.androidContext import org.koin.core.context.startKoin class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) startKoin { androidContext(applicationContext) modules(koinModules) } setContent { MainView() } } }
PomodoroTracker-MP/androidApp/src/androidMain/kotlin/com/myapplication/MainActivity.kt
4074171553
package com.churakov.hrservice 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.churakov.hrservice", appContext.packageName) } }
HRService/app/src/androidTest/java/com/churakov/hrservice/ExampleInstrumentedTest.kt
3289445189
package com.churakov.hrservice 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) } }
HRService/app/src/test/java/com/churakov/hrservice/ExampleUnitTest.kt
239670627
package com.churakov.hrservice import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
HRService/app/src/main/java/com/churakov/hrservice/MainActivity.kt
3080523461
package com.churakov.hrservice import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [SettingsFragment.newInstance] factory method to * create an instance of this fragment. */ class SettingsFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_settings, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment SettingsFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = SettingsFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
HRService/app/src/main/java/com/churakov/hrservice/SettingsFragment.kt
14935972
package com.churakov.hrservice import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [AuthorizationFragment.newInstance] factory method to * create an instance of this fragment. */ class AuthorizationFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_authorization, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment AuthorizationFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = AuthorizationFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
HRService/app/src/main/java/com/churakov/hrservice/AuthorizationFragment.kt
734573446
package com.churakov.hrservice import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [NotificationsFragment.newInstance] factory method to * create an instance of this fragment. */ class NotificationsFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_notifications, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment NotificationsFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = NotificationsFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
HRService/app/src/main/java/com/churakov/hrservice/NotificationsFragment.kt
1234295430
package com.churakov.hrservice import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [MainFragment.newInstance] factory method to * create an instance of this fragment. */ class MainFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_main, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment MainFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = MainFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
HRService/app/src/main/java/com/churakov/hrservice/MainFragment.kt
4245263927
package com.churakov.hrservice import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [WelcomeFragment.newInstance] factory method to * create an instance of this fragment. */ class WelcomeFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_welcome, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment WelcomeFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = WelcomeFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
HRService/app/src/main/java/com/churakov/hrservice/WelcomeFragment.kt
3931178494
package xyz.larkyy.aquaticseries.chunk interface ChunkData { }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/chunk/ChunkData.kt
274515851
package xyz.larkyy.aquaticseries.chunk import org.bukkit.Chunk class ChunkDataContainer<T: ChunkData>( val serializer: ChunkDataSerializer<T> ) { val active = HashMap<String,T>() val inactive = HashMap<String,DyingChunkData<T>>() fun getChunkData(chunk: Chunk): T? { val str = "${chunk.world.name};${chunk.x};${chunk.z}" return active[str] } fun addChunkData(chunk: Chunk, value: T) { val str = "${chunk.world.name};${chunk.x};${chunk.z}" active[str] = value } }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/chunk/ChunkDataContainer.kt
1031405377
package xyz.larkyy.aquaticseries.chunk class DyingChunkData<T: ChunkData>( val chunkData: T, val dieAfter: Int ) { var ticksAlive = 0 fun tick(): Boolean { ticksAlive++ return (ticksAlive >= dieAfter) } }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/chunk/DyingChunkData.kt
2320379396
package xyz.larkyy.aquaticseries.chunk abstract class ChunkDataSerializer<T: ChunkData> { abstract fun serialize(value: MutableList<T>): String abstract fun deserialize(value: String): MutableList<T> }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/chunk/ChunkDataSerializer.kt
1513794034
package xyz.larkyy.aquaticseries import org.bukkit.block.BlockFace class Utils { companion object { fun cardinalDirection(direction: Float): BlockFace { var rotation: Float = (direction - 180) % 360 if (rotation < 0) { rotation += 360.0f } return when { rotation >= 315 || rotation < 45 -> BlockFace.NORTH rotation >= 45 && rotation < 135 -> BlockFace.EAST rotation >= 135 && rotation < 225 -> BlockFace.SOUTH else -> BlockFace.WEST } } } }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/Utils.kt
2226806600
package xyz.larkyy.aquaticseries import org.bukkit.Bukkit import org.bukkit.Location fun Location.toStringSimple(): String { return "${this.world!!.name};${this.x};${this.y};${this.z}" } fun Location.toStringDetailed(): String { return "${this.world!!.name};${this.x};${this.y};${this.z};${this.yaw};${this.pitch}" } fun String.toLocation(): Location? { val parts = this.split(";") if (parts.size < 4) return null val world = Bukkit.getWorld(parts[0]) ?: return null val x = parts[1].toDoubleOrNull() ?: return null val y = parts[2].toDoubleOrNull() ?: return null val z = parts[3].toDoubleOrNull() ?: return null if (parts.size > 5) { val yaw = parts[4].toFloatOrNull() ?: return null val pitch = parts[5].toFloatOrNull() ?: return null return Location(world, x, y, z, yaw, pitch) } return Location(world, x, y, z) }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/LocationExt.kt
519389596
package xyz.larkyy.aquaticseries import org.bukkit.plugin.java.JavaPlugin abstract class AbstractAquaticPlugin: JavaPlugin() { val injections = ArrayList<AbstractAquaticModuleInject>() fun injectAll() { for (injection in injections) { injection.inject() } } fun ejectAll() { for (injection in injections) { injection.eject() } } }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/AbstractAquaticPlugin.kt
1576117913
package xyz.larkyy.aquaticseries import org.bukkit.plugin.java.JavaPlugin import java.io.File abstract class AbstractAquaticModuleInject( val plugin: JavaPlugin, val dataFolder: File ) { abstract fun inject() abstract fun eject() }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/AbstractAquaticModuleInject.kt
1860237105
package xyz.larkyy.aquaticseries import org.bukkit.Bukkit class AquaticLogger { private inner class ErrorLogger: AbstractAquaticLogger() { override fun log(message: String) { Bukkit.getConsoleSender().sendMessage("§c[ERROR] $message") } } private inner class InfoLogger: AbstractAquaticLogger() { override fun log(message: String) { Bukkit.getConsoleSender().sendMessage("§e[INFO] $message") } } abstract inner class AbstractAquaticLogger() { abstract fun log(message: String) } }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/AquaticLogger.kt
1258130880
package xyz.larkyy.aquaticseries.chance interface IChance { fun chance(): Double }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/chance/IChance.kt
1497285207
package xyz.larkyy.aquaticseries.chance class ChanceUtils { companion object { fun <T : IChance> getRandomItem(items: MutableList<T>): T? { val chances = items.map { it.chance() }.toMutableList() val randomIndex = getRandomChanceIndex(chances) if (randomIndex < 0) return null return items[randomIndex] } fun getRandomChanceIndex(chances: MutableList<Double>): Int { if (chances.isEmpty()) return -1 if (getTotalPercentage(chances) <= 0) { return -1 } var totalWeight = 0.0 for (chance in chances) { totalWeight += chance } var random: Double = Math.random() * totalWeight for (i in 0..<chances.size) { random -= chances[i] if (random <= 0.0) { return i } } return -1 } private fun getTotalPercentage(chances: MutableList<Double>): Double { return chances.sum() } } }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/chance/ChanceUtils.kt
4218974142
package xyz.larkyy.aquaticseries import com.google.gson.Gson import org.bukkit.Bukkit import org.bukkit.plugin.java.JavaPlugin import org.bukkit.scheduler.BukkitRunnable import xyz.larkyy.aquaticseries.interactable.InteractableHandler import xyz.larkyy.aquaticseries.awaiters.AbstractAwaiter import xyz.larkyy.aquaticseries.awaiters.IAAwaiter import xyz.larkyy.aquaticseries.awaiters.MEGAwaiter class AquaticSeriesLib private constructor(val plugin: JavaPlugin, workloadDelay: Long) { val interactableHandler = InteractableHandler(workloadDelay) var enginesLoaded = false init { object : BukkitRunnable() { override fun run() { interactableHandler.registerListeners(plugin) } }.runTaskLater(plugin,1) val loaders = ArrayList<AbstractAwaiter>() if (Bukkit.getPluginManager().getPlugin("ModelEngine") != null) { val awaiter = MEGAwaiter(this) loaders += awaiter awaiter.future.thenRun { if (loaders.all { it.loaded }) { onEnginesInit() } } } if (Bukkit.getPluginManager().getPlugin("ItemsAdder") != null) { val awaiter = IAAwaiter(this) loaders += awaiter awaiter.future.thenRun { if (loaders.all { it.loaded }) { onEnginesInit() } } } } private fun onEnginesInit() { enginesLoaded = true interactableHandler.canRun = true interactableHandler.interactableWorkload.run() } companion object { val GSON = Gson() private var _INSTANCE: AquaticSeriesLib? = null val INSTANCE: AquaticSeriesLib get() { if (_INSTANCE == null) { throw Exception("Library was not initialized! Use the init() method first!") } return _INSTANCE!! } fun init(plugin: JavaPlugin, workloadDelay: Long): AquaticSeriesLib { val instance = _INSTANCE if (instance != null) return instance _INSTANCE = AquaticSeriesLib(plugin, workloadDelay) return _INSTANCE!! } } }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/AquaticSeriesLib.kt
1406049055
package xyz.larkyy.aquaticseries.awaiters import com.ticxo.modelengine.api.ModelEngineAPI import com.ticxo.modelengine.api.events.ModelRegistrationEvent import com.ticxo.modelengine.api.generator.ModelGenerator import org.bukkit.event.EventHandler import org.bukkit.event.Listener import xyz.larkyy.aquaticseries.AquaticSeriesLib import java.util.concurrent.CompletableFuture class MEGAwaiter(val lib: AquaticSeriesLib): AbstractAwaiter() { override val future: CompletableFuture<Void> = CompletableFuture() init { if (ModelEngineAPI.getAPI().modelGenerator.isInitialized) { future.complete(null) loaded = true } else { lib.plugin.server.pluginManager.registerEvents(Listeners(),lib.plugin) } } inner class Listeners: Listener { @EventHandler fun onMegInit(event: ModelRegistrationEvent) { if (event.phase == ModelGenerator.Phase.FINISHED) { future.complete(null) loaded = true } } } }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/awaiters/MEGAwaiter.kt
1921350016
package xyz.larkyy.aquaticseries.awaiters import java.util.concurrent.CompletableFuture abstract class AbstractAwaiter { abstract val future: CompletableFuture<Void> var loaded = false }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/awaiters/AbstractAwaiter.kt
1943533759
package xyz.larkyy.aquaticseries.awaiters import dev.lone.itemsadder.api.Events.ItemsAdderLoadDataEvent import org.bukkit.event.EventHandler import org.bukkit.event.Listener import xyz.larkyy.aquaticseries.AquaticSeriesLib import java.util.concurrent.CompletableFuture class IAAwaiter(val lib: AquaticSeriesLib): AbstractAwaiter() { override val future: CompletableFuture<Void> = CompletableFuture() init { lib.plugin.server.pluginManager.registerEvents(Listeners(),lib.plugin) } inner class Listeners: Listener { @EventHandler fun onIALoad(event: ItemsAdderLoadDataEvent) { future.complete(null) loaded = true } } }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/awaiters/IAAwaiter.kt
1286039114
package xyz.larkyy.aquaticseries.item.impl import org.bukkit.Material import org.bukkit.enchantments.Enchantment import org.bukkit.inventory.ItemFlag import org.bukkit.inventory.ItemStack import xyz.larkyy.aquaticseries.item.CustomItem class VanillaItem( val material: Material, name: String?, description: MutableList<String>?, amount: Int, modelData: Int, enchantments: MutableMap<Enchantment, Int>?, flags: MutableList<ItemFlag>?, ): CustomItem( name, description, amount, modelData, enchantments, flags ) { override fun getUnmodifiedItem(): ItemStack { return ItemStack(material) } }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/item/impl/VanillaItem.kt
1715176402
package xyz.larkyy.aquaticseries.item.impl import io.lumine.mythic.api.MythicProvider import io.lumine.mythic.bukkit.adapters.BukkitItemStack import org.bukkit.enchantments.Enchantment import org.bukkit.inventory.ItemFlag import org.bukkit.inventory.ItemStack import xyz.larkyy.aquaticseries.item.CustomItem class MMItem( val id: String, name: String?, description: MutableList<String>?, amount: Int, modelData: Int, enchantments: MutableMap<Enchantment, Int>?, flags: MutableList<ItemFlag>? ): CustomItem(name, description, amount, modelData, enchantments, flags) { override fun getUnmodifiedItem(): ItemStack { return (MythicProvider.get().itemManager.getItem(id).get() .generateItemStack(1) as BukkitItemStack).build() } }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/item/impl/MMItem.kt
3135243065
package xyz.larkyy.aquaticseries.item.impl import io.th0rgal.oraxen.api.OraxenItems import org.bukkit.enchantments.Enchantment import org.bukkit.inventory.ItemFlag import org.bukkit.inventory.ItemStack import xyz.larkyy.aquaticseries.item.CustomItem class OraxenItem( val id: String, name: String?, description: MutableList<String>?, amount: Int, modelData: Int, enchantments: MutableMap<Enchantment, Int>?, flags: MutableList<ItemFlag>? ) : CustomItem(name, description, amount, modelData, enchantments, flags) { override fun getUnmodifiedItem(): ItemStack { return OraxenItems.getItemById(id).build() } }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/item/impl/OraxenItem.kt
1306144865
package xyz.larkyy.aquaticseries.item import org.bukkit.Material import org.bukkit.NamespacedKey import org.bukkit.configuration.file.FileConfiguration import org.bukkit.enchantments.Enchantment import org.bukkit.entity.Player import org.bukkit.inventory.ItemFlag import org.bukkit.inventory.ItemStack import org.bukkit.inventory.meta.EnchantmentStorageMeta import org.bukkit.persistence.PersistentDataType import xyz.larkyy.aquaticseries.format.color.ColorUtils import java.util.* abstract class CustomItem( val name: String?, val description: MutableList<String>?, val amount: Int, val modelData: Int, val enchantments: MutableMap<Enchantment,Int>?, val flags: MutableList<ItemFlag>? ) { var registryId: String? = null fun giveItem(player: Player) { giveItem(player,amount) } fun giveItem(player: Player, amount: Int) { val iS = getItem() iS.amount = amount player.inventory.addItem(iS) } fun getItem(): ItemStack { val iS = getUnmodifiedItem() val im = iS.itemMeta ?: return iS name?.apply { im.setDisplayName(ColorUtils.format(name)) } description?.apply { im.lore = ColorUtils.format(description) } if (modelData > 0) { im.setCustomModelData(modelData) } flags?.apply { im.addItemFlags(*this.toTypedArray()) } registryId?.let { im.persistentDataContainer.set(CustomItemHandler.NAMESPACE_KEY, PersistentDataType.STRING,it) } iS.itemMeta = im enchantments?.apply { if (iS.type == Material.ENCHANTED_BOOK) { val esm = im as EnchantmentStorageMeta this.forEach { (t, u) -> esm.addStoredEnchant(t,u,true) } iS.itemMeta = esm } else { iS.itemMeta = im iS.addUnsafeEnchantments(enchantments) } } iS.amount = amount return iS } fun register(id: String) { if (this.registryId != null) return this.registryId = id customItemHandler.itemRegistry[id] = this } abstract fun getUnmodifiedItem(): ItemStack companion object { val customItemHandler: CustomItemHandler = CustomItemHandler() private fun getEnchantmentByString(ench: String): Enchantment? { return Enchantment.getByKey(NamespacedKey.minecraft(ench.lowercase(Locale.getDefault()))) } fun get(id: String): CustomItem? { return customItemHandler.itemRegistry[id] } fun get(itemStack: ItemStack): CustomItem? { val pdc = itemStack.itemMeta?.persistentDataContainer ?: return null if (!pdc.has(CustomItemHandler.NAMESPACE_KEY, PersistentDataType.STRING)) return null val id = pdc.get(CustomItemHandler.NAMESPACE_KEY, PersistentDataType.STRING) return customItemHandler.itemRegistry[id] } fun create( namespace: String, name: String?, description: MutableList<String>?, amount: Int, modeldata: Int, enchantments: MutableMap<Enchantment, Int>?, flags: MutableList<ItemFlag>? ): CustomItem { return customItemHandler.getCustomItem(namespace, name, description, amount, modeldata, enchantments, flags) } fun loadFromYaml(cfg: FileConfiguration, path: String): CustomItem? { if (!cfg.contains(path)) { return null } var lore: MutableList<String>? = null if (cfg.contains("$path.lore")) { lore = cfg.getStringList("$path.lore") } val enchantments: MutableMap<Enchantment, Int> = HashMap() if (cfg.contains("$path.enchants")) { for (str in cfg.getStringList("$path.enchants")) { val strs = str.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() if (strs.size < 2) { continue } val enchantment = getEnchantmentByString(strs[0]) ?: continue val level = strs[1].toInt() enchantments[enchantment] = level } } val flags: MutableList<ItemFlag> = ArrayList() if (cfg.contains("$path.flags")) { for (flag in cfg.getStringList("$path.flags")) { val itemFlag = ItemFlag.valueOf(flag.uppercase(Locale.getDefault())) flags.add(itemFlag) } } return create( cfg.getString("$path.material", "STONE")!!, cfg.getString("$path.display-name"), lore, cfg.getInt("$path.amount", 1), cfg.getInt("$path.model-data"), enchantments, flags ) } } }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/item/CustomItem.kt
2019208054
package xyz.larkyy.aquaticseries.item import org.bukkit.Material import org.bukkit.NamespacedKey import org.bukkit.enchantments.Enchantment import org.bukkit.inventory.ItemFlag import xyz.larkyy.aquaticseries.AquaticSeriesLib import xyz.larkyy.aquaticseries.item.factory.ItemFactory import xyz.larkyy.aquaticseries.item.factory.impl.MMFactory import xyz.larkyy.aquaticseries.item.factory.impl.OraxenFactory import xyz.larkyy.aquaticseries.item.impl.VanillaItem import java.util.* import kotlin.collections.HashMap class CustomItemHandler { private val itemRegistries = HashMap<String, ItemFactory>().apply { put("mythicitem", MMFactory()) put("oraxen", OraxenFactory()) } val itemRegistry = HashMap<String,CustomItem>() companion object { val NAMESPACE_KEY = NamespacedKey(AquaticSeriesLib.INSTANCE.plugin,"Custom_Item_Registry") } fun getCustomItem( namespace: String, name: String?, description: MutableList<String>?, amount: Int, modeldata: Int, enchantments: MutableMap<Enchantment, Int>?, flags: MutableList<ItemFlag>? ): CustomItem { val strs = namespace.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() val provider = strs[0].lowercase(Locale.getDefault()) val factory: ItemFactory? = itemRegistries[provider] if (strs.size == 1 || factory == null) { return VanillaItem( Material.valueOf(strs[0].uppercase(Locale.getDefault())), name, description, amount, modeldata, enchantments, flags ) } val identifier = namespace.substring(provider.length + 1) return factory.create(identifier, name, description, amount, modeldata, enchantments, flags) } }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/item/CustomItemHandler.kt
1961729702
package xyz.larkyy.aquaticseries.item.factory.impl import org.bukkit.enchantments.Enchantment import org.bukkit.inventory.ItemFlag import xyz.larkyy.aquaticseries.item.impl.OraxenItem import xyz.larkyy.aquaticseries.item.CustomItem import xyz.larkyy.aquaticseries.item.factory.ItemFactory class OraxenFactory: ItemFactory { override fun create( id: String, name: String?, description: MutableList<String>?, amount: Int, modelData: Int, enchantments: MutableMap<Enchantment, Int>?, flags: MutableList<ItemFlag>? ): CustomItem { return OraxenItem(id, name, description, amount, modelData, enchantments, flags) } }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/item/factory/impl/OraxenFactory.kt
3685524765
package xyz.larkyy.aquaticseries.item.factory.impl import org.bukkit.enchantments.Enchantment import org.bukkit.inventory.ItemFlag import xyz.larkyy.aquaticseries.item.CustomItem import xyz.larkyy.aquaticseries.item.factory.ItemFactory import xyz.larkyy.aquaticseries.item.impl.MMItem class MMFactory: ItemFactory { override fun create( id: String, name: String?, description: MutableList<String>?, amount: Int, modelData: Int, enchantments: MutableMap<Enchantment, Int>?, flags: MutableList<ItemFlag>? ): CustomItem { return MMItem(id, name, description, amount, modelData, enchantments, flags) } }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/item/factory/impl/MMFactory.kt
458137771
package xyz.larkyy.aquaticseries.item.factory import org.bukkit.enchantments.Enchantment import org.bukkit.inventory.ItemFlag import xyz.larkyy.aquaticseries.item.CustomItem interface ItemFactory { fun create(id: String, name: String?, description: MutableList<String>?, amount: Int, modelData: Int, enchantments: MutableMap<Enchantment,Int>?, flags: MutableList<ItemFlag>?): CustomItem }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/item/factory/ItemFactory.kt
2415600113
package xyz.larkyy.aquaticseries.interactable.impl.meg import com.ticxo.modelengine.api.entity.Dummy class MegInteractableDummy( val spawnedInteractable: SpawnedMegInteractable ): Dummy<Any>() { }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/interactable/impl/meg/MegInteractableDummy.kt
893732253
package xyz.larkyy.aquaticseries.interactable.impl.meg import com.jeff_media.customblockdata.CustomBlockData import org.bukkit.Bukkit import org.bukkit.Location import org.bukkit.persistence.PersistentDataType import org.bukkit.util.Consumer import org.bukkit.util.Vector import xyz.larkyy.aquaticseries.AquaticSeriesLib import xyz.larkyy.aquaticseries.Utils import xyz.larkyy.aquaticseries.interactable.* import xyz.larkyy.aquaticseries.interactable.event.MegInteractableInteractEvent import xyz.larkyy.aquaticseries.interactable.impl.block.BlockShape import xyz.larkyy.aquaticseries.toStringDetailed import xyz.larkyy.aquaticseries.toStringSimple import kotlin.math.floor class MEGInteractable( override val id: String, override val shape: BlockShape, val modelId: String, val onInteract: Consumer<MegInteractableInteractEvent> ) : AbstractInteractable() { override val serializer: MegInteractableSerializer get() { return AquaticSeriesLib.INSTANCE.interactableHandler.serializers[MEGInteractable::class.java] as MegInteractableSerializer } init { AquaticSeriesLib.INSTANCE.interactableHandler.registry[id] = this } override fun spawn(location: Location): SpawnedMegInteractable { val locations = ArrayList<Location>() val spawned = SpawnedMegInteractable(location, this, locations) Bukkit.broadcastMessage("Spawning MEG") val nullChars = ArrayList<Char>() processLayerCells(shape.layers, location) { char, newLoc -> val block = shape.blocks[char] if (block == null) { nullChars += char } else { block.place(newLoc) locations += newLoc } } val cbd = CustomBlockData(location.block, AquaticSeriesLib.INSTANCE.plugin) val blockData = InteractableData(id, location.yaw, location.pitch, serializer.serialize(spawned), shape.layers, nullChars) cbd.set(INTERACTABLE_KEY, PersistentDataType.STRING, AquaticSeriesLib.GSON.toJson(blockData)) AquaticSeriesLib.INSTANCE.interactableHandler.addParent(location, spawned) for (loc in locations) { AquaticSeriesLib.INSTANCE.interactableHandler.addChildren(loc, location) } return spawned } fun onInteract(event: MegInteractableInteractEvent) { this.onInteract.accept(event) } override fun onChunkLoad(data: InteractableData, location: Location) { serializer.deserialize(data, location, this) } override fun onChunkUnload(data: InteractableData) { } }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/interactable/impl/meg/MEGInteractable.kt
1009468985
package xyz.larkyy.aquaticseries.interactable.impl.meg import com.jeff_media.customblockdata.CustomBlockData import com.ticxo.modelengine.api.ModelEngineAPI import com.ticxo.modelengine.api.model.ActiveModel import com.ticxo.modelengine.api.model.ModeledEntity import org.bukkit.Location import org.bukkit.Material import xyz.larkyy.aquaticseries.AquaticSeriesLib import xyz.larkyy.aquaticseries.interactable.AbstractInteractable import xyz.larkyy.aquaticseries.interactable.AbstractSpawnedInteractable import xyz.larkyy.aquaticseries.toStringDetailed import xyz.larkyy.aquaticseries.toStringSimple import kotlin.jvm.optionals.getOrNull class SpawnedMegInteractable( override val location: Location, override val interactable: MEGInteractable, override val associatedLocations: List<Location> ) : AbstractSpawnedInteractable() { val dummy = MegInteractableDummy(this) override var loaded = false init { AquaticSeriesLib.INSTANCE.interactableHandler.addWorkloadJob(location.chunk) { dummy.location = this.location dummy.bodyRotationController.yBodyRot = location.yaw dummy.bodyRotationController.xHeadRot = location.pitch dummy.bodyRotationController.yHeadRot = location.yaw dummy.yHeadRot = location.yaw dummy.yBodyRot = location.yaw val me = ModelEngineAPI.createModeledEntity(dummy) val am = ModelEngineAPI.createActiveModel(interactable.modelId) me.addModel(am,true) this.loaded = true } } val modeledEntity: ModeledEntity? get() { if (!loaded) return null return ModelEngineAPI.getModeledEntity(dummy.entityId) } val activeModel: ActiveModel? get() { if (!loaded) return null return modeledEntity?.getModel(interactable.modelId)?.getOrNull() } override fun despawn() { destroyEntity() for (associatedLocation in associatedLocations) { AquaticSeriesLib.INSTANCE.interactableHandler.removeChildren(associatedLocation) } val cbd = CustomBlockData(location.block, AquaticSeriesLib.INSTANCE.plugin) cbd.remove(AbstractInteractable.INTERACTABLE_KEY) AquaticSeriesLib.INSTANCE.interactableHandler.removeParent(location) cbd.clear() } fun destroyEntity() { if (!loaded) return modeledEntity?.destroy() } }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/interactable/impl/meg/SpawnedMegInteractable.kt
989862496
package xyz.larkyy.aquaticseries.interactable.impl.meg import org.bukkit.Location import xyz.larkyy.aquaticseries.interactable.AbstractInteractable import xyz.larkyy.aquaticseries.interactable.AbstractInteractableSerializer import xyz.larkyy.aquaticseries.interactable.InteractableData import xyz.larkyy.aquaticseries.toLocation import xyz.larkyy.aquaticseries.toStringDetailed class MegInteractableSerializer: AbstractInteractableSerializer<SpawnedMegInteractable>() { override fun serialize(value: SpawnedMegInteractable): String { return value.location.toStringDetailed() } override fun deserialize( value: InteractableData, location: Location, interactable: AbstractInteractable ): SpawnedMegInteractable? { if (interactable !is MEGInteractable) return null val realLoc = value.data.toLocation() ?: return null return interactable.spawn(realLoc) } }
AquaticSeriesLib/src/main/kotlin/xyz/larkyy/aquaticseries/interactable/impl/meg/MegInteractableSerializer.kt
3463475358