path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/pathfinding/Pathfinder.kt
390416065
package com.nexus.farmap.domain.pathfinding import com.nexus.farmap.domain.tree.Tree interface Pathfinder { suspend fun findWay( from: String, to: String, tree: Tree ): Path? }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/smoothing/BezierPoint.kt
724503624
package com.nexus.farmap.domain.smoothing import dev.benedikt.math.bezier.vector.Vector3D data class BezierPoint( val t: Double, var pos: Vector3D )
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/utils/FloatExt.kt
468572702
package com.nexus.farmap.domain.utils import dev.romainguy.kotlin.math.Float3 import dev.romainguy.kotlin.math.pow import kotlin.math.abs import kotlin.math.sqrt fun Float3.getApproxDif(pos: Float3): Float { return sqrt( +abs(pow(x - pos.x, 2f)) + abs(pow(z - pos.z, 2f)) ) }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/hit_test/OrientatedPosition.kt
3683246756
package com.nexus.farmap.domain.hit_test import dev.romainguy.kotlin.math.Float3 import dev.romainguy.kotlin.math.Quaternion data class OrientatedPosition( val position: Float3, val orientation: Quaternion )
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/hit_test/HitTestResult.kt
725745218
package com.nexus.farmap.domain.hit_test import com.google.ar.core.HitResult data class HitTestResult( val orientatedPosition: OrientatedPosition, val hitResult: HitResult )
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/ml/ObjectDetector.kt
560058351
package com.nexus.farmap.domain.ml import android.media.Image import com.nexus.farmap.data.model.DetectedObjectResult /** * Describes a common interface for [GoogleCloudVisionDetector] and [MLKitObjectDetector] that can * infer object labels in a given [Image] and gives results in a list of [DetectedObjectResult]. */ interface ObjectDetector { /** * Infers a list of [DetectedObjectResult] given a camera image frame, which contains a confidence level, * a label, and a pixel coordinate on the image which is believed to be the center of the object. */ suspend fun analyze( mediaImage: Image, rotationDegrees: Int, imageCropPercentages: Pair<Int, Int>, displaySize: Pair<Int, Int> ): Result<DetectedObjectResult> }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/ml/DetectedText.kt
3141089637
package com.nexus.farmap.domain.ml import com.nexus.farmap.data.model.DetectedObjectResult import com.google.ar.core.Frame data class DetectedText( val detectedObjectResult: DetectedObjectResult, val frame: Frame )
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/use_cases/GetDestinationDesc.kt
3816662283
package com.nexus.farmap.domain.use_cases import android.content.Context import com.nexus.farmap.R class GetDestinationDesc { operator fun invoke(number: String, context: Context): String { val building = number[0] val floor = number[1] val room = number.drop(2) val floorStr = context.getString(R.string.floor) val roomStr = context.getString(R.string.room) return "$building, $floorStr$floor, $roomStr$room" } }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/use_cases/HitTest.kt
812868667
package com.nexus.farmap.domain.use_cases import com.nexus.farmap.domain.hit_test.HitTestResult import com.nexus.farmap.domain.hit_test.OrientatedPosition import com.google.ar.sceneform.math.Quaternion import com.google.ar.sceneform.math.Vector3 import dev.romainguy.kotlin.math.Float2 import io.github.sceneview.ar.arcore.ArFrame import io.github.sceneview.math.toFloat3 import io.github.sceneview.math.toNewQuaternion class HitTest { operator fun invoke(arFrame: ArFrame, targetPos: Float2): Result<HitTestResult> { arFrame.frame.let { frame -> val hitResult1 = frame.hitTest(targetPos.x, targetPos.y) val hitResult2 = frame.hitTest(targetPos.x - 5, targetPos.y) val hitResult3 = frame.hitTest(targetPos.x, targetPos.y + 5) if (hitResult1.isNotEmpty() && hitResult2.isNotEmpty() && hitResult3.isNotEmpty()) { val result1 = hitResult1.first() val result2 = hitResult2.first() val result3 = hitResult3.first() val pos1 = Vector3( result1.hitPose.tx(), result1.hitPose.ty(), result1.hitPose.tz() ) val pos2 = Vector3( result2.hitPose.tx(), result2.hitPose.ty(), result2.hitPose.tz() ) val pos3 = Vector3( result3.hitPose.tx(), result3.hitPose.ty(), result3.hitPose.tz() ) val vector1 = Vector3.subtract(pos1, pos2).normalized() val vector2 = Vector3.subtract(pos1, pos3).normalized() val vectorForward = Vector3.cross(vector1, vector2).normalized() vectorForward.y = 0f val orientation = Quaternion.lookRotation( vectorForward, Vector3.up() ).toNewQuaternion() val orientatedPosition = OrientatedPosition(pos1.toFloat3(), orientation) return Result.success(HitTestResult(orientatedPosition, result1)) } else { return Result.failure(Exception("Null hit result")) } } } }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/use_cases/QuaternionExtensions.kt
3751114170
package com.nexus.farmap.domain.use_cases import com.google.ar.sceneform.math.Vector3 import dev.romainguy.kotlin.math.Quaternion import dev.romainguy.kotlin.math.inverse import io.github.sceneview.math.toNewQuaternion import io.github.sceneview.math.toOldQuaternion fun Quaternion.convert(quaternion2: Quaternion): Quaternion { return this * quaternion2 } fun Quaternion.inverted(): Quaternion { return toOldQuaternion().inverted().toNewQuaternion() } fun Quaternion.opposite(): Quaternion { return inverse(this) } fun Quaternion.Companion.lookRotation(forward: Vector3, up: Vector3 = Vector3.up()): Quaternion { val rotationFromAtoB = com.google.ar.sceneform.math.Quaternion.lookRotation(forward, up) return com.google.ar.sceneform.math.Quaternion.multiply( rotationFromAtoB, com.google.ar.sceneform.math.Quaternion.axisAngle(Vector3(1.0f, 0.0f, 0.0f), 270f) ).toNewQuaternion() }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/use_cases/AnalyzeImage.kt
200799845
package com.nexus.farmap.domain.use_cases import android.media.Image import com.nexus.farmap.data.model.DetectedObjectResult import com.nexus.farmap.domain.ml.ObjectDetector class AnalyzeImage( private val objectDetector: ObjectDetector, ) { suspend operator fun invoke( image: Image, imageRotation: Int, imageCropPercentage: Pair<Int, Int>, displaySize: Pair<Int, Int> ): Result<DetectedObjectResult> { return objectDetector.analyze( image, imageRotation, imageCropPercentage, displaySize ) } }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/use_cases/SmoothPath.kt
852601568
package com.nexus.farmap.domain.use_cases import com.google.ar.sceneform.math.Quaternion.lookRotation import com.google.ar.sceneform.math.Quaternion.multiply import com.google.ar.sceneform.math.Quaternion.axisAngle import com.nexus.farmap.domain.hit_test.OrientatedPosition import com.nexus.farmap.domain.smoothing.BezierPoint import com.nexus.farmap.domain.tree.TreeNode import com.google.ar.sceneform.math.Vector3 import dev.benedikt.math.bezier.curve.BezierCurve import dev.benedikt.math.bezier.curve.Order import dev.benedikt.math.bezier.math.DoubleMathHelper import dev.benedikt.math.bezier.vector.Vector3D import dev.romainguy.kotlin.math.Float3 import dev.romainguy.kotlin.math.Quaternion import io.github.sceneview.math.toFloat3 import io.github.sceneview.math.toNewQuaternion import io.github.sceneview.math.toVector3 private const val ROUTE_STEP = 0.3f class SmoothPath { operator fun invoke( nodes: List<TreeNode> ): List<OrientatedPosition> { val list = mutableListOf<OrientatedPosition>() if (nodes.size > 3) { for (i in 1 until nodes.size - 2) { val node1 = nodes[i] val node2 = nodes[i + 1] val fromVector = node1.position.toVector3() val toVector = node2.position.toVector3() val lineLength = Vector3.subtract(fromVector, toVector).length() if (lineLength < ROUTE_STEP) { continue } val nodesAmount = (lineLength / ROUTE_STEP).toInt() val dx = (toVector.x - fromVector.x) / nodesAmount val dy = (toVector.y - fromVector.y) / nodesAmount val dz = (toVector.z - fromVector.z) / nodesAmount val difference = Vector3.subtract(toVector, fromVector) val directionFromTopToBottom = difference.normalized() val rotationFromAToB: com.google.ar.sceneform.math.Quaternion = lookRotation( directionFromTopToBottom, Vector3.up() ) val rotation = multiply( rotationFromAToB, axisAngle(Vector3(1.0f, 0.0f, 0.0f), 270f) ).toNewQuaternion() val lowStep = if (nodesAmount < 3) 0 else if (nodesAmount == 3) 1 else 2 val highStep = if (nodesAmount < 3) 1 else if (nodesAmount == 3) 2 else 3 for (j in 0..nodesAmount - highStep) { val position = Float3( fromVector.x + dx * j, fromVector.y + dy * j, fromVector.z + dz * j ) if (list.isEmpty() || i == 1) { val pos = OrientatedPosition(position, rotation) list.add(pos) } else if (j == lowStep) { list.addAll( getBezierSmoothPoints( list.removeLast().position, position, fromVector.toFloat3(), ROUTE_STEP ) ) } else if (j > lowStep) { val pos = OrientatedPosition(position, rotation) list.add(pos) } } if (i == nodes.size - 3) { for (j in nodesAmount - highStep until nodesAmount) { val position = Float3( fromVector.x + dx * j, fromVector.y + dy * j, fromVector.z + dz * j ) val pos = OrientatedPosition(position, rotation) list.add(pos) } } } } return list } private fun getBezierSmoothPoints( start: Float3, end: Float3, point: Float3, step: Float ): List<OrientatedPosition> { val curve = bezierCurve( start, end, point ) val curveLen = curve.length val rawPointsAmount = 50 val rawStep = curveLen / rawPointsAmount val rawPoints = mutableListOf<BezierPoint>() var i = 0.0 while (i < curveLen) { val t = i / curveLen val pos = curve.getCoordinatesAt(t) rawPoints.add(BezierPoint(t, pos)) i += rawStep } val endPoint = BezierPoint(1.0, curve.getCoordinatesAt(1.0)) return walkCurve(endPoint, rawPoints, step.toDouble()).map { rawPoint -> val pos = rawPoint.pos.toFloat3() val tangent = curve.getTangentAt(rawPoint.t) pos.x = pos.x tangent.y = tangent.y OrientatedPosition( rawPoint.pos.toFloat3(), Quaternion.lookRotation(curve.getTangentAt(rawPoint.t).toVector3()) ) } } private fun bezierCurve( start: Float3, end: Float3, point: Float3 ): BezierCurve<Double, Vector3D> { val curve = BezierCurve( Order.QUADRATIC, start.toVector3D(), end.toVector3D(), listOf(point.toVector3D()), 20, DoubleMathHelper() ) curve.computeLength() return curve } private fun walkCurve( end: BezierPoint, points: List<BezierPoint>, spacing: Double, offset: Double = 0.0 ): List<BezierPoint> { val result = mutableListOf<BezierPoint>() val space = if (spacing > 0.00001) spacing else 0.00001 var distanceNeeded = offset while (distanceNeeded < 0) { distanceNeeded += space } var current = points[0] var next = points[1] var i = 1 val last = points.count() - 1 while (true) { val diff = next.pos - current.pos val dist = diff.magnitude() if (dist >= distanceNeeded) { current.pos += diff * (distanceNeeded / dist) result.add(current) distanceNeeded = spacing } else if (i != last) { distanceNeeded -= dist current = next next = points[++i] } else { break } } val dist = (result.last().pos - end.pos).magnitude() if (dist < spacing / 2) { result.removeLast() result.add(end) } else { result.add(end) } return result } private fun Float3.toVector3D(): Vector3D { return Vector3D( this.x.toDouble(), this.y.toDouble(), this.z.toDouble() ) } private fun Vector3D.toFloat3(): Float3 { return Float3( this.x.toFloat(), this.y.toFloat(), this.z.toFloat() ) } private fun Vector3D.toVector3(): Vector3 { return Vector3( this.x.toFloat(), this.y.toFloat(), this.z.toFloat() ) } }
nexus-farmap/app/src/main/java/com/nexus/farmap/domain/use_cases/FindWay.kt
352211757
package com.nexus.farmap.domain.use_cases import com.nexus.farmap.domain.pathfinding.Path import com.nexus.farmap.domain.pathfinding.Pathfinder import com.nexus.farmap.domain.tree.Tree class FindWay( private val pathfinder: Pathfinder ) { suspend operator fun invoke( from: String, to: String, tree: Tree ): Path? { return pathfinder.findWay(from, to, tree) } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/MainActivity.kt
2753884513
package com.nexus.farmap.presentation import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.nexus.farmap.R import com.nexus.farmap.data.ml.classification.ARCoreSessionLifecycleHelper import com.google.ar.core.CameraConfig import com.google.ar.core.CameraConfigFilter import com.google.ar.core.Config class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val arCoreSessionHelper = ARCoreSessionLifecycleHelper(this) arCoreSessionHelper.beforeSessionResume = { session -> session.configure(session.config.apply { // To get the best image of the object in question, enable autofocus. focusMode = Config.FocusMode.AUTO if (session.isDepthModeSupported(Config.DepthMode.AUTOMATIC)) { depthMode = Config.DepthMode.AUTOMATIC } }) val filter = CameraConfigFilter(session).setFacingDirection(CameraConfig.FacingDirection.BACK) val configs = session.getSupportedCameraConfigs(filter) val sort = compareByDescending<CameraConfig> { it.imageSize.width }.thenByDescending { it.imageSize.height } session.cameraConfig = configs.sortedWith(sort)[0] } } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/LabelObject.kt
3468524420
package com.nexus.farmap.presentation import com.nexus.farmap.domain.hit_test.OrientatedPosition import com.google.ar.core.Anchor import io.github.sceneview.ar.node.ArNode data class LabelObject( val label: String, val pos: OrientatedPosition, var node: ArNode? = null, var anchor: Anchor? = null )
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/confirmer/ConfirmFragment.kt
3710963181
package com.nexus.farmap.presentation.confirmer import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.OnBackPressedCallback import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.nexus.farmap.databinding.FragmentConfirmBinding import com.nexus.farmap.presentation.preview.MainEvent import com.nexus.farmap.presentation.preview.MainShareModel import com.nexus.farmap.presentation.preview.MainUiEvent import kotlinx.coroutines.launch class ConfirmFragment : Fragment() { private val mainModel: MainShareModel by activityViewModels() private var _binding: FragmentConfirmBinding? = null private val binding get() = _binding!! private val args: ConfirmFragmentArgs by navArgs() private val confType by lazy { args.confirmType } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val callback: OnBackPressedCallback = object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { mainModel.onEvent(MainEvent.RejectConfObject(confType)) findNavController().popBackStack() } } requireActivity().onBackPressedDispatcher.addCallback(this, callback) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentConfirmBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { setEnabled(true) binding.acceptButton.setOnClickListener { setEnabled(false) mainModel.onEvent(MainEvent.AcceptConfObject(confType)) } binding.rejectButton.setOnClickListener { setEnabled(false) mainModel.onEvent(MainEvent.RejectConfObject(confType)) findNavController().popBackStack() } viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { mainModel.mainUiEvents.collect { uiEvent -> when (uiEvent) { is MainUiEvent.InitSuccess -> { val action = ConfirmFragmentDirections.actionConfirmFragmentToRouterFragment() findNavController().navigate(action) } is MainUiEvent.InitFailed -> { findNavController().popBackStack() } is MainUiEvent.EntryCreated -> { val action = ConfirmFragmentDirections.actionConfirmFragmentToRouterFragment() findNavController().navigate(action) } is MainUiEvent.EntryAlreadyExists -> { val action = ConfirmFragmentDirections.actionConfirmFragmentToRouterFragment() findNavController().navigate(action) } else -> {} } } } } } private fun setEnabled(enabled: Boolean) { binding.acceptButton.isEnabled = enabled binding.rejectButton.isEnabled = enabled } companion object { const val CONFIRM_INITIALIZE = 0 const val CONFIRM_ENTRY = 1 } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/search/adapters/EntriesAdapter.kt
4245969851
package com.nexus.farmap.presentation.search.adapters import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.nexus.farmap.R class EntriesAdapter( private val onItemClick: (String) -> Unit ) : ListAdapter<EntryItem, EntriesAdapter.ItemViewholder>(DiffCallback()) { private var rawList = listOf<EntryItem>() private var filter: String = "" override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewholder { return ItemViewholder( onItemClick, LayoutInflater.from(parent.context).inflate(R.layout.entry_item, parent, false) ) } override fun onBindViewHolder(holder: ItemViewholder, position: Int) { holder.bind(getItem(position)) } class ItemViewholder(private val onItemClick: (String) -> Unit, itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(item: EntryItem) = with(itemView) { val textView: TextView = this.findViewById(R.id.entry_number) val descTextView: TextView = this.findViewById(R.id.description_text) textView.text = item.number descTextView.text = item.description setOnClickListener { onItemClick(item.number) } } } fun changeList(entries: List<EntryItem>) { rawList = entries filter = "" submitList(rawList) } fun applyFilter(filter: String) { this.filter = filter submitList(rawList.filter { it.number.startsWith(filter) }.sortedBy { it.number.length }) } } class DiffCallback : DiffUtil.ItemCallback<EntryItem>() { override fun areItemsTheSame(oldItem: EntryItem, newItem: EntryItem): Boolean { return oldItem.number == newItem.number } override fun areContentsTheSame(oldItem: EntryItem, newItem: EntryItem): Boolean { return oldItem == newItem } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/search/adapters/EntryItem.kt
1746303821
package com.nexus.farmap.presentation.search.adapters data class EntryItem( val number: String, val description: String )
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/search/SearchFragment.kt
1214577843
package com.nexus.farmap.presentation.search import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo import androidx.activity.OnBackPressedCallback import androidx.core.widget.doOnTextChanged import androidx.fragment.app.activityViewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.LinearLayoutManager import com.nexus.farmap.R import com.nexus.farmap.data.App import com.nexus.farmap.databinding.FragmentSearchBinding import com.nexus.farmap.presentation.search.adapters.EntriesAdapter import com.nexus.farmap.presentation.search.adapters.EntryItem import com.nexus.farmap.presentation.common.helpers.viewHideInput import com.nexus.farmap.presentation.common.helpers.viewRequestInput import com.nexus.farmap.presentation.preview.MainEvent import com.nexus.farmap.presentation.preview.MainShareModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class SearchFragment : Fragment() { private val destinationDesc = App.instance!!.getDestinationDesc private val mainModel: MainShareModel by activityViewModels() private var _binding: FragmentSearchBinding? = null private val binding get() = _binding!! private val adapter = EntriesAdapter { number -> processSearchResult(number) } private val args: SearchFragmentArgs by navArgs() val changeType by lazy { args.changeType } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val callback: OnBackPressedCallback = object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { findNavController().popBackStack() } } requireActivity().onBackPressedDispatcher.addCallback(this, callback) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentSearchBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { with(binding.searchInput) { doOnTextChanged { text, _, _, _ -> adapter.applyFilter(text.toString()) } setOnEditorActionListener { v, actionId, event -> var handled = false if (actionId == EditorInfo.IME_ACTION_SEARCH) { processSearchResult(text.toString()) handled = true } handled } binding.searchLayout.hint = if (changeType == TYPE_END) getString(R.string.to) else getString(R.string.from) } binding.entryRecyclerView.adapter = adapter binding.entryRecyclerView.layoutManager = LinearLayoutManager( requireActivity().applicationContext ) var entriesList = listOf<EntryItem>() viewLifecycleOwner.lifecycleScope.launch { withContext(Dispatchers.IO) { entriesList = mainModel.entriesNumber.map { number -> EntryItem(number, destinationDesc(number, requireActivity().applicationContext)) } } adapter.changeList(entriesList) } binding.searchInput.viewRequestInput() viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { mainModel.searchUiEvents.collectLatest { uiEvent -> when (uiEvent) { is SearchUiEvent.SearchSuccess -> { binding.searchLayout.error = null binding.searchInput.viewHideInput() findNavController().popBackStack() } is SearchUiEvent.SearchInvalid -> { binding.searchLayout.error = resources.getString(R.string.incorrect_number) binding.searchInput.viewRequestInput() } } } } } } private fun processSearchResult(number: String) { mainModel.onEvent(MainEvent.TrySearch(number, changeType)) } companion object { const val TYPE_START = 0 const val TYPE_END = 1 } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/search/SearchUiEvent.kt
587209771
package com.nexus.farmap.presentation.search sealed class SearchUiEvent { object SearchSuccess : SearchUiEvent() object SearchInvalid : SearchUiEvent() }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/common/helpers/InputFunctions.kt
677422124
package com.nexus.farmap.presentation.common.helpers import android.content.Context import android.view.View import android.view.inputmethod.InputMethodManager fun View.viewRequestInput() { viewHideInput() isActivated = true val hasFocus = requestFocus() hasFocus.let { val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.showSoftInput(this, 0) } } fun View.viewHideInput() { val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(this.windowToken, 0) }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/common/helpers/DisplayRotationHelper.kt
628908911
package com.nexus.farmap.presentation.common.helpers import android.content.Context import android.hardware.camera2.CameraAccessException import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.CameraManager import android.hardware.display.DisplayManager import android.hardware.display.DisplayManager.DisplayListener import android.view.Display import android.view.Surface import android.view.WindowManager import com.google.ar.core.Session /** * Helper to track the display rotations. In particular, the 180 degree rotations are not notified * by the onSurfaceChanged() callback, and thus they require listening to the android display * events. */ class DisplayRotationHelper(context: Context) : DisplayListener { private var viewportChanged = false private var viewportWidth = 0 private var viewportHeight = 0 private val display: Display private val displayManager: DisplayManager private val cameraManager: CameraManager /** Registers the display listener. Should be called from [Activity.onResume]. */ fun onResume() { displayManager.registerDisplayListener(this, null) } /** Unregisters the display listener. Should be called from [Activity.onPause]. */ fun onPause() { displayManager.unregisterDisplayListener(this) } /** * Records a change in surface dimensions. This will be later used by [ ][.updateSessionIfNeeded]. Should be called from [ ]. * * @param width the updated width of the surface. * @param height the updated height of the surface. */ fun onSurfaceChanged(width: Int, height: Int) { viewportWidth = width viewportHeight = height viewportChanged = true } /** * Updates the session display geometry if a change was posted either by [ ][.onSurfaceChanged] call or by [.onDisplayChanged] system callback. This * function should be called explicitly before each call to [Session.update]. This * function will also clear the 'pending update' (viewportChanged) flag. * * @param session the [Session] object to update if display geometry changed. */ fun updateSessionIfNeeded(session: Session) { if (viewportChanged) { val displayRotation = display.rotation session.setDisplayGeometry(displayRotation, viewportWidth, viewportHeight) viewportChanged = false } } /** * Returns the aspect ratio of the GL surface viewport while accounting for the display rotation * relative to the device camera sensor orientation. */ fun getCameraSensorRelativeViewportAspectRatio(cameraId: String?): Float { val aspectRatio: Float val cameraSensorToDisplayRotation = getCameraSensorToDisplayRotation(cameraId) aspectRatio = when (cameraSensorToDisplayRotation) { 90, 270 -> viewportHeight.toFloat() / viewportWidth.toFloat() 0, 180 -> viewportWidth.toFloat() / viewportHeight.toFloat() else -> throw RuntimeException("Unhandled rotation: $cameraSensorToDisplayRotation") } return aspectRatio } /** * Returns the rotation of the back-facing camera with respect to the display. The value is one of * 0, 90, 180, 270. */ fun getCameraSensorToDisplayRotation(cameraId: String?): Int { val characteristics: CameraCharacteristics characteristics = try { cameraManager.getCameraCharacteristics(cameraId!!) } catch (e: CameraAccessException) { throw RuntimeException("Unable to determine display orientation", e) } // Camera sensor orientation. val sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION)!! // Current display orientation. val displayOrientation = toDegrees(display.rotation) // Make sure we return 0, 90, 180, or 270 degrees. return (sensorOrientation - displayOrientation + 360) % 360 } private fun toDegrees(rotation: Int): Int { return when (rotation) { Surface.ROTATION_0 -> 0 Surface.ROTATION_90 -> 90 Surface.ROTATION_180 -> 180 Surface.ROTATION_270 -> 270 else -> throw RuntimeException("Unknown rotation $rotation") } } override fun onDisplayAdded(displayId: Int) {} override fun onDisplayRemoved(displayId: Int) {} override fun onDisplayChanged(displayId: Int) { viewportChanged = true } /** * Constructs the DisplayRotationHelper but does not register the listener yet. * * @param context the Android [Context]. */ init { displayManager = context.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager display = windowManager.defaultDisplay } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/common/helpers/DrawerHelper.kt
1092554644
package com.nexus.farmap.presentation.common.helpers import android.graphics.Color import android.widget.TextView import androidx.cardview.widget.CardView import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import com.nexus.farmap.R import com.nexus.farmap.domain.hit_test.OrientatedPosition import com.nexus.farmap.domain.tree.TreeNode import com.google.ar.core.Anchor import com.google.ar.sceneform.math.Quaternion import com.google.ar.sceneform.math.Vector3 import com.google.ar.sceneform.rendering.* import com.uchuhimo.collections.MutableBiMap import io.github.sceneview.ar.ArSceneView import io.github.sceneview.ar.node.ArNode import io.github.sceneview.ar.scene.destroy import io.github.sceneview.math.Position import io.github.sceneview.math.Scale import io.github.sceneview.math.toNewQuaternion import io.github.sceneview.math.toVector3 import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.future.await import kotlinx.coroutines.launch class DrawerHelper( private val fragment: Fragment, ) { private var labelScale = Scale(0.15f, 0.075f, 0.15f) private var arrowScale = Scale(0.5f, 0.5f, 0.5f) private var labelAnimationDelay = 2L private var arrowAnimationDelay = 2L private var labelAnimationPart = 10 private var arrowAnimationPart = 15 private val animationJobs = mutableMapOf<ArNode, Job>() suspend fun drawNode( treeNode: TreeNode, surfaceView: ArSceneView, anchor: Anchor? = null ): ArNode { return when (treeNode) { is TreeNode.Path -> { drawPath(treeNode, surfaceView, anchor) } is TreeNode.Entry -> { drawEntry(treeNode, surfaceView, anchor) } } } suspend fun removeLink( pair: Pair<ArNode, ArNode>, modelsToLinkModels: MutableBiMap<Pair<ArNode, ArNode>, ArNode> ) { modelsToLinkModels[pair]?.destroy() modelsToLinkModels.remove(pair) } private suspend fun drawPath( treeNode: TreeNode.Path, surfaceView: ArSceneView, anchor: Anchor? = null ): ArNode { val modelNode = ArNode() modelNode.loadModel( context = fragment.requireContext(), glbFileLocation = "models/nexus.glb", ) modelNode.position = treeNode.position modelNode.modelScale = Scale(0.1f) if (anchor != null) { modelNode.anchor = anchor } else { modelNode.anchor = modelNode.createAnchor() } modelNode.model?.let { it.isShadowCaster = false it.isShadowReceiver = false } surfaceView.addChild(modelNode) return modelNode } private suspend fun drawEntry( treeNode: TreeNode.Entry, surfaceView: ArSceneView, anchor: Anchor? = null ): ArNode { return placeLabel( treeNode.number, OrientatedPosition(treeNode.position, treeNode.forwardVector), surfaceView ) } suspend fun placeLabel( label: String, pos: OrientatedPosition, surfaceView: ArSceneView, anchor: Anchor? = null ): ArNode = placeRend( label = label, pos = pos, surfaceView = surfaceView, scale = labelScale, anchor = anchor ) suspend fun placeArrow( pos: OrientatedPosition, surfaceView: ArSceneView ): ArNode = placeRend( pos = pos, surfaceView = surfaceView, scale = arrowScale ) private suspend fun placeRend( label: String? = null, pos: OrientatedPosition, surfaceView: ArSceneView, scale: Scale, anchor: Anchor? = null ): ArNode { var node: ArNode? = null ViewRenderable.builder() .setView(fragment.requireContext(), if (label != null) R.layout.text_sign else R.layout.route_node) .setSizer { Vector3(0f, 0f, 0f) }.setVerticalAlignment(ViewRenderable.VerticalAlignment.CENTER) .setHorizontalAlignment(ViewRenderable.HorizontalAlignment.CENTER).build() .thenAccept { renderable: ViewRenderable -> renderable.let { it.isShadowCaster = false it.isShadowReceiver = false } if (label != null) { val cardView = renderable.view as CardView val textView: TextView = cardView.findViewById(R.id.signTextView) textView.text = label } val textNode = ArNode().apply { setModel( renderable = renderable ) model position = Position(pos.position.x, pos.position.y, pos.position.z) quaternion = pos.orientation if (anchor != null) { this.anchor = anchor } else { this.anchor = this.createAnchor() } } surfaceView.addChild(textNode) node = textNode textNode.animateViewAppear( scale, if (label != null) labelAnimationDelay else arrowAnimationDelay, if (label != null) labelAnimationPart else arrowAnimationPart ) }.await() return node!! } fun removeNode(node: ArNode) { node.destroy() node.anchor?.destroy() animationJobs[node]?.cancel() } fun removeArrowWithAnim(node: ArNode) { node.model as ViewRenderable? ?: throw Exception("No view renderable") node.animateViewDisappear(arrowScale, arrowAnimationDelay, arrowAnimationPart) } fun drawLine( from: ArNode, to: ArNode, modelsToLinkModels: MutableBiMap<Pair<ArNode, ArNode>, ArNode>, surfaceView: ArSceneView ) { val fromVector = from.position.toVector3() val toVector = to.position.toVector3() // Compute a line's length val lineLength = Vector3.subtract(fromVector, toVector).length() // Prepare a color val colorOrange = Color(Color.parseColor("#ffffff")) // 1. make a material by the color MaterialFactory.makeOpaqueWithColor(fragment.requireContext(), colorOrange).thenAccept { material: Material? -> // 2. make a model by the material val model = ShapeFactory.makeCylinder( 0.01f, lineLength, Vector3(0f, lineLength / 2, 0f), material ) model.isShadowCaster = false model.isShadowReceiver = false // 3. make node val node = ArNode() node.setModel(model) node.parent = from surfaceView.addChild(node) // 4. set rotation val difference = Vector3.subtract(toVector, fromVector) val directionFromTopToBottom = difference.normalized() val rotationFromAToB: Quaternion = Quaternion.lookRotation( directionFromTopToBottom, Vector3.up() ) val rotation = Quaternion.multiply( rotationFromAToB, Quaternion.axisAngle(Vector3(1.0f, 0.0f, 0.0f), 270f) ) node.modelQuaternion = rotation.toNewQuaternion() node.position = from.position modelsToLinkModels[Pair(from, to)] = node } } private fun ArNode.animateViewAppear(targetScale: Scale, delay: Long, part: Int) { animateView(true, targetScale, delay, part, end = null) } private fun ArNode.animateViewDisappear(targetScale: Scale, delay: Long, part: Int) { animateView(false, targetScale, delay, part) { removeNode(it) } } private fun ArNode.animateView( appear: Boolean, targetScale: Scale, delay: Long, part: Int, end: ((ArNode) -> Unit)? ) { val renderable = this.model as ViewRenderable? ?: throw Exception("No view renderable") var size = renderable.sizer.getSize(renderable.view) val xPart = targetScale.x / part val yPart = targetScale.y / part val zPart = targetScale.z / part animationJobs[this]?.cancel() animationJobs[this] = fragment.viewLifecycleOwner.lifecycleScope.launch { while (true) { if (size.x >= targetScale.toVector3().x && appear) { break } else if (size.x <= 0 && !appear) { break } renderable.sizer = ViewSizer { if (appear) size.addConst(xPart, yPart, zPart) else size.addConst(xPart, yPart, zPart, -1) } delay(delay) size = renderable.sizer.getSize(renderable.view) } if (end != null) { end(this@animateView) } } } private fun Vector3.addConst(xValue: Float, yValue: Float, zValue: Float, modifier: Int = 1): Vector3 { return Vector3( x + xValue * modifier, y + yValue * modifier, z + zValue * modifier ) } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/preview/MainUiEvent.kt
2290684724
package com.nexus.farmap.presentation.preview import com.nexus.farmap.domain.tree.TreeNode import com.google.ar.core.Anchor sealed interface MainUiEvent { object InitSuccess : MainUiEvent object InitFailed : MainUiEvent object PathNotFound : MainUiEvent object EntryAlreadyExists : MainUiEvent object EntryCreated : MainUiEvent class NodeCreated(val treeNode: TreeNode, val anchor: Anchor? = null) : MainUiEvent class LinkCreated(val node1: TreeNode, val node2: TreeNode) : MainUiEvent class NodeDeleted(val node: TreeNode) : MainUiEvent }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/preview/MainShareModel.kt
263953695
package com.nexus.farmap.presentation.preview import android.annotation.SuppressLint import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.nexus.farmap.data.App import com.nexus.farmap.domain.hit_test.HitTestResult import com.nexus.farmap.domain.tree.TreeNode import com.nexus.farmap.presentation.LabelObject import com.nexus.farmap.presentation.confirmer.ConfirmFragment import com.nexus.farmap.presentation.preview.state.PathState import com.nexus.farmap.presentation.search.SearchFragment import com.nexus.farmap.presentation.search.SearchUiEvent import dev.romainguy.kotlin.math.Float3 import dev.romainguy.kotlin.math.Quaternion import io.github.sceneview.ar.arcore.ArFrame import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class MainShareModel : ViewModel() { private val findWay = App.instance!!.findWay private var _pathState = MutableStateFlow(PathState()) val pathState = _pathState.asStateFlow() private var _frame = MutableStateFlow<ArFrame?>(null) val frame = _frame.asStateFlow() private var _mainUiEvents = MutableSharedFlow<MainUiEvent>() val mainUiEvents = _mainUiEvents.asSharedFlow() private var _searchUiEvents = MutableSharedFlow<SearchUiEvent>() val searchUiEvents = _searchUiEvents.asSharedFlow() @SuppressLint("StaticFieldLeak") private var _confirmationObject = MutableStateFlow<LabelObject?>(null) val confirmationObject = _confirmationObject.asStateFlow() private var _selectedNode = MutableStateFlow<TreeNode?>(null) val selectedNode = _selectedNode.asStateFlow() private var _linkPlacementMode = MutableStateFlow(false) val linkPlacementMode = _linkPlacementMode.asStateFlow() private var tree = App.instance!!.getTree() val treeDiffUtils = tree.diffUtils val entriesNumber = tree.getEntriesNumbers() private var pathfindJob: Job? = null init { preload() } fun onEvent(event: MainEvent) { when (event) { is MainEvent.NewFrame -> { viewModelScope.launch { _frame.emit(event.frame) } } is MainEvent.NewConfirmationObject -> { _confirmationObject.update { event.confObject } } is MainEvent.TrySearch -> { viewModelScope.launch { processSearch(event.number, event.changeType) } } is MainEvent.AcceptConfObject -> { when (event.confirmType) { ConfirmFragment.CONFIRM_INITIALIZE -> { viewModelScope.launch { _confirmationObject.value?.let { initialize( it.label, it.pos.position, it.pos.orientation ) _confirmationObject.update { null } } } } ConfirmFragment.CONFIRM_ENTRY -> { viewModelScope.launch { _confirmationObject.value?.let { createNode( number = it.label, position = it.pos.position, orientation = it.pos.orientation ) _confirmationObject.update { null } } } } } } is MainEvent.RejectConfObject -> { viewModelScope.launch { _confirmationObject.update { null } } } is MainEvent.NewSelectedNode -> { viewModelScope.launch { _selectedNode.update { event.node } } } is MainEvent.ChangeLinkMode -> { viewModelScope.launch { _linkPlacementMode.update { !linkPlacementMode.value } } } is MainEvent.CreateNode -> { viewModelScope.launch { createNode( number = event.number, position = event.position, orientation = event.orientation, hitTestResult = event.hitTestResult ) } } is MainEvent.LinkNodes -> { viewModelScope.launch { linkNodes(event.node1, event.node2) } } is MainEvent.DeleteNode -> { viewModelScope.launch { removeNode(event.node) } } } } private suspend fun processSearch(number: String, changeType: Int) { val entry = tree.getEntry(number) if (entry == null) { _searchUiEvents.emit(SearchUiEvent.SearchInvalid) return } else { if (changeType == SearchFragment.TYPE_START) { val endEntry = pathState.value.endEntry _pathState.update { PathState( startEntry = entry, endEntry = if (entry.number == endEntry?.number) null else endEntry ) } } else { val startEntry = pathState.value.startEntry _pathState.update { PathState( startEntry = if (entry.number == startEntry?.number) null else startEntry, endEntry = entry ) } } //Search successes pathfindJob?.cancel() pathfindJob = viewModelScope.launch { pathfind() } _searchUiEvents.emit(SearchUiEvent.SearchSuccess) } } private suspend fun pathfind() { val from = pathState.value.startEntry?.number ?: return val to = pathState.value.endEntry?.number ?: return if (tree.getEntry(from) != null && tree.getEntry(to) != null) { val path = findWay(from, to, tree) if (path != null) { _pathState.update { it.copy( path = path ) } } else { _mainUiEvents.emit(MainUiEvent.PathNotFound) } } else { throw Exception("Unknown tree nodes") } } private suspend fun createNode( number: String? = null, position: Float3? = null, orientation: Quaternion? = null, hitTestResult: HitTestResult? = null, ) { if (position == null && hitTestResult == null) { throw Exception("No position was provided") } if (number != null && tree.hasEntry(number)) { _mainUiEvents.emit(MainUiEvent.EntryAlreadyExists) return } val treeNode = tree.addNode( position ?: hitTestResult!!.orientatedPosition.position, number, orientation ) treeNode.let { if (number != null) { _mainUiEvents.emit(MainUiEvent.EntryCreated) } _mainUiEvents.emit( MainUiEvent.NodeCreated( treeNode, hitTestResult?.hitResult?.createAnchor() ) ) } } private suspend fun linkNodes(node1: TreeNode, node2: TreeNode) { if (tree.addLink(node1, node2)) { _linkPlacementMode.update { false } _mainUiEvents.emit(MainUiEvent.LinkCreated(node1, node2)) } } private suspend fun removeNode(node: TreeNode) { tree.removeNode(node) _mainUiEvents.emit(MainUiEvent.NodeDeleted(node)) if (node == selectedNode.value) { _selectedNode.update { null } } if (node == pathState.value.endEntry) { _pathState.update { it.copy(endEntry = null, path = null) } } else if (node == pathState.value.startEntry) { _pathState.update { it.copy(startEntry = null, path = null) } } } private suspend fun initialize(entryNumber: String, position: Float3, newOrientation: Quaternion): Boolean { var result: Result<Unit?> withContext(Dispatchers.IO) { result = tree.initialize(entryNumber, position, newOrientation) } if (result.isFailure) { _mainUiEvents.emit(MainUiEvent.InitFailed) return false } _mainUiEvents.emit(MainUiEvent.InitSuccess) val entry = tree.getEntry(entryNumber) if (entry != null) { _pathState.update { PathState( startEntry = entry ) } } else { _pathState.update { PathState() } } return true } private fun preload() { viewModelScope.launch { tree.preload() } } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/preview/state/PathState.kt
3782352864
package com.nexus.farmap.presentation.preview.state import com.nexus.farmap.domain.pathfinding.Path import com.nexus.farmap.domain.tree.TreeNode data class PathState( val startEntry: TreeNode.Entry? = null, val endEntry: TreeNode.Entry? = null, val path: Path? = null )
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/preview/PreviewFragment.kt
4123906793
package com.nexus.farmap.presentation.preview import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import com.nexus.farmap.R import com.nexus.farmap.data.App import com.nexus.farmap.databinding.FragmentPreviewBinding import com.nexus.farmap.domain.tree.TreeNode import com.nexus.farmap.presentation.LabelObject import com.nexus.farmap.presentation.common.helpers.DrawerHelper import com.nexus.farmap.presentation.preview.nodes_adapters.PathAdapter import com.nexus.farmap.presentation.preview.nodes_adapters.TreeAdapter import com.nexus.farmap.presentation.preview.state.PathState import com.nexus.farmap.presentation.preview.MainShareModel import com.nexus.farmap.presentation.preview.MainUiEvent import com.nexus.farmap.presentation.preview.MainEvent import com.google.android.material.snackbar.Snackbar import com.google.ar.core.TrackingState import com.google.ar.core.exceptions.* import com.uchuhimo.collections.MutableBiMap import com.uchuhimo.collections.mutableBiMapOf import dev.romainguy.kotlin.math.Float3 import io.github.sceneview.ar.arcore.ArFrame import io.github.sceneview.ar.node.ArNode import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch class PreviewFragment : Fragment() { private val mainModel: MainShareModel by activityViewModels() private var _binding: FragmentPreviewBinding? = null private val binding get() = _binding!! private val drawerHelper = DrawerHelper(this) private var endPlacingJob: Job? = null private var startPlacingJob: Job? = null private var wayBuildingJob: Job? = null private var treeBuildingJob: Job? = null private var currentPathState: PathState? = null private var lastPositionTime = 0L private lateinit var pathAdapter: PathAdapter private lateinit var treeAdapter: TreeAdapter private var lastConfObject: LabelObject? = null private var confObjectJob: Job? = null private val treeNodesToModels: MutableBiMap<TreeNode, ArNode> = mutableBiMapOf() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentPreviewBinding.inflate(inflater, container, false) return binding.root } override fun onResume() { super.onResume() binding.sceneView.onResume(this) } override fun onPause() { super.onPause() binding.sceneView.onPause(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { //TODO process pause and resume pathAdapter = PathAdapter( drawerHelper, binding.sceneView, VIEWABLE_PATH_NODES, viewLifecycleOwner.lifecycleScope ) treeAdapter = TreeAdapter( drawerHelper, binding.sceneView, DEFAULT_BUFFER_SIZE, viewLifecycleOwner.lifecycleScope ) binding.sceneView.apply { planeRenderer.isVisible = true instructions.enabled = false onArFrame = { frame -> onDrawFrame(frame) } onTouch = { node, _ -> if (App.mode == App.ADMIN_MODE) { node?.let { it -> if (!mainModel.linkPlacementMode.value) { selectNode(it as ArNode) } else { val treeNode = mainModel.selectedNode.value treeAdapter.getArNode(treeNode)?.let { node1 -> linkNodes(node1, it as ArNode) } } } } true } onArSessionFailed = { exception -> val message = when (exception) { is UnavailableArcoreNotInstalledException, is UnavailableUserDeclinedInstallationException -> getString( R.string.install_arcode ) is UnavailableApkTooOldException -> getString(R.string.update_arcode) is UnavailableSdkTooOldException -> getString(R.string.update_app) is UnavailableDeviceNotCompatibleException -> getString(R.string.no_arcore_support) is CameraNotAvailableException -> getString(R.string.camera_not_available) is SecurityException -> getString(R.string.provide_camera_permission) else -> getString(R.string.failed_to_create_session) } Toast.makeText(requireContext(), message, Toast.LENGTH_LONG).show() } } selectNode(null) viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { mainModel.pathState.collectLatest { pathState -> //All entry labels are drawn automatically in ADMIN_MODE. if (currentPathState?.endEntry != pathState.endEntry) { endPlacingJob?.cancel() currentPathState?.endEntry?.let { end -> treeNodesToModels[end]?.let { drawerHelper.removeNode(it) } } endPlacingJob = viewLifecycleOwner.lifecycleScope.launch { pathState.endEntry?.let { end -> treeNodesToModels[end] = drawerHelper.drawNode( end, binding.sceneView, ) } } } if (currentPathState?.startEntry != pathState.startEntry) { startPlacingJob?.cancel() currentPathState?.startEntry?.let { start -> treeNodesToModels[start]?.let { drawerHelper.removeNode(it) } } startPlacingJob = viewLifecycleOwner.lifecycleScope.launch { pathState.startEntry?.let { start -> treeNodesToModels[start] = drawerHelper.drawNode( start, binding.sceneView, ) } } } currentPathState = pathState } } } viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { mainModel.mainUiEvents.collectLatest { uiEvent -> when (uiEvent) { is MainUiEvent.InitFailed -> { showSnackbar(getString(R.string.init_failed)) } is MainUiEvent.NodeCreated -> { showSnackbar(getString(R.string.node_created)) } is MainUiEvent.LinkCreated -> { viewLifecycleOwner.lifecycleScope.launch { treeAdapter.createLink(uiEvent.node1, uiEvent.node2) showSnackbar(getString(R.string.link_created)) } } is MainUiEvent.NodeDeleted -> { showSnackbar(getString(R.string.node_deleted)) } is MainUiEvent.PathNotFound -> { showSnackbar(getString(R.string.no_path)) } is MainUiEvent.EntryAlreadyExists -> { showSnackbar(getString(R.string.entry_already_exists)) } else -> {} } } } } viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { mainModel.confirmationObject.collectLatest { confObject -> confObjectJob?.cancel() confObjectJob = viewLifecycleOwner.lifecycleScope.launch { lastConfObject?.node?.let { drawerHelper.removeNode(it) } confObject?.let { it.node = drawerHelper.placeLabel( confObject.label, confObject.pos, binding.sceneView ) lastConfObject = it } } } } } } private fun onDrawFrame(frame: ArFrame) { val camera = frame.camera // Handle tracking failures. if (camera.trackingState != TrackingState.TRACKING) { return } mainModel.onEvent( MainEvent.NewFrame(frame) ) val userPos = Float3( frame.camera.displayOrientedPose.tx(), frame.camera.displayOrientedPose.ty(), frame.camera.displayOrientedPose.tz() ) if (System.currentTimeMillis() - lastPositionTime > POSITION_DETECT_DELAY) { lastPositionTime = System.currentTimeMillis() changeViewablePath(userPos) if (App.mode == App.ADMIN_MODE) { changeViewableTree(userPos) mainModel.selectedNode.value?.let { node -> checkSelectedNode(node) } } } } private fun selectNode(node: ArNode?) { // User selected entry can be stored in PreviewFragment nodes map, // if this node displayed as PathState start or end val treeNode = treeNodesToModels.inverse[node] ?: treeAdapter.getTreeNode(node) mainModel.onEvent(MainEvent.NewSelectedNode(treeNode)) } private fun checkSelectedNode(treeNode: TreeNode) { if (treeAdapter.getArNode(treeNode) == null) { mainModel.onEvent(MainEvent.NewSelectedNode(null)) } } private fun linkNodes(node1: ArNode, node2: ArNode) { viewLifecycleOwner.lifecycleScope.launch { val path1: TreeNode? = treeAdapter.getTreeNode(node1) val path2: TreeNode? = treeAdapter.getTreeNode(node2) if (path1 != null && path2 != null) { mainModel.onEvent(MainEvent.LinkNodes(path1, path2)) } } } private fun changeViewablePath(userPosition: Float3) { wayBuildingJob?.cancel() wayBuildingJob = viewLifecycleOwner.lifecycleScope.launch(Dispatchers.Default) { val nodes = currentPathState?.path?.getNearNodes( number = VIEWABLE_PATH_NODES, position = userPosition ) pathAdapter.commit(nodes ?: listOf()) } } //ONLY FOR ADMIN MODE private fun changeViewableTree(userPosition: Float3) { if (treeBuildingJob?.isCompleted == true || treeBuildingJob?.isCancelled == true || treeBuildingJob == null) { treeBuildingJob?.cancel() treeBuildingJob = viewLifecycleOwner.lifecycleScope.launch(Dispatchers.Default) { val nodes = mainModel.treeDiffUtils.getNearNodes( radius = VIEWABLE_ADMIN_NODES, position = userPosition ) treeAdapter.commit(nodes) } } } private fun showSnackbar(message: String) { Snackbar.make(binding.sceneView, message, Snackbar.LENGTH_SHORT).show() } companion object { //How many path nodes will be displayed at the moment const val VIEWABLE_PATH_NODES = 32 //Distance of viewable nodes for admin mode const val VIEWABLE_ADMIN_NODES = 8f //How often the check for path and tree redraw will be in millisecond const val POSITION_DETECT_DELAY = 100L //Image crop percentage for recognition val DESIRED_CROP = Pair(0, 0) } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/preview/nodes_adapters/PathAdapter.kt
3658976602
package com.nexus.farmap.presentation.preview.nodes_adapters import androidx.lifecycle.LifecycleCoroutineScope import com.nexus.farmap.domain.hit_test.OrientatedPosition import com.nexus.farmap.presentation.common.helpers.DrawerHelper import io.github.sceneview.ar.ArSceneView import io.github.sceneview.ar.node.ArNode class PathAdapter( drawerHelper: DrawerHelper, previewView: ArSceneView, bufferSize: Int, scope: LifecycleCoroutineScope, ) : NodesAdapter<OrientatedPosition>(drawerHelper, previewView, bufferSize, scope) { override suspend fun onInserted(item: OrientatedPosition): ArNode = drawerHelper.placeArrow(item, previewView) override suspend fun onRemoved(item: OrientatedPosition, node: ArNode) = drawerHelper.removeArrowWithAnim(node) }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/preview/nodes_adapters/NodesAdapter.kt
632047783
package com.nexus.farmap.presentation.preview.nodes_adapters import androidx.lifecycle.LifecycleCoroutineScope import com.nexus.farmap.presentation.common.helpers.DrawerHelper import io.github.sceneview.ar.ArSceneView import io.github.sceneview.ar.node.ArNode import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.withContext abstract class NodesAdapter<T>( val drawerHelper: DrawerHelper, val previewView: ArSceneView, bufferSize: Int, scope: LifecycleCoroutineScope ) { protected val nodes = mutableMapOf<T, ArNode>() private val changesFlow = MutableSharedFlow<DiffOperation<T>>( replay = 0, extraBufferCapacity = bufferSize, onBufferOverflow = BufferOverflow.DROP_OLDEST ) init { scope.launchWhenStarted { changesFlow.collect { change -> when (change) { is DiffOperation.Deleted -> { nodes[change.item]?.let { nodes.remove(change.item) onRemoved(change.item, it) } } is DiffOperation.Added -> { if (nodes[change.item] == null) { nodes[change.item] = onInserted(change.item) } } } } } } suspend fun commit(newList: List<T>) { calculateChanges(newList) } private suspend fun calculateChanges(newList: List<T>) = withContext(Dispatchers.Default) { nodes.keys.asSequence().minus(newList).map { item -> DiffOperation.Deleted(item) }.forEach { change -> changesFlow.tryEmit(change) } newList.asSequence().minus(nodes.keys).map { item -> DiffOperation.Added(item) } .forEach { change -> changesFlow.tryEmit(change) } } abstract suspend fun onInserted(item: T): ArNode abstract suspend fun onRemoved(item: T, node: ArNode) sealed class DiffOperation<out T> { class Added<out T>(val item: T) : DiffOperation<T>() class Deleted<out T>(val item: T) : DiffOperation<T>() } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/preview/nodes_adapters/TreeAdapter.kt
367282932
package com.nexus.farmap.presentation.preview.nodes_adapters import androidx.lifecycle.LifecycleCoroutineScope import com.nexus.farmap.domain.tree.TreeNode import com.nexus.farmap.presentation.common.helpers.DrawerHelper import com.uchuhimo.collections.MutableBiMap import com.uchuhimo.collections.mutableBiMapOf import io.github.sceneview.ar.ArSceneView import io.github.sceneview.ar.node.ArNode class TreeAdapter( drawerHelper: DrawerHelper, previewView: ArSceneView, bufferSize: Int, scope: LifecycleCoroutineScope, ) : NodesAdapter<TreeNode>(drawerHelper, previewView, bufferSize, scope) { private val modelsToLinkModels: MutableBiMap<Pair<ArNode, ArNode>, ArNode> = mutableBiMapOf() override suspend fun onInserted(item: TreeNode): ArNode { val node1 = drawerHelper.drawNode(item, previewView) for (id in item.neighbours) { nodes.keys.firstOrNull { it.id == id }?.let { treeNode -> nodes[treeNode]?.let { node2 -> if (modelsToLinkModels[Pair(node1, node2)] == null) { drawerHelper.drawLine( node1, node2, modelsToLinkModels, previewView ) } } } } return node1 } override suspend fun onRemoved(item: TreeNode, node: ArNode) { drawerHelper.removeNode(node) modelsToLinkModels.keys.filter { it.first == node || it.second == node }.forEach { pair -> drawerHelper.removeLink(pair, modelsToLinkModels) } } suspend fun createLink(treeNode1: TreeNode, treeNode2: TreeNode) { val node1 = nodes[treeNode1] val node2 = nodes[treeNode2] if (node1 != null && node2 != null) { drawerHelper.drawLine( node1, node2, modelsToLinkModels, previewView ) } } fun getArNode(treeNode: TreeNode?): ArNode? = nodes[treeNode] fun getTreeNode(node: ArNode?): TreeNode? { node?.let { return nodes.entries.find { it.value == node }?.key } return null } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/preview/MainEvent.kt
1161096757
package com.nexus.farmap.presentation.preview import com.nexus.farmap.domain.hit_test.HitTestResult import com.nexus.farmap.domain.tree.TreeNode import com.nexus.farmap.presentation.LabelObject import dev.romainguy.kotlin.math.Float3 import dev.romainguy.kotlin.math.Quaternion import io.github.sceneview.ar.arcore.ArFrame sealed interface MainEvent { class NewFrame(val frame: ArFrame) : MainEvent class NewConfirmationObject(val confObject: LabelObject) : MainEvent class TrySearch(val number: String, val changeType: Int) : MainEvent class AcceptConfObject(val confirmType: Int) : MainEvent class RejectConfObject(val confirmType: Int) : MainEvent class NewSelectedNode(val node: TreeNode?) : MainEvent object ChangeLinkMode : MainEvent class CreateNode( val number: String? = null, val position: Float3? = null, val orientation: Quaternion? = null, val hitTestResult: HitTestResult ) : MainEvent class DeleteNode(val node: TreeNode) : MainEvent class LinkNodes(val node1: TreeNode, val node2: TreeNode) : MainEvent }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/scanner/ScannerFragment.kt
3321419975
package com.nexus.farmap.presentation.scanner import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.nexus.farmap.data.App import com.nexus.farmap.databinding.FragmentScannerBinding import com.nexus.farmap.domain.hit_test.HitTestResult import com.nexus.farmap.domain.ml.DetectedText import com.nexus.farmap.presentation.LabelObject import com.nexus.farmap.presentation.common.helpers.DisplayRotationHelper import com.nexus.farmap.presentation.confirmer.ConfirmFragment import com.nexus.farmap.presentation.preview.MainEvent import com.nexus.farmap.presentation.preview.MainShareModel import com.nexus.farmap.presentation.preview.PreviewFragment import com.google.ar.core.TrackingState import com.google.ar.core.exceptions.NotYetAvailableException import dev.romainguy.kotlin.math.Float2 import io.github.sceneview.ar.arcore.ArFrame import kotlinx.coroutines.Job import kotlinx.coroutines.launch private const val SMOOTH_DELAY = 0.5 class ScannerFragment : Fragment() { private val mainModel: MainShareModel by activityViewModels() private var _binding: FragmentScannerBinding? = null private val binding get() = _binding!! private val args: ScannerFragmentArgs by navArgs() private val scanType by lazy { args.scanType } private val hitTest = App.instance!!.hitTest private val analyzeImage = App.instance!!.analyzeImage private lateinit var displayRotationHelper: DisplayRotationHelper private var lastDetectedObject: DetectedText? = null private var scanningNow: Boolean = false private var currentScanSmoothDelay: Double = 0.0 private var scanningJob: Job? = null private var lastFrameTime = System.currentTimeMillis() private var navigating = false override fun onAttach(context: Context) { super.onAttach(context) displayRotationHelper = DisplayRotationHelper(context) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentScannerBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { mainModel.frame.collect { frame -> frame?.let { onFrame(it) } } } } } override fun onResume() { lastDetectedObject = null scanningNow = false currentScanSmoothDelay = 0.0 scanningJob?.cancel() scanningJob = null navigating = false super.onResume() displayRotationHelper.onResume() } override fun onPause() { super.onPause() displayRotationHelper.onPause() } private fun onFrame(frame: ArFrame) { if (currentScanSmoothDelay > 0) { currentScanSmoothDelay -= getFrameInterval() } if (!scanningNow) { if (scanningJob?.isActive != true) { scanningJob?.cancel() scanningJob = viewLifecycleOwner.lifecycleScope.launch { if (currentScanSmoothDelay <= 0 && lastDetectedObject != null) { val res = hitTestDetectedObject(lastDetectedObject!!, frame) if (res != null && !navigating) { val confirmationObject = LabelObject( label = lastDetectedObject!!.detectedObjectResult.label, pos = res.orientatedPosition, anchor = res.hitResult.createAnchor() ) mainModel.onEvent( MainEvent.NewConfirmationObject( confirmationObject ) ) toConfirm( when (scanType) { TYPE_INITIALIZE -> { ConfirmFragment.CONFIRM_INITIALIZE } TYPE_ENTRY -> { ConfirmFragment.CONFIRM_ENTRY } else -> { throw IllegalArgumentException("Unrealised type") } } ) } else { currentScanSmoothDelay = SMOOTH_DELAY } } else { scanningNow = true val detectedObject = tryGetDetectedObject(frame) if (lastDetectedObject == null) { lastDetectedObject = detectedObject currentScanSmoothDelay = SMOOTH_DELAY } else if (detectedObject == null) { currentScanSmoothDelay = SMOOTH_DELAY } else { if (lastDetectedObject!!.detectedObjectResult.label != detectedObject.detectedObjectResult.label) { currentScanSmoothDelay = SMOOTH_DELAY } lastDetectedObject = detectedObject } scanningNow = false } } } } } private fun toConfirm(type: Int) { if (!navigating) { navigating = true val action = ScannerFragmentDirections.actionScannerFragmentToConfirmFragment( type ) findNavController().navigate(action) } } private suspend fun tryGetDetectedObject(frame: ArFrame): DetectedText? { val camera = frame.camera val session = frame.session if (camera.trackingState != TrackingState.TRACKING) { return null } val cameraImage = frame.tryAcquireCameraImage() if (cameraImage != null) { val cameraId = session.cameraConfig.cameraId val imageRotation = displayRotationHelper.getCameraSensorToDisplayRotation(cameraId) val displaySize = Pair( session.displayWidth, session.displayHeight ) val detectedResult = analyzeImage( cameraImage, imageRotation, PreviewFragment.DESIRED_CROP, displaySize ) cameraImage.close() detectedResult.getOrNull()?.let { return DetectedText(it, frame.frame) } return null } cameraImage?.close() return null } private fun hitTestDetectedObject(detectedText: DetectedText, frame: ArFrame): HitTestResult? { val detectedObject = detectedText.detectedObjectResult return useHitTest( detectedObject.centerCoordinate.x, detectedObject.centerCoordinate.y, frame ).getOrNull() } private fun useHitTest( x: Float, y: Float, frame: ArFrame ): Result<HitTestResult> { return hitTest(frame, Float2(x, y)) } private fun getFrameInterval(): Long { val frameTime = System.currentTimeMillis() - lastFrameTime lastFrameTime = System.currentTimeMillis() return frameTime } private fun ArFrame.tryAcquireCameraImage() = try { frame.acquireCameraImage() } catch (e: NotYetAvailableException) { null } catch (e: Throwable) { throw e } companion object { const val SCAN_TYPE = "scanType" const val TYPE_INITIALIZE = 0 const val TYPE_ENTRY = 1 } }
nexus-farmap/app/src/main/java/com/nexus/farmap/presentation/router/RouterFragment.kt
3337784668
package com.nexus.farmap.presentation.router import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isGone import androidx.core.view.isVisible import androidx.fragment.app.activityViewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.findNavController import com.nexus.farmap.R import com.nexus.farmap.data.App import com.nexus.farmap.databinding.FragmentRouterBinding import com.nexus.farmap.domain.hit_test.HitTestResult import com.nexus.farmap.presentation.preview.MainEvent import com.nexus.farmap.presentation.preview.MainShareModel import com.nexus.farmap.presentation.scanner.ScannerFragment import com.nexus.farmap.presentation.search.SearchFragment import dev.romainguy.kotlin.math.Float2 import dev.romainguy.kotlin.math.Float3 import dev.romainguy.kotlin.math.Quaternion import io.github.sceneview.ar.arcore.ArFrame import kotlinx.coroutines.launch class RouterFragment : Fragment() { private val destinationDesc = App.instance!!.getDestinationDesc private val hitTest = App.instance!!.hitTest private val mainModel: MainShareModel by activityViewModels() private var _binding: FragmentRouterBinding? = null private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentRouterBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { if (App.mode == App.ADMIN_MODE) { binding.adminPanel.isVisible = true } else { binding.adminPanel.isGone = true } binding.adminButton.setOnClickListener { toggleAdmin() } binding.deleteButton.setOnClickListener { removeSelectedNode() } binding.linkButton.setOnClickListener { changeLinkPlacementMode() } binding.placeButton.setOnClickListener { viewLifecycleOwner.lifecycleScope.launch { createNode() } } binding.entryButton.setOnClickListener { val bundle = Bundle() bundle.putInt( ScannerFragment.SCAN_TYPE, ScannerFragment.TYPE_ENTRY ) findNavController().navigate(R.id.action_global_scannerFragment, args = bundle) } binding.fromInput.setOnFocusChangeListener { _, b -> if (b) { binding.fromInput.isActivated = false binding.fromInput.clearFocus() search(SearchFragment.TYPE_START) } } binding.toInput.setOnFocusChangeListener { _, b -> if (b) { binding.toInput.isActivated = false binding.toInput.clearFocus() search(SearchFragment.TYPE_END) } } viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { mainModel.pathState.collect { pathState -> binding.fromInput.setText(pathState.startEntry?.number ?: "") binding.toInput.setText(pathState.endEntry?.number ?: "") if (pathState.path != null) { binding.destinationText.isVisible = true binding.destinationText.text = resources.getString( R.string.going, destinationDesc(pathState.endEntry!!.number, requireContext()) ) } else { binding.destinationText.isGone = true } } } } viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { mainModel.selectedNode.collect { treeNode -> binding.linkButton.isEnabled = treeNode != null binding.deleteButton.isEnabled = treeNode != null } } } viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { mainModel.linkPlacementMode.collect { link -> binding.linkButton.text = if (link) getString(R.string.cancel) else getString(R.string.link) } } } } private fun search(type: Int) { val action = RouterFragmentDirections.actionRouterFragmentToSearchFragment( type ) findNavController().navigate(action) } private fun changeLinkPlacementMode() { mainModel.onEvent(MainEvent.ChangeLinkMode) } private fun toggleAdmin() { if (App.mode == App.ADMIN_MODE) App.mode = App.USER_MODE else App.mode = App.ADMIN_MODE } private fun removeSelectedNode() { mainModel.selectedNode.value?.let { mainModel.onEvent(MainEvent.DeleteNode(it)) } } private fun createNode( number: String? = null, position: Float3? = null, orientation: Quaternion? = null, ) { viewLifecycleOwner.lifecycleScope.launch { mainModel.frame.value?.let { frame -> val result = useHitTest(frame).getOrNull() if (result != null) { mainModel.onEvent( MainEvent.CreateNode( number, position, orientation, result ) ) } } } } private fun useHitTest( frame: ArFrame, x: Float = frame.session.displayWidth / 2f, y: Float = frame.session.displayHeight / 2f, ): Result<HitTestResult> { return hitTest(frame, Float2(x, y)) } }
problem_solvingLev3/src/YearCalender.kt
1283245231
fun printYearCalendar(year: Int) { println("---------------------\n") println("-----------$year----------\n") println("---------------------\n") for (i in 1..12) { printMonthCalendar(year, i) println() } }
problem_solvingLev3/src/getDateFromTotelOfDays.kt
2765007750
fun getDate(year: Int, totalDays: Int): String { var startMonth = 1 var daysInMonth: Int var reminder = totalDays val days: Int; while (true) { daysInMonth = daysInMonth(year, startMonth) if (reminder > daysInMonth) { reminder -= daysInMonth startMonth++ } else { days = reminder break } } return "date for [$totalDays] : $days/$startMonth/$year" }
problem_solvingLev3/src/TotalDays.kt
546277472
fun totalDayFromBeginningOfYear(day: Int, month: Int, year: Int): Int { var counter = 0 for (i in 1..<month) { counter += daysInMonth(year, i) } counter += day return counter }
problem_solvingLev3/src/PrintDataInLeapYear.kt
3393515367
fun daysInYear(year: Int): Int { return if (isLeapYear(year)) 366 else 365 } fun hours(year: Int) = daysInYear(year) * 24 fun minutes(year: Int) = hours(year) * 60 fun seconds(year: Int) = minutes(year) * 60
problem_solvingLev3/src/Main.kt
1088117531
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or // click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter. fun readNumber(msg: String): Int { print(msg) val number = readln().toInt() return number } fun main() { }
problem_solvingLev3/src/MonthCalender.kt
3031277457
fun monthDayName(month: Int): String { val monthName = listOf( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ) return monthName[month-1] } fun printMonthCalendar(year: Int, month: Int) { val current = gregorianCalender(1, month, year) val numberOfDaysInMonth = daysInMonth(year, month) println("----------${monthDayName(month)}-----------") print("Sun Mon Tue Wed The Fri Sat\n") var index = current for (j in 1..current) { print(" ") } for (i in 1..numberOfDaysInMonth) { print("$i ") if (++index == 7) { index = 0 println() } } println("\n--------------------------------") }
problem_solvingLev3/src/getDateAfterAddingMoreDays.kt
4214981724
fun getDateAfterAddMoreDays(year: Int, totalDays: Int): String { var currentYear = year var startMonth = 1 var daysInMonth: Int var reminder = totalDays val days: Int while (true) { daysInMonth = daysInMonth(currentYear, startMonth) if (reminder > daysInMonth) { reminder -= daysInMonth startMonth++ if (startMonth == 12) currentYear++ } else { days = reminder break } } return "date for [$totalDays] : $days/$startMonth/$currentYear" }
problem_solvingLev3/src/dayInWeek.kt
1665738101
fun gregorianCalender(day: Int, month: Int, year: Int): Int { val a = (14 - month) / 12 val y = year - a val m = month + (12 * a) - 2 return (day + y + (y / 4) - (y / 100) + (y / 400) + ((31 * m) / 12)) % 7 } fun shortDayName(day: Int): String { val arrayOfDay = listOf("Sun", "Mon", "Tue", "Wed", "The", "Fri", "Sat") return arrayOfDay[day] }
problem_solvingLev3/src/isLeapYear.kt
1861209480
/* * * Check is The Year User entered Is Leap or not * * */ fun isLeapYear(year: Int): Boolean { return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 }
problem_solvingLev3/src/PrintNumberInMonth.kt
242581140
fun daysInMonth(year: Int, month: Int): Int { if (month < 1 || month > 12) return 0 if (month == 2) { return if (isLeapYear(year)) 29 else 28 } else if (month == 4 || month == 6 || month == 9 || month == 11) return 30 return 31 } fun hours(year: Int, month: Int) = daysInMonth(year, month) * 24 fun minutes(year: Int, month: Int) = hours(year, month) * 60 fun seconds(year: Int, month: Int) = minutes(year, month) * 60
vipexam/core/ui/src/androidTest/java/app/xlei/vipexam/core/ui/ExampleInstrumentedTest.kt
3447633109
package app.xlei.vipexam.core.ui 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("app.xlei.vipexam.core.ui.test", appContext.packageName) } }
vipexam/core/ui/src/test/java/app/xlei/vipexam/core/ui/ExampleUnitTest.kt
1016663293
package app.xlei.vipexam.core.ui 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) } }
vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/EmptyTextToolbar.kt
1776917720
package app.xlei.vipexam.core.ui import android.content.ClipboardManager import android.content.ComponentName import android.content.Context import android.content.Context.CLIPBOARD_SERVICE import android.content.Intent import android.content.pm.PackageManager import android.content.pm.ResolveInfo import android.os.Build import android.view.ActionMode import android.view.Menu import android.view.MenuItem import android.view.View import androidx.compose.ui.geometry.Rect import androidx.compose.ui.platform.TextToolbar import androidx.compose.ui.platform.TextToolbarStatus /** * Empty text toolbar * * @property onHide * @property onSelect * in [app.xlei.vipexam.feature.wordlist.components.TranslationSheet], [VipexamTextToolbar] don't * work, we use this. */ class EmptyTextToolbar( private val onHide: (() -> Unit)? = null, private val onSelect: () -> Unit, ) : TextToolbar { override val status: TextToolbarStatus = TextToolbarStatus.Hidden override fun hide() { onHide?.invoke() } override fun showMenu( rect: Rect, onCopyRequested: (() -> Unit)?, onPasteRequested: (() -> Unit)?, onCutRequested: (() -> Unit)?, onSelectAllRequested: (() -> Unit)?, ) { onSelect.invoke() onCopyRequested?.invoke() } } class VipexamTextToolbar( private val onHide: (() -> Unit)? = null, private val view: View, onTranslate: () -> Unit, ) : TextToolbar { private var actionMode: ActionMode? = null private val textActionModeCallback: VipexamTextActionModeCallback = VipexamTextActionModeCallback( context = view.context, onActionModeDestroy = { actionMode = null }, onTranslate = onTranslate ) override var status: TextToolbarStatus = TextToolbarStatus.Hidden private set override fun hide() { status = TextToolbarStatus.Hidden actionMode?.finish() actionMode = null onHide?.invoke() } override fun showMenu( rect: Rect, onCopyRequested: (() -> Unit)?, onPasteRequested: (() -> Unit)?, onCutRequested: (() -> Unit)?, onSelectAllRequested: (() -> Unit)?, ) { textActionModeCallback.rect = rect textActionModeCallback.onCopyRequested = onCopyRequested textActionModeCallback.onCutRequested = onCutRequested textActionModeCallback.onPasteRequested = onPasteRequested textActionModeCallback.onSelectAllRequested = onSelectAllRequested if (actionMode == null) { status = TextToolbarStatus.Shown actionMode = view.startActionMode( FloatingTextActionModeCallback(textActionModeCallback), ActionMode.TYPE_FLOATING, ) } else { actionMode?.invalidate() } } } class VipexamTextActionModeCallback( val context: Context, val onActionModeDestroy: (() -> Unit)? = null, var rect: Rect = Rect.Zero, var onCopyRequested: (() -> Unit)? = null, var onPasteRequested: (() -> Unit)? = null, var onCutRequested: (() -> Unit)? = null, var onSelectAllRequested: (() -> Unit)? = null, val onTranslate: () -> Unit, ) : ActionMode.Callback { private val displayNameComparator by lazy { ResolveInfo.DisplayNameComparator(packageManager) } private val packageManager by lazy { context.packageManager } private val clipboardManager by lazy { context.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager } private val textProcessors = mutableListOf<ComponentName>() override fun onCreateActionMode( mode: ActionMode?, menu: Menu?, ): Boolean { requireNotNull(menu) requireNotNull(mode) onCopyRequested?.let { menu.add( 0, 0, 0, R.string.translate ) addTextProcessors(menu) } return true } override fun onPrepareActionMode( mode: ActionMode?, menu: Menu?, ): Boolean { if (mode == null || menu == null) return false updateMenuItems(menu) return true } override fun onActionItemClicked( mode: ActionMode?, item: MenuItem?, ): Boolean { when (val itemId = item!!.itemId) { 0 -> { onCopyRequested?.invoke() onTranslate.invoke() } else -> { if (itemId < 100) return false onCopyRequested?.invoke() val clip = clipboardManager.primaryClip if (clip != null && clip.itemCount > 0) { textProcessors.getOrNull(itemId - 100)?.let { cn -> context.startActivity( Intent(Intent.ACTION_PROCESS_TEXT).apply { type = "text/plain" component = cn putExtra(Intent.EXTRA_PROCESS_TEXT, clip.getItemAt(0).text) } ) } } } } mode?.finish() return true } override fun onDestroyActionMode(mode: ActionMode?) { onActionModeDestroy?.invoke() } private fun addTextProcessors(menu: Menu) { textProcessors.clear() val intentActionProcessText = Intent(Intent.ACTION_PROCESS_TEXT).apply { type = "text/plain" } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { packageManager.queryIntentActivities( intentActionProcessText, PackageManager.ResolveInfoFlags.of(0L) ) } else { packageManager.queryIntentActivities(intentActionProcessText, 0) } .sortedWith(displayNameComparator) .forEachIndexed { index, info -> val label = info.loadLabel(packageManager) val id = 100 + index if (menu.findItem(id) == null) { // groupId, itemId, order, title menu.add(1, id, id, label) .setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW) } textProcessors.add( ComponentName( info.activityInfo.applicationInfo.packageName, info.activityInfo.name, ), ) } } private fun updateMenuItems(menu: Menu) { onCopyRequested?.let { addTextProcessors(menu) } } } internal class FloatingTextActionModeCallback( private val callback: VipexamTextActionModeCallback, ) : ActionMode.Callback2() { override fun onActionItemClicked( mode: ActionMode?, item: MenuItem?, ): Boolean { return callback.onActionItemClicked(mode, item) } override fun onCreateActionMode( mode: ActionMode?, menu: Menu?, ): Boolean { return callback.onCreateActionMode(mode, menu) } override fun onPrepareActionMode( mode: ActionMode?, menu: Menu?, ): Boolean { return callback.onPrepareActionMode(mode, menu) } override fun onDestroyActionMode(mode: ActionMode?) { callback.onDestroyActionMode(mode) } override fun onGetContentRect( mode: ActionMode?, view: View?, outRect: android.graphics.Rect?, ) { val rect = callback.rect outRect?.set( rect.left.toInt(), rect.top.toInt(), rect.right.toInt(), rect.bottom.toInt(), ) } }
vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/ErrorMessage.kt
1666416582
package app.xlei.vipexam.core.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable fun ErrorMessage( message: String, modifier: Modifier = Modifier, onClickRetry: () -> Unit ) { Row( modifier = modifier.padding(10.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( text = message, color = MaterialTheme.colorScheme.error, modifier = Modifier.weight(1f), maxLines = 2 ) OutlinedButton(onClick = onClickRetry) { Text(text = "retry") } } }
vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/util/scrollutil.kt
659661404
package app.xlei.vipexam.core.ui.util import androidx.compose.foundation.lazy.LazyListState import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue @Composable fun LazyListState.isScrollingUp(): Boolean { var previousIndex by remember(this) { mutableIntStateOf(firstVisibleItemIndex) } var previousScrollOffset by remember(this) { mutableIntStateOf(firstVisibleItemScrollOffset) } return remember(this) { derivedStateOf { if (previousIndex != firstVisibleItemIndex) { previousIndex > firstVisibleItemIndex } else { previousScrollOffset >= firstVisibleItemScrollOffset }.also { previousIndex = firstVisibleItemIndex previousScrollOffset = firstVisibleItemScrollOffset } } }.value }
vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/OnLoading.kt
376698902
package app.xlei.vipexam.core.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp @Composable fun OnLoading(onLoadingTextId: Int = R.string.loading){ Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = stringResource(id = onLoadingTextId), color = MaterialTheme.colorScheme.primary, maxLines = 1, overflow = TextOverflow.Ellipsis ) CircularProgressIndicator(Modifier.padding(top = 10.dp)) } }
vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/PageLoader.kt
2388408973
package app.xlei.vipexam.core.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow @Composable fun PageLoader(modifier: Modifier = Modifier) { Column( modifier = modifier, verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = stringResource(id = R.string.loading), color = MaterialTheme.colorScheme.primary, maxLines = 1, overflow = TextOverflow.Ellipsis ) } }
vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/Banner.kt
280410704
package app.xlei.vipexam.core.ui import android.view.SoundEffectConstants import androidx.compose.animation.Crossfade import androidx.compose.foundation.background import androidx.compose.foundation.clickable 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.fillMaxHeight 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.foundation.shape.RoundedCornerShape import androidx.compose.material3.Icon import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider 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.vector.ImageVector import androidx.compose.ui.platform.LocalView import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @Composable fun Banner( modifier: Modifier = Modifier, title: String, desc: String? = null, backgroundColor: Color = MaterialTheme.colorScheme.primaryContainer, icon: ImageVector? = null, action: (@Composable () -> Unit)? = null, onClick: () -> Unit = {}, ) { val view = LocalView.current Surface( modifier = modifier .fillMaxWidth() .height(if (!desc.isNullOrBlank()) 88.dp else Dp.Unspecified), color = Color.Unspecified, ) { Row( modifier = Modifier .fillMaxSize() .padding(horizontal = 16.dp) .clip(RoundedCornerShape(32.dp)) .background(backgroundColor alwaysLight true) .clickable { view.playSoundEffect(SoundEffectConstants.CLICK) onClick() } .padding(16.dp, 20.dp), verticalAlignment = Alignment.CenterVertically ) { icon?.let { icon -> Crossfade(targetState = icon, label = "") { Icon( imageVector = it, contentDescription = null, modifier = Modifier.padding(end = 16.dp), tint = MaterialTheme.colorScheme.onSurface alwaysLight true, ) } } Column( modifier = Modifier .weight(1f) .fillMaxHeight(), verticalArrangement = Arrangement.SpaceBetween, ) { Text( text = title, maxLines = if (desc == null) 2 else 1, style = MaterialTheme.typography.titleLarge.copy(fontSize = 20.sp), color = MaterialTheme.colorScheme.onSurface alwaysLight true, overflow = TextOverflow.Ellipsis, ) desc?.let { Text( text = it, style = MaterialTheme.typography.bodySmall, color = (MaterialTheme.colorScheme.onSurface alwaysLight true).copy(alpha = 0.7f), maxLines = 1, overflow = TextOverflow.Ellipsis, ) } } action?.let { Box(Modifier.padding(start = 16.dp)) { CompositionLocalProvider( LocalContentColor provides (MaterialTheme.colorScheme.onSurface alwaysLight true) ) { it() } } } } } }
vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/VipexamArticleContainer.kt
1750085964
package app.xlei.vipexam.core.ui import android.content.ClipData import android.view.View import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.clickable import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.draganddrop.dragAndDropSource import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.Column import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draganddrop.DragAndDropTransferData import androidx.compose.ui.platform.LocalTextToolbar import androidx.compose.ui.platform.LocalView import app.xlei.vipexam.preference.LocalLongPressAction import app.xlei.vipexam.preference.LongPressAction /** * Vipexam article container * * @param onArticleLongClick 内容点击事件 * @param onDragContent 可以拖动的内容 * @param content 内容 * @receiver */ @OptIn(ExperimentalFoundationApi::class) @Composable fun VipexamArticleContainer( onClick: (() -> Unit)? = {}, onArticleLongClick: (() -> Unit)? = {}, onDragContent: String? = null, content: @Composable () -> Unit ){ var showTranslateDialog by rememberSaveable { mutableStateOf(false) } val longPressAction = LocalLongPressAction.current when (longPressAction) { LongPressAction.ShowTranslation -> CompositionLocalProvider( value = LocalTextToolbar provides VipexamTextToolbar( view = LocalView.current ) { showTranslateDialog = true } ) { SelectionContainer( modifier = Modifier.clickable { onClick?.invoke() } ) { content() } } LongPressAction.ShowQuestion -> Column( modifier = Modifier .combinedClickable( onClick = { onClick?.invoke() }, onLongClick = onArticleLongClick ) ) { content() } LongPressAction.None -> Column( modifier = Modifier .dragAndDropSource { detectTapGestures( onPress = { onClick?.invoke() }, onLongPress = { startTransfer( DragAndDropTransferData( clipData = ClipData.newPlainText("", onDragContent), flags = View.DRAG_FLAG_GLOBAL, ) ) }, ) } ){ content() } } if (longPressAction.isShowTranslation() && showTranslateDialog) TranslateDialog( onDismissRequest = { showTranslateDialog = false } ) { AddToWordListButton(onClick = { showTranslateDialog = false }) } }
vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/vm/AddToWordListButtonViewModel.kt
3669884021
package app.xlei.vipexam.core.ui.vm import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import app.xlei.vipexam.core.data.repository.Repository import app.xlei.vipexam.core.database.module.Word import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject @HiltViewModel class AddToWordListButtonViewModel @Inject constructor( private val wordRepository: Repository<Word> ) : ViewModel() { fun addToWordList(word: String) { viewModelScope.launch { withContext(Dispatchers.IO) { wordRepository.add( Word( word = word ) ) } } } }
vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/AddToWordListButton.kt
2472867175
package app.xlei.vipexam.core.ui import android.content.ClipboardManager import android.content.Context import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.hilt.navigation.compose.hiltViewModel import app.xlei.vipexam.core.ui.vm.AddToWordListButtonViewModel /** * Add to word list button * * @param onClick 点击行为 * @param viewModel 添加到单词表vm * @receiver */ @Composable fun AddToWordListButton( onClick: (() -> Unit) = {}, viewModel: AddToWordListButtonViewModel = hiltViewModel() ){ val context = LocalContext.current val clipBoardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager TextButton( onClick = { viewModel.addToWordList( clipBoardManager.primaryClip?.getItemAt(0)?.text?.toString()!! ) onClick.invoke() } ) { Text(stringResource(id = R.string.add_to_word_list)) } }
vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/OnError.kt
210277787
package app.xlei.vipexam.core.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow @Composable fun OnError( textId: Int = R.string.internet_error, error: String? = null, ){ Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = stringResource(id = textId), color = MaterialTheme.colorScheme.primary, maxLines = 1, overflow = TextOverflow.Ellipsis ) error?.let { Text( text = it, color = MaterialTheme.colorScheme.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.labelSmall ) } } }
vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/LoadingNextPageItem.kt
600524274
package app.xlei.vipexam.core.ui import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.material3.CircularProgressIndicator import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable fun LoadingNextPageItem(modifier: Modifier) { CircularProgressIndicator( modifier = modifier .fillMaxWidth() .padding(10.dp) .wrapContentWidth(Alignment.CenterHorizontally) ) }
vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/LoginAlert.kt
90776413
package app.xlei.vipexam.core.ui import androidx.compose.material3.AlertDialog import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource @Composable fun LoginAlert( onDismissRequest: () -> Unit, ){ AlertDialog( onDismissRequest = onDismissRequest, confirmButton = { TextButton(onClick = { onDismissRequest.invoke() }) { Text(text = stringResource(id = R.string.ok)) } }, title = { Text(text = stringResource(id = R.string.login_to_continue)) } ) }
vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/palette.kt
2748357709
package app.xlei.vipexam.core.ui import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.ReadOnlyComposable import androidx.compose.runtime.Stable import androidx.compose.ui.graphics.Color import app.xlei.vipexam.preference.LocalThemeMode @Stable @Composable @ReadOnlyComposable infix fun Color.alwaysLight(isAlways: Boolean): Color { val colorScheme = MaterialTheme.colorScheme return if (isAlways && LocalThemeMode.current.isDarkTheme()) { when (this) { colorScheme.primary -> colorScheme.onPrimary colorScheme.secondary -> colorScheme.onSecondary colorScheme.tertiary -> colorScheme.onTertiary colorScheme.background -> colorScheme.onBackground colorScheme.error -> colorScheme.onError colorScheme.surface -> colorScheme.onSurface colorScheme.surfaceVariant -> colorScheme.onSurfaceVariant colorScheme.primaryContainer -> colorScheme.onPrimaryContainer colorScheme.secondaryContainer -> colorScheme.onSecondaryContainer colorScheme.tertiaryContainer -> colorScheme.onTertiaryContainer colorScheme.errorContainer -> colorScheme.onErrorContainer colorScheme.inverseSurface -> colorScheme.inverseOnSurface colorScheme.onPrimary -> colorScheme.primary colorScheme.onSecondary -> colorScheme.secondary colorScheme.onTertiary -> colorScheme.tertiary colorScheme.onBackground -> colorScheme.background colorScheme.onError -> colorScheme.error colorScheme.onSurface -> colorScheme.surface colorScheme.onSurfaceVariant -> colorScheme.surfaceVariant colorScheme.onPrimaryContainer -> colorScheme.primaryContainer colorScheme.onSecondaryContainer -> colorScheme.secondaryContainer colorScheme.onTertiaryContainer -> colorScheme.tertiaryContainer colorScheme.onErrorContainer -> colorScheme.errorContainer colorScheme.inverseOnSurface -> colorScheme.inverseSurface else -> Color.Unspecified } } else { this } } @Stable @Composable @ReadOnlyComposable infix fun Color.alwaysDark(isAlways: Boolean): Color { val colorScheme = MaterialTheme.colorScheme return if (isAlways && !LocalThemeMode.current.isDarkTheme()) { when (this) { colorScheme.primary -> colorScheme.onPrimary colorScheme.secondary -> colorScheme.onSecondary colorScheme.tertiary -> colorScheme.onTertiary colorScheme.background -> colorScheme.onBackground colorScheme.error -> colorScheme.onError colorScheme.surface -> colorScheme.onSurface colorScheme.surfaceVariant -> colorScheme.onSurfaceVariant colorScheme.primaryContainer -> colorScheme.onPrimaryContainer colorScheme.secondaryContainer -> colorScheme.onSecondaryContainer colorScheme.tertiaryContainer -> colorScheme.onTertiaryContainer colorScheme.errorContainer -> colorScheme.onErrorContainer colorScheme.inverseSurface -> colorScheme.inverseOnSurface colorScheme.onPrimary -> colorScheme.primary colorScheme.onSecondary -> colorScheme.secondary colorScheme.onTertiary -> colorScheme.tertiary colorScheme.onBackground -> colorScheme.background colorScheme.onError -> colorScheme.error colorScheme.onSurface -> colorScheme.surface colorScheme.onSurfaceVariant -> colorScheme.surfaceVariant colorScheme.onPrimaryContainer -> colorScheme.primaryContainer colorScheme.onSecondaryContainer -> colorScheme.secondaryContainer colorScheme.onTertiaryContainer -> colorScheme.tertiaryContainer colorScheme.onErrorContainer -> colorScheme.errorContainer colorScheme.inverseOnSurface -> colorScheme.inverseSurface else -> Color.Unspecified } } else { this } } fun String.checkColorHex(): String? { var s = this.trim() if (s.length > 6) { s = s.substring(s.length - 6) } return "[0-9a-fA-F]{6}".toRegex().find(s)?.value } @Stable fun String.safeHexToColor(): Color = try { Color(java.lang.Long.parseLong(this, 16)) } catch (e: Exception) { Color.Transparent }
vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/TranslationDialog.kt
2319367502
package app.xlei.vipexam.core.ui import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.os.Build import android.widget.Toast import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.material3.AlertDialog import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import app.xlei.vipexam.core.network.module.TranslationResponse import compose.icons.FeatherIcons import compose.icons.feathericons.Loader import kotlinx.coroutines.launch @Composable fun TranslateDialog( onDismissRequest: () -> Unit, dismissButton: @Composable () -> Unit = { TextButton(onClick = onDismissRequest) { Text(text = stringResource(R.string.cancel)) } }, confirmButton: @Composable () -> Unit = { TextButton(onClick = onDismissRequest) { Text(text = stringResource(id = R.string.ok)) } }, ) { val coroutine = rememberCoroutineScope() val context = LocalContext.current val clipboardManager = context.getSystemService( Context.CLIPBOARD_SERVICE ) as ClipboardManager val localConfiguration = LocalConfiguration.current AlertDialog( onDismissRequest = onDismissRequest, title = { clipboardManager.primaryClip?.getItemAt(0)?.text?.toString()?.let { LazyColumn ( modifier = Modifier .heightIn(max = (localConfiguration.screenHeightDp/2).dp) ){ item { Text( text = it ) } } } }, text = { var translation by remember { mutableStateOf( TranslationResponse( code = 200, id = "", data = "", emptyList() ) ) } DisposableEffect(Unit) { coroutine.launch { val res = app.xlei.vipexam.core.network.module.NetWorkRepository.translateToZH( text = clipboardManager.primaryClip?.getItemAt(0)?.text?.toString()!! ) res.onSuccess { translation = it }.onFailure { onDismissRequest.invoke() Toast.makeText(context, it.toString(), Toast.LENGTH_SHORT).show() } } onDispose { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { clipboardManager.clearPrimaryClip() } else { clipboardManager.setPrimaryClip( ClipData.newPlainText("", "") ) } } } LazyColumn { item { Text( text = translation.data, fontSize = if (translation.alternatives.isNotEmpty()) 24.sp else TextUnit.Unspecified, ) } item { LazyRow { when { translation.alternatives.isEmpty() && translation.data == "" -> { item { Icon( imageVector = FeatherIcons.Loader, contentDescription = null, ) } } else -> { items(translation.alternatives.size) { Text( text = translation.alternatives[it], modifier = Modifier.padding(end = 12.dp) ) } } } } } } }, dismissButton = dismissButton, confirmButton = confirmButton ) }
vipexam/core/ui/src/main/java/app/xlei/vipexam/core/ui/DateText.kt
1712580068
package app.xlei.vipexam.core.ui import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource import java.time.Duration import java.time.Instant import java.time.LocalDate import java.time.LocalDateTime import java.time.ZoneId import java.time.format.DateTimeFormatter @Composable fun DateText(time: Long?=null){ time?.let { Text( text = getFormattedDate(it), style = MaterialTheme.typography.bodySmall ) } } @Composable fun getFormattedDate(time: Long): String { val dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault()) val now = LocalDateTime.now() val today = LocalDate.now() val date = dateTime.toLocalDate() val duration = Duration.between(dateTime, now) return when { duration.toMinutes() < 1 -> stringResource(id = R.string.just_now) duration.toHours() < 1 -> "${duration.toMinutes()}" + stringResource(id = R.string.minute_before) duration.toDays() < 1 -> "${duration.toHours()}" + stringResource(id = R.string.hour_before) date.year == today.year -> dateTime.format(DateTimeFormatter.ofPattern("MM-dd")) else -> dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) } }
vipexam/core/database/src/androidTest/java/app/xlei/vipexam/core/database/ExampleInstrumentedTest.kt
3542410033
package app.xlei.vipexam.core.database import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith /** * 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("app.xlei.vipexam.core.database.test", appContext.packageName) } }
vipexam/core/database/src/test/java/app/xlei/vipexam/core/database/ExampleUnitTest.kt
2337610697
package app.xlei.vipexam.core.database import org.junit.Assert.assertEquals import org.junit.Test /** * 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) } }
vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/di/DaosModule.kt
469967449
package app.xlei.vipexam.core.database.di import app.xlei.vipexam.core.database.VipexamDatabase import app.xlei.vipexam.core.database.dao.BookmarkDao import app.xlei.vipexam.core.database.dao.ExamHistoryDao import app.xlei.vipexam.core.database.dao.UserDao import app.xlei.vipexam.core.database.dao.WordDao import app.xlei.vipexam.core.database.module.ExamHistory import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) object DaosModule { @Provides fun providesWordDao( database: VipexamDatabase ): WordDao = database.wordDao() @Provides fun providesUserDao( database: VipexamDatabase ): UserDao = database.userDao() @Provides fun providesExamHistory( database: VipexamDatabase ): ExamHistoryDao = database.examHistoryDao() @Provides fun providesBookmark( database: VipexamDatabase ): BookmarkDao = database.bookmarkDao() }
vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/di/DatabaseModule.kt
1166161274
package app.xlei.vipexam.core.database.di import android.content.Context import androidx.room.Room import app.xlei.vipexam.core.database.VipexamDatabase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object DatabaseModule { @Provides @Singleton fun providesVipexamDatabase( @ApplicationContext context: Context ): VipexamDatabase = Room.databaseBuilder( context, VipexamDatabase::class.java, "vipexam-database" ).build() @Singleton @Provides fun providesCoroutineScope(): CoroutineScope { return CoroutineScope(SupervisorJob() + Dispatchers.IO) } }
vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/module/Bookmark.kt
3465202507
package app.xlei.vipexam.core.database.module import androidx.room.Entity import androidx.room.PrimaryKey import java.util.Calendar @Entity(tableName = "bookmarks") data class Bookmark( @PrimaryKey(autoGenerate = true) val id: Int = 0, val examName: String, val examId: String, val question: String, val created: Long = Calendar.getInstance().timeInMillis, )
vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/module/WordEntity.kt
127143791
package app.xlei.vipexam.core.database.module import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey import java.util.Calendar @Entity( tableName = "words", indices = [Index(value = ["word"], unique = true)] ) data class Word( @PrimaryKey(autoGenerate = true) val id: Int = 0, @ColumnInfo(name = "word") val word: String, val created: Long = Calendar.getInstance().timeInMillis, )
vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/module/ExamHistory.kt
524733643
package app.xlei.vipexam.core.database.module import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey import java.util.Calendar @Entity( tableName = "exam_history", indices = [Index(value = ["examId"], unique = true)] ) data class ExamHistory ( @PrimaryKey(autoGenerate = true) val examHistoryId: Int = 0, val examName: String, @ColumnInfo(name = "examId") val examId: String, val lastOpen: Long = Calendar.getInstance().timeInMillis, )
vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/module/UserEntity.kt
2782821428
package app.xlei.vipexam.core.database.module import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "users") data class User( @PrimaryKey val account: String, val password: String, )
vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/module/LanguageEntity.kt
1596476166
package app.xlei.vipexam.core.database.module import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class Language( @PrimaryKey(autoGenerate = false) val code: String = "", @ColumnInfo val name: String = "" ) { override fun equals(other: Any?): Boolean { (other as? Language)?.let { otherLang -> return otherLang.name.lowercase() == this.name.lowercase() || otherLang.code.lowercase() == this.code.lowercase() } return super.equals(other) } override fun hashCode() = 31 * code.hashCode() + name.hashCode() }
vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/dao/UserDao.kt
4107336487
package app.xlei.vipexam.core.database.dao import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update import app.xlei.vipexam.core.database.module.User import kotlinx.coroutines.flow.Flow @Dao interface UserDao{ @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(user: User) @Update(onConflict = OnConflictStrategy.REPLACE) suspend fun update(user: User) @Delete suspend fun delete(user: User) @Query("SELECT * FROM users") fun getAllUsers(): Flow<List<User>> @Query("SELECT * FROM users WHERE account=:account") fun getUser(account: String): User }
vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/dao/ExamHistoryDao.kt
3970294260
package app.xlei.vipexam.core.database.dao import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import app.xlei.vipexam.core.database.module.ExamHistory import kotlinx.coroutines.flow.Flow @Dao interface ExamHistoryDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(historyEntity: ExamHistory) @Query("SELECT * FROM exam_history ORDER BY lastOpen DESC") fun getAllExamHistory(): Flow<List<ExamHistory>> @Query("SELECT * FROM exam_history WHERE examId=:examId LIMIT 1") fun getExamHistoryByExamId(examId: String): ExamHistory? @Query("SELECT * FROM exam_history ORDER BY lastOpen DESC LIMIT 1") fun getLastOpened(): Flow<ExamHistory?> @Delete suspend fun deleteHistory(historyEntity: ExamHistory) @Query("DELETE FROM exam_history WHERE examId=:examId") suspend fun deleteHistoryByExamId(examId: String) @Query("DELETE FROM exam_history WHERE examHistoryId IN (SELECT examHistoryId FROM exam_history)") suspend fun removeAllHistory() }
vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/dao/BookmarkDao.kt
533354100
package app.xlei.vipexam.core.database.dao import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query import app.xlei.vipexam.core.database.module.Bookmark import kotlinx.coroutines.flow.Flow @Dao interface BookmarkDao { @Query("SELECT * FROM bookmarks") fun getAllBookMarks(): Flow<List<Bookmark>> @Insert suspend fun insertBookmark(bookmark: Bookmark) @Delete suspend fun deleteBookmark(bookmark: Bookmark) }
vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/dao/WordDao.kt
259182272
package app.xlei.vipexam.core.database.dao import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import app.xlei.vipexam.core.database.module.Word import kotlinx.coroutines.flow.Flow @Dao interface WordDao { @Query("SELECT * FROM words") fun getAllWords(): Flow<List<Word>> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(word: Word) @Delete suspend fun delete(word: Word) }
vipexam/core/database/src/main/java/app/xlei/vipexam/core/database/VipexamDatabase.kt
3987373601
package app.xlei.vipexam.core.database import androidx.room.Database import androidx.room.RoomDatabase import app.xlei.vipexam.core.database.dao.BookmarkDao import app.xlei.vipexam.core.database.dao.ExamHistoryDao import app.xlei.vipexam.core.database.dao.UserDao import app.xlei.vipexam.core.database.dao.WordDao import app.xlei.vipexam.core.database.module.Bookmark import app.xlei.vipexam.core.database.module.ExamHistory import app.xlei.vipexam.core.database.module.User import app.xlei.vipexam.core.database.module.Word @Database( entities = [ Word::class, User::class, ExamHistory::class, Bookmark::class, ], version = 1 ) abstract class VipexamDatabase : RoomDatabase() { abstract fun wordDao(): WordDao abstract fun userDao(): UserDao abstract fun examHistoryDao(): ExamHistoryDao abstract fun bookmarkDao(): BookmarkDao }
vipexam/core/network/src/androidTest/java/app/xlei/vipexam/core/network/ExampleInstrumentedTest.kt
93560170
package app.xlei.vipexam.core.network import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith /** * 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("app.xlei.vipexam.core.network.test", appContext.packageName) } }
vipexam/core/network/src/test/java/app/xlei/vipexam/core/network/ExampleUnitTest.kt
4250647699
package app.xlei.vipexam.core.network import org.junit.Assert.assertEquals import org.junit.Test /** * 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) } }
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/addQCollect/AddQCollectResponse.kt
3069709865
package app.xlei.vipexam.core.network.module.addQCollect import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class AddQCollectResponse( @SerialName("code") val code: String, @SerialName("msg") val msg: String )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/NetWorkRepository.kt
3875475075
package app.xlei.vipexam.core.network.module import android.os.Environment import app.xlei.vipexam.core.network.module.TiJiaoTest.TiJiaoTestPayload import app.xlei.vipexam.core.network.module.TiJiaoTest.TiJiaoTestResponse import app.xlei.vipexam.core.network.module.addQCollect.AddQCollectResponse import app.xlei.vipexam.core.network.module.deleteQCollect.DeleteQCollectResponse import app.xlei.vipexam.core.network.module.getExamList.GetExamListResponse import app.xlei.vipexam.core.network.module.getExamResponse.GetExamResponse import app.xlei.vipexam.core.network.module.getExamResponse.Muban import app.xlei.vipexam.core.network.module.login.LoginResponse import app.xlei.vipexam.core.network.module.momoLookUp.MomoLookUpResponse import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.engine.cio.CIO import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.request.HttpRequestBuilder import io.ktor.client.request.get import io.ktor.client.request.header import io.ktor.client.request.headers import io.ktor.client.request.post import io.ktor.client.request.setBody import io.ktor.client.statement.bodyAsChannel import io.ktor.client.statement.bodyAsText import io.ktor.http.ContentType import io.ktor.http.HeadersBuilder import io.ktor.http.HttpHeaders import io.ktor.http.contentType import io.ktor.serialization.kotlinx.json.json import io.ktor.util.cio.writeChannel import io.ktor.utils.io.copyAndClose import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import java.io.File object NetWorkRepository { private lateinit var account: String private lateinit var password: String private lateinit var token: String private lateinit var organization: String private val httpClient by lazy { _httpClient.value } private val _httpClient = lazy { HttpClient(CIO) { engine { requestTimeout = 0 } install(ContentNegotiation) { json() } } } fun isAvailable() = this::account.isInitialized && this::token.isInitialized private fun HttpRequestBuilder.vipExamHeaders( referrer: String ): HeadersBuilder { return headers { append(HttpHeaders.Accept,"application/json, text/javascript, */*; q=0.01") append(HttpHeaders.AcceptLanguage,"zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6") append(HttpHeaders.Connection,"keep-alive") append(HttpHeaders.ContentType,"application/x-www-form-urlencoded; charset=UTF-8") append(HttpHeaders.Origin,"https://vipexam.cn") append("Sec-Fetch-Dest", "empty") append("Sec-Fetch-Mode", "cors") append("Sec-Fetch-Site", "same-origin") append(HttpHeaders.UserAgent, "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0") append("X-Requested-With", "XMLHttpRequest") append( "sec-ch-ua", "\"Microsoft Edge\";v=\"119\", \"Chromium\";v=\"119\", \"Not?A_Brand\";v=\"24\"" ) append("sec-ch-ua-mobile", "?0") append("sec-ch-ua-platform", "\"macOS\"") append(HttpHeaders.Referrer,referrer) } } suspend fun getToken( account: String, password: String, organization: String, ): Result<LoginResponse> { this.account = account this.password = password this.organization = organization return try { httpClient.post("https://vipexam.cn/user/login.action") { vipExamHeaders(referrer = "https://vipexam.cn/login2.html") setBody("account=$account&password=$password") }.body<LoginResponse>().also { if (it.code == "1") this.token = it.token }.run { when (code) { "1" -> Result.success(this) else -> Result.failure(error(msg)) } }.also { println(organization) } } catch (e: Exception) { Result.failure(e) } } suspend fun getExam(examId: String): Result<GetExamResponse> { return try { Result.success( httpClient.post("https://vipexam.cn/exam/getExamList.action") { vipExamHeaders(referrer = "https://vipexam.cn/begin_testing2.html?id=$examId") setBody("examID=$examId&account=$account&token=$token") }.body() ) }catch (e: Exception){ println(e) Result.failure(e) } } fun getQuestions(mubanList: List<Muban>): List<Pair<String, String>> { val questions = mutableListOf<Pair<String, String>>() for (muban in mubanList) { questions.add(muban.ename to muban.cname) } return questions } suspend fun getExamList( page: String, examStyle: Int, examTypeEName: String, ): Result<GetExamListResponse> { return try { Result.success( httpClient.post("https://vipexam.cn/web/moreCourses") { vipExamHeaders(referrer = "https://vipexam.cn/resources_kinds.html?id=$examTypeEName") setBody("data={\"account\":\"$account\",\"token\":\"$token\",\"typeCode\":\"$examTypeEName\",\"resourceType\":\"${examStyle}\",\"courriculumType\":\"0\",\"classHourS\":\"0\",\"classHourE\":\"0\",\"yearPublishedS\":\"0\",\"yearPublishedE\":\"0\",\"page\":$page,\"limit\":20,\"collegeName\":\"$organization\"}") }.body<GetExamListResponse>().also { println(it) } ) } catch (e: Exception){ Result.failure(e) } } suspend fun searchExam( page: String, searchContent: String ): Result<GetExamListResponse> { return try { Result.success( httpClient.post("https://vipexam.cn/examseek/speedinessSearch"){ vipExamHeaders(referrer = "exam_paper.html?field=1&exam_paper.html?field=1&keys=$searchContent") setBody(""" account=$account&token=$token&data={"page":$page,"limit":20,"fields":"1","keyword":"$searchContent","matching":"like"} """.trimIndent()) }.body() ) } catch (e: Exception){ Result.failure(e) } } suspend fun translateToZH(text: String): Result<TranslationResponse> { return try { Result.success( httpClient.post("https://api.deeplx.org/translate") { header("Accept", "application/json, text/javascript, */*; q=0.01") contentType(ContentType.Application.Json) setBody( mapOf( "text" to text, "source_lang" to "EN", "target_lang" to "ZH" ) ) }.body() ) } catch (e: Exception) { return Result.failure(e) } } suspend fun download( fileName: String, examId: String, ){ val client = HttpClient(CIO) try { val res = client.get(""" https://vipexam.cn/web/getExamWordByStu?examID=$examId&account=$account&token=$token """.trimIndent()){ headers { append("Host", "vipexam.cn") append("Connection", "keep-alive") append("sec-ch-ua", "\"Not A(Brand\";v=\"99\", \"Microsoft Edge\";v=\"121\", \"Chromium\";v=\"121\"") append("sec-ch-ua-mobile", "?0") append("sec-ch-ua-platform", "\"macOS\"") append("Upgrade-Insecure-Requests", "1") append("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0") append("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7") append("Sec-Fetch-Site", "none") append("Sec-Fetch-Mode", "navigate") append("Sec-Fetch-User", "?1") append("Sec-Fetch-Dest", "document") append("Accept-Encoding", "gzip, deflate, br") append("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6") } }.bodyAsChannel().also { val downloadsPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) val file = File(downloadsPath, "$fileName.doc") if (!downloadsPath.exists()) { downloadsPath.mkdirs() } it.copyAndClose(file.writeChannel()) } println(res) } catch (e: Exception) { println(e) } } suspend fun addQCollect( examId: String, questionCode: String ): Result<AddQCollectResponse> { return try { Result.success( httpClient.post("https://vipexam.cn/questioncollect/addQCollect.action") { vipExamHeaders("https://vipexam.cn/begin_testing2.html?id=$examId") setBody( """ account=$account&token=$token&ExamID=$examId&QuestionCode=$questionCode """.trimIndent() ) }.body() ) } catch (e: Exception) { Result.failure(e) } } suspend fun deleteQCollect( examId: String, questionCode: String ): Result<DeleteQCollectResponse> { return try { Result.success( httpClient.post("https://vipexam.cn/questioncollect/deleteQCollect.action") { vipExamHeaders("https://vipexam.cn/begin_testing2.html?id=$examId") setBody( """ account=$account&token=$token&ExamID=$examId&QuestionCode=$questionCode """.trimIndent() ) }.body() ) } catch (e: Exception) { Result.failure(e) } } suspend fun tiJiaoTest(payload: TiJiaoTestPayload): Result<TiJiaoTestResponse> { return try { println(Json.encodeToString(payload)) Result.success( httpClient.post("https://vipexam.cn/exam/TiJiaoTest") { vipExamHeaders("https://vipexam.cn/begin_testing.html?id=${payload.examID}") setBody( "data=" + Json.encodeToString( payload.copy( account = account, token = token, ) ) ) }.run { println(this.bodyAsText()) this.body<TiJiaoTestResponse>() } ) } catch (e: Exception) { println(e) Result.failure(e) } } suspend fun momoLookUp( offset: Int, keyword: String, paperType: String = "CET6" ): Result<MomoLookUpResponse> { return try { Result.success( httpClient.get("https://lookup.maimemo.com/api/v1/search?offset=$offset&limit=10&keyword=$keyword&paper_type=$paperType") .body<MomoLookUpResponse>() ) } catch (e: Exception) { Result.failure(e) } } }
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/eudic/Data.kt
3626294431
package app.xlei.vipexam.core.network.module.eudic import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Data( @SerialName("id") val id: String, @SerialName("language") val language: String, @SerialName("name") val name: String )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/eudic/AddNewCategoryResponse.kt
457777723
package app.xlei.vipexam.core.network.module.eudic import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class AddNewCategoryResponse( @SerialName("data") val `data`: Data, @SerialName("message") val message: String )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/eudic/GetAllCategoryResponse.kt
2070468948
package app.xlei.vipexam.core.network.module.eudic import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class GetAllCategoryResponse( @SerialName("data") val `data`: List<Data>, @SerialName("message") val message: String )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/eudic/AddWordsResponse.kt
1805897571
package app.xlei.vipexam.core.network.module.eudic import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class AddWordsResponse( @SerialName("message") val message: String )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/getExamList/Exam.kt
3672553677
package app.xlei.vipexam.core.network.module.getExamList import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Exam( @SerialName("collectDate") val collectDate: String? = null, @SerialName("examTypeEName") val examTypeEName: String = "", @SerialName("examdate") val examdate: String = "", @SerialName("examid") val examid: String = "", @SerialName("examname") val examname: String = "", @SerialName("examstyle") val examstyle: String = "", @SerialName("examtyleStr") val examtyleStr: String = "", @SerialName("examtypeII") val examtypeII: String? = null, @SerialName("examtypecode") val examtypecode: String = "", @SerialName("fullName") val fullName: String = "", @SerialName("temlExamtimeLimit") val temlExamtimeLimit: Int = 0, @SerialName("templatecode") val templatecode: String = "", @SerialName("tid") val tid: Int = 0, @SerialName("tmplExamScore") val tmplExamScore: Int = 0 )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/getExamList/GetExamListResponse.kt
3164184904
package app.xlei.vipexam.core.network.module.getExamList import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class GetExamListResponse( @SerialName("code") val code: String = "", @SerialName("count") val count: Int = 0, @SerialName("list") val list: List<Exam> = listOf(), @SerialName("msg") val msg: String = "", @SerialName("resourceType") val resourceType: Int = 0 )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/getExamResponse/Shiti.kt
539922747
package app.xlei.vipexam.core.network.module.getExamResponse import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Shiti( @SerialName("answerPic") val answerPic: String = "", @SerialName("audioFiles") val audioFiles: String = "", @SerialName("children") val children: List<Children> = listOf(), @SerialName("discPic") val discPic: String = "", @SerialName("discription") val discription: String = "", @SerialName("fifth") val fifth: String = "", @SerialName("fifthPic") val fifthPic: String = "", @SerialName("first") val first: String = "", @SerialName("firstPic") val firstPic: String = "", @SerialName("fourth") val fourth: String = "", @SerialName("fourthPic") val fourthPic: String = "", @SerialName("groupCodePrimQuestion") val groupCodePrimQuestion: String = "", @SerialName("isCollect") val isCollect: String = "", @SerialName("originalText") val originalText: String = "", @SerialName("primPic") val primPic: String = "", @SerialName("primQuestion") val primQuestion: String = "", @SerialName("questionCode") val questionCode: String = "", @SerialName("refAnswer") val refAnswer: String = "", @SerialName("second") val second: String = "", @SerialName("secondPic") val secondPic: String = "", @SerialName("secondQuestion") val secondQuestion: String? = null, @SerialName("subPrimPic") val subPrimPic: String = "", @SerialName("subjectTypeEname") val subjectTypeEname: String = "", @SerialName("third") val third: String = "", @SerialName("thirdPic") val thirdPic: String = "" )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/getExamResponse/Children.kt
3138195974
package app.xlei.vipexam.core.network.module.getExamResponse import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Children( @SerialName("answerPic") val answerPic: String = "", @SerialName("audioFiles") val audioFiles: String = "", @SerialName("discPic") val discPic: String = "", @SerialName("discription") val discription: String = "", @SerialName("fifth") val fifth: String = "", @SerialName("fifthPic") val fifthPic: String = "", @SerialName("first") val first: String = "", @SerialName("firstPic") val firstPic: String = "", @SerialName("fourth") val fourth: String = "", @SerialName("fourthPic") val fourthPic: String = "", @SerialName("isCollect") val isCollect: String = "", @SerialName("originalText") val originalText: String = "", @SerialName("primPic") val primPic: String = "", @SerialName("primQuestion") val primQuestion: String = "", @SerialName("questionCode") val questionCode: String = "", @SerialName("refAnswer") val refAnswer: String = "", @SerialName("second") val second: String = "", @SerialName("secondPic") val secondPic: String = "", @SerialName("secondQuestion") val secondQuestion: String = "", @SerialName("subPrimPic") val subPrimPic: String = "", @SerialName("subjectTypeEname") val subjectTypeEname: String = "", @SerialName("third") val third: String = "", @SerialName("thirdPic") val thirdPic: String = "" )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/getExamResponse/Muban.kt
188128934
package app.xlei.vipexam.core.network.module.getExamResponse import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Muban( @SerialName("basic") val basic: String = "", @SerialName("cname") val cname: String = "", @SerialName("cunt") val cunt: Int = 0, @SerialName("ename") val ename: String = "", @SerialName("grade") val grade: String = "", @SerialName("shiti") val shiti: List<Shiti> = listOf() )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/getExamResponse/GetExamResponse.kt
4288815216
package app.xlei.vipexam.core.network.module.getExamResponse import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class GetExamResponse( @SerialName("code") val code: Int = 0, @SerialName("count") val count: Int = 0, @SerialName("examID") val examID: String = "", @SerialName("examName") val examName: String = "", @SerialName("examTypeCode") val examTypeCode: String = "", @SerialName("examstyle") val examstyle: String = "", @SerialName("msg") val msg: String = "", @SerialName("muban") val muban: List<Muban> = listOf(), @SerialName("planID") val planID: String = "", @SerialName("timelimit") val timelimit: Int = 0 )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/TranslationResponse.kt
1280449400
package app.xlei.vipexam.core.network.module import kotlinx.serialization.Serializable @Serializable data class TranslationResponse( val code: Int, val id: String, val data: String, val alternatives: List<String>, )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/momoLookUp/Total.kt
1743361055
package app.xlei.vipexam.core.network.module.momoLookUp import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Total( @SerialName("relation") val relation: String, @SerialName("value") val value: Int )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/momoLookUp/Context.kt
1452598656
package app.xlei.vipexam.core.network.module.momoLookUp import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Context( @SerialName("answers") val answers: List<String>, @SerialName("options") val options: List<Option>, @SerialName("phrase") val phrase: String, @SerialName("translation") val translation: String )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/momoLookUp/Data.kt
3607752772
package app.xlei.vipexam.core.network.module.momoLookUp import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Data( @SerialName("phrases") val phrases: List<Phrase>, @SerialName("time_cost") val timeCost: Int, @SerialName("total") val total: Total )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/momoLookUp/Highlight.kt
4126577149
package app.xlei.vipexam.core.network.module.momoLookUp import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Highlight( @SerialName("context") val context: Context )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/momoLookUp/MomoLookUpResponse.kt
410383793
package app.xlei.vipexam.core.network.module.momoLookUp import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class MomoLookUpResponse( @SerialName("data") val `data`: Data, @SerialName("errors") val errors: List<String>, @SerialName("success") val success: Boolean )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/momoLookUp/Option.kt
993485946
package app.xlei.vipexam.core.network.module.momoLookUp import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Option( @SerialName("option") val option: String, @SerialName("phrase") val phrase: String, @SerialName("translation") val translation: String )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/momoLookUp/Phrase.kt
3672884726
package app.xlei.vipexam.core.network.module.momoLookUp import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Phrase( @SerialName("context") val context: Context, @SerialName("highlight") val highlight: Highlight, @SerialName("paper_id") val paperId: String, @SerialName("path") val path: String, @SerialName("phrase_en") val phraseEn: String, @SerialName("phrase_id") val phraseId: String, @SerialName("phrase_zh") val phraseZh: String, @SerialName("source") val source: String )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/TiJiaoTest/TiJiaoTestPayload.kt
534435237
package app.xlei.vipexam.core.network.module.TiJiaoTest import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class TiJiaoTestPayload( @SerialName("account") val account: String? = null, @SerialName("count") val count: String, @SerialName("examID") val examID: String, @SerialName("examName") val examName: String, @SerialName("examStyle") val examStyle: String, @SerialName("examTypeCode") val examTypeCode: String, @SerialName("TestQuestion") val testQuestion: List<TestQuestion>, @SerialName("token") val token: String? = null )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/TiJiaoTest/TiJiaoTestResponse.kt
2533703278
package app.xlei.vipexam.core.network.module.TiJiaoTest import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class TiJiaoTestResponse( @SerialName("code") val code: Int, @SerialName("grade") val grade: Double, @SerialName("gradedCount") val gradedCount: String, @SerialName("msg") val msg: String )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/TiJiaoTest/TestQuestion.kt
1695533809
package app.xlei.vipexam.core.network.module.TiJiaoTest import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class TestQuestion( @SerialName("basic") val basic: String, @SerialName("grade") val grade: String, @SerialName("questionCode") val questionCode: String, @SerialName("questiontype") val questiontype: String, @SerialName("refAnswer") val refAnswer: String )
vipexam/core/network/src/main/java/app/xlei/vipexam/core/network/module/EudicRemoteDatasource.kt
3552708609
package app.xlei.vipexam.core.network.module import app.xlei.vipexam.core.network.module.eudic.AddNewCategoryResponse import app.xlei.vipexam.core.network.module.eudic.AddWordsResponse import app.xlei.vipexam.core.network.module.eudic.GetAllCategoryResponse import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.engine.cio.CIO import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.request.get import io.ktor.client.request.headers import io.ktor.client.request.post import io.ktor.client.request.setBody import io.ktor.client.statement.bodyAsText import io.ktor.http.ContentType import io.ktor.http.contentType import io.ktor.serialization.kotlinx.json.json import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json object EudicRemoteDatasource { lateinit var api: String private val httpClient by lazy { _httpClient.value } private val _httpClient = lazy { HttpClient(CIO) { engine { requestTimeout = 0 } install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) } } } private suspend fun getAllCategory(): Result<GetAllCategoryResponse> { return try { Result.success( httpClient.get("https://api.frdic.com/api/open/v1/studylist/category?language=en") { headers { append("Authorization", api) } }.body<GetAllCategoryResponse>().also { println(it) } ) } catch (e: Exception) { println(e) Result.failure(e) } } private suspend fun uploadAllWords(words: List<String>, id: String): Result<AddWordsResponse> { return try { Result.success( httpClient.post("https://api.frdic.com/api/open/v1/studylist/words") { headers { append("Authorization", api) } setBody( AddNewWordsPayload( id, "en", words ) ) contentType(ContentType.Application.Json) }.body<AddWordsResponse>().also { println(it) } ) } catch (e: Exception) { println(e) Result.failure(e) } } private suspend fun createNewCategory(): Result<String> { return try { Result.success( httpClient.post("https://api.frdic.com/api/open/v1/studylist/category") { headers { append("Authorization", api) } setBody("{\n \"language\": \"en\",\n \"name\": \"vipexam\"\n}") contentType(ContentType.Application.Json) }.run { bodyAsText().also { println(it) } body<AddNewCategoryResponse>().data.id } ) } catch (e: Exception) { println(e) Result.failure(e) } } suspend fun check() = getAllCategory() suspend fun sync(words: List<String>): Boolean { if (words.isEmpty()) { return false } else { getAllCategory() .onSuccess { resp -> resp.data.firstOrNull { it.name == "vipexam" } .let { data -> if (data != null) uploadAllWords(words, data.id) .onSuccess { return true } .onFailure { return false } else { createNewCategory() .onSuccess { uploadAllWords(words, it) .onSuccess { return true } .onFailure { return false } } .onFailure { return false } } } } .onFailure { return false } return false } } } @Serializable private data class AddNewWordsPayload( val id: String, val language: String, val words: List<String>, )