package idsdk.overlay import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.animation.ValueAnimator import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import com.getcapacitor.plugin.luna.idsdk.R import com.getcapacitor.plugin.luna.idsdk.databinding.FragmentOverlayBinding import idsdk.CaptureBridge import idsdk.Settings import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import ai.visionlabs.lunaid.core.api.model.DetectionError import ai.visionlabs.lunaid.core.api.model.Event class OverlayFragment : Fragment() { private var _binding: FragmentOverlayBinding? = null private val binding get() = _binding!! private var interactionAnimation: AnimatorSet? = null companion object { private const val TAG = "OverlayFragment" private const val BLINK = 1 private const val YAW_LEFT = 2 private const val YAW_RIGHT = 3 private const val PITCH_UP = 4 private const val PITCH_DOWN = 5 } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentOverlayBinding.inflate(inflater, container, false) with(binding) { overlayClose.setOnClickListener { requireActivity().finish() } } return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.overlayViewport.isVisible = true binding.overlayDetection.isVisible = Settings.overlayShowDetection val controller = CaptureBridge.controller if (controller == null) { Log.e(TAG, "onViewCreated: LunaCameraController is null") return } controller.errors .onEach { effectError -> Log.d(TAG, "error: ${effectError.error}") setTextVisibility(_binding?.overlayError, getErrorMessage(effectError.error)) delay(1000) setTextVisibility(_binding?.overlayError, null) } .flowOn(Dispatchers.Main) .launchIn(lifecycleScope) controller.events .onEach { event -> when (event) { is Event.Started -> Log.d(TAG, "event: Started") is Event.FaceFound -> Log.d(TAG, "event: FaceFound") is Event.LivenessCheckStarted -> Log.d(TAG, "event: LivenessCheckStarted") is Event.LivenessCheckEnded -> Log.d(TAG, "event: LivenessCheckEnded") is Event.InteractionStarted -> { Log.d(TAG, "event: InteractionStarted ${event.type}") setTextVisibility(_binding?.overlayInteraction, getInteractionTip(event.type)) updateInteractionAnimation(event.type) } is Event.InteractionMidway -> Log.d(TAG, "event: InteractionMidway ${event.type}") is Event.InteractionEnded -> { Log.d(TAG, "event: InteractionEnded ${event.type}") setTextVisibility(_binding?.overlayInteraction, null) stopHeadTurnAnimation() } // Все интеракции пройдены, SDK ещё делает финальные проверки. is Event.InteractionCompleted -> { Log.d(TAG, "event: InteractionCompleted") stopHeadTurnAnimation() setTextVisibility(_binding?.overlayInteraction, "Обработка…") } } } .flowOn(Dispatchers.Main) .launchIn(lifecycleScope) } private fun getErrorMessage(err: DetectionError?): String { Log.d(TAG, err.toString()) return when (err) { DetectionError.PrimaryFaceLost, DetectionError.FaceLost, DetectionError.FaceOutOfFrame, DetectionError.FaceOutOfFrameDuringInteraction, DetectionError.FaceDetectSmall -> { "Поместите лицо в центр рамки" } DetectionError.TooDark -> { "Плохие условия съемки: Слишком темно" } DetectionError.TooMuchLight -> { "Плохие условия съемки: Лицо засвечено" } DetectionError.TooIlluminated -> { "Слишком яркий свет на лице. Уберите блики" } DetectionError.TooManyFaces -> { "Убедитесь, что в кадре только Вы" } DetectionError.BadHeadPose -> { "Неправильный ракурс головы. Поверните голову к камере и держите её прямо" } DetectionError.BadEyesStatus, DetectionError.OccludedEyes -> { "Держите глаза открытыми" } DetectionError.BadQuality -> { "Низкое качество изображения. Проверьте условия съёмки" } DetectionError.BlurredFace -> { "Плохие условия съемки или лицо размыто" } DetectionError.OccludedFace -> { "Лицо перекрыто. Проверьте, что посторонние предметы не перекрывают лицо" } DetectionError.GlassesOn -> { "Пожалуйста, снимите очки" } DetectionError.FaceWithMask -> { "Пожалуйста, снимите маску" } else -> { "Неизвестная ошибка" } } } private fun getInteractionTip(interactionType: Int): String { return when (interactionType) { BLINK -> { "Моргните глазами" } YAW_LEFT -> { "Поверните голову налево и вернитесь в исходное положение" } YAW_RIGHT -> { "Поверните голову направо и вернитесь в исходное положение" } PITCH_UP -> { "Поднимите голову вверх и вернитесь в исходное положение" } PITCH_DOWN -> { "Опустите голову вниз и вернитесь в исходное положение" } else -> { "Ошибка при идентификации: $interactionType" } } } private fun setTextVisibility(textView: TextView?, text: String?) { textView ?: return textView.text = text.orEmpty() textView.isVisible = !text.isNullOrBlank() } private fun updateInteractionAnimation(interactionType: Int) { when (interactionType) { YAW_LEFT -> startHeadTurnAnimation( drawableRes = R.drawable.ic_head_turn_left, direction = -1f ) YAW_RIGHT -> startHeadTurnAnimation( drawableRes = R.drawable.ic_head_turn_right, direction = 1f ) else -> stopHeadTurnAnimation() } } private fun startHeadTurnAnimation(drawableRes: Int, direction: Float) { val icon = _binding?.overlayInteractionAnimation ?: return icon.setImageResource(drawableRes) icon.isVisible = true icon.alpha = 1f icon.translationX = 0f interactionAnimation?.cancel() val distancePx = 20f * resources.displayMetrics.density * direction val moveAnimator = ObjectAnimator.ofFloat(icon, View.TRANSLATION_X, 0f, distancePx).apply { duration = 500 repeatCount = ValueAnimator.INFINITE repeatMode = ValueAnimator.REVERSE } val alphaAnimator = ObjectAnimator.ofFloat(icon, View.ALPHA, 1f, 0.35f).apply { duration = 500 repeatCount = ValueAnimator.INFINITE repeatMode = ValueAnimator.REVERSE } interactionAnimation = AnimatorSet().apply { playTogether(moveAnimator, alphaAnimator) start() } } private fun stopHeadTurnAnimation() { interactionAnimation?.cancel() interactionAnimation = null _binding?.overlayInteractionAnimation?.apply { clearAnimation() alpha = 1f translationX = 0f isVisible = false } } override fun onDestroyView() { stopHeadTurnAnimation() super.onDestroyView() _binding = null } }