Compare commits
32
Commits
main
...
613bd90bad
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
613bd90bad | ||
|
|
9818a56fe1 | ||
|
|
f6c477c9be | ||
|
|
1246e41e4b | ||
|
|
26574808df | ||
|
|
d4c7d7180e | ||
|
|
4a85b9f83e | ||
|
|
e4057c3d6a | ||
|
|
90e8966528 | ||
|
|
c8a7494344 | ||
|
|
02614c2817 | ||
|
|
9f49f73a31 | ||
|
|
da2e69b014 | ||
|
|
f6347e99cd | ||
|
|
d40c13d802 | ||
|
|
23319cfddb | ||
|
|
6d93c1c8dd | ||
|
|
c9323f26a7 | ||
|
|
7dafd61314 | ||
|
|
d056d28d83 | ||
|
|
8570486798 | ||
|
|
208920dfea | ||
|
|
88d8dfda04 | ||
|
|
d39d85cd99 | ||
|
|
c01ce1dca0 | ||
|
|
25ac9c4c35 | ||
|
|
a3a02e623f | ||
|
|
7a654d54f0 | ||
|
|
de2aacca90 | ||
|
|
cf1c2d7d0e | ||
|
|
13cb3bfd7b | ||
|
|
bcd2162cd7 |
@@ -19,6 +19,7 @@ pubspec.lock
|
||||
*.iws
|
||||
.idea/
|
||||
.cursor
|
||||
Podfile.lock
|
||||
|
||||
# The .vscode folder contains launch configuration and tasks you configure in
|
||||
# VS Code which you may wish to be included in version control, so this line
|
||||
@@ -47,3 +48,6 @@ app.*.map.json
|
||||
/android/app/release
|
||||
/android/.kotlin
|
||||
|
||||
CLAUDE.md
|
||||
AGENTS.md
|
||||
test/
|
||||
@@ -4,7 +4,7 @@ plugins {
|
||||
id("dev.flutter.flutter-gradle-plugin")
|
||||
}
|
||||
|
||||
val appPackageName = "com.qxy.dronex"
|
||||
val appPackageName = "com.dronex.rec"
|
||||
|
||||
android {
|
||||
namespace = appPackageName
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="com.qxy.dronex">
|
||||
package="com.dronex.rec">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
@@ -10,7 +10,6 @@
|
||||
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
|
||||
<uses-permission
|
||||
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="28" />
|
||||
@@ -57,4 +56,4 @@
|
||||
<data android:mimeType="text/plain" />
|
||||
</intent>
|
||||
</queries>
|
||||
</manifest>
|
||||
</manifest>
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.dronex.rec
|
||||
|
||||
object AppConstants {
|
||||
private const val CHANNEL_NAMESPACE = "app.record_tool"
|
||||
const val PLATFORM_INFO_CHANNEL = "$CHANNEL_NAMESPACE/platform_info"
|
||||
const val RECORDING_METHOD_CHANNEL = "$CHANNEL_NAMESPACE/recording"
|
||||
const val RECORDING_EVENT_CHANNEL = "$CHANNEL_NAMESPACE/recording_events"
|
||||
const val RECORDING_ACTION_START = "$CHANNEL_NAMESPACE.recording.START"
|
||||
const val RECORDING_ACTION_STOP = "$CHANNEL_NAMESPACE.recording.STOP"
|
||||
}
|
||||
+4
-3
@@ -1,4 +1,4 @@
|
||||
package com.qxy.dronex
|
||||
package com.dronex.rec
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.ApplicationInfo
|
||||
@@ -7,8 +7,8 @@ import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.os.StatFs
|
||||
import androidx.camera.view.PreviewView
|
||||
import com.qxy.dronex.recording.RecordingPlatformHandler
|
||||
import com.qxy.dronex.recording.RecordingPreviewFactory
|
||||
import com.dronex.rec.recording.RecordingPlatformHandler
|
||||
import com.dronex.rec.recording.RecordingPreviewFactory
|
||||
import io.flutter.embedding.android.FlutterActivity
|
||||
import io.flutter.embedding.engine.FlutterEngine
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
@@ -114,6 +114,7 @@ class MainActivity : FlutterActivity() {
|
||||
"brand" to Build.BRAND,
|
||||
"model" to Build.MODEL,
|
||||
"systemVersion" to Build.VERSION.RELEASE,
|
||||
"sdkInt" to Build.VERSION.SDK_INT,
|
||||
"isPhysicalDevice" to !isEmulator,
|
||||
)
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.qxy.dronex.recording
|
||||
package com.dronex.rec.recording
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.qxy.dronex.recording
|
||||
package com.dronex.rec.recording
|
||||
|
||||
import android.app.NotificationManager
|
||||
import android.content.Context
|
||||
File diff suppressed because it is too large
Load Diff
+3
-3
@@ -1,4 +1,4 @@
|
||||
package com.qxy.dronex.recording
|
||||
package com.dronex.rec.recording
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
@@ -14,8 +14,8 @@ import android.os.PowerManager
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.LifecycleService
|
||||
import com.qxy.dronex.AppConstants
|
||||
import com.qxy.dronex.MainActivity
|
||||
import com.dronex.rec.AppConstants
|
||||
import com.dronex.rec.MainActivity
|
||||
|
||||
class RecordingForegroundService : LifecycleService() {
|
||||
private var wakeLock: PowerManager.WakeLock? = null
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.dronex.rec.recording
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.provider.MediaStore
|
||||
import androidx.camera.video.FileOutputOptions
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
object RecordingOutputFactory {
|
||||
private const val RELATIVE_PATH = "Movies/飞行极控录像工作台"
|
||||
private const val MIME_TYPE = "video/mp4"
|
||||
|
||||
fun buildSegmentOutputOptions(segmentFile: File): FileOutputOptions {
|
||||
return FileOutputOptions.Builder(segmentFile).build()
|
||||
}
|
||||
|
||||
fun createSegmentFile(
|
||||
context: Context,
|
||||
displayName: String?,
|
||||
index: Int,
|
||||
): File {
|
||||
val directory = File(context.cacheDir, "recording_segments")
|
||||
if (!directory.exists()) {
|
||||
directory.mkdirs()
|
||||
}
|
||||
val baseName = resolveFileName(displayName).removeSuffix(".mp4")
|
||||
return File(directory, "${baseName}_${System.currentTimeMillis()}_part$index.mp4")
|
||||
}
|
||||
|
||||
fun createMergeFile(context: Context, displayName: String?): File {
|
||||
val directory = File(context.cacheDir, "recording_segments")
|
||||
if (!directory.exists()) {
|
||||
directory.mkdirs()
|
||||
}
|
||||
val baseName = resolveFileName(displayName).removeSuffix(".mp4")
|
||||
return File(directory, "${baseName}_${System.currentTimeMillis()}_merged.mp4")
|
||||
}
|
||||
|
||||
fun publishToMediaStore(
|
||||
context: Context,
|
||||
displayName: String?,
|
||||
sourceFile: File,
|
||||
): String? {
|
||||
val fileName = resolveFileName(displayName)
|
||||
val contentValues =
|
||||
ContentValues().apply {
|
||||
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
|
||||
put(MediaStore.MediaColumns.MIME_TYPE, MIME_TYPE)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
put(MediaStore.Video.Media.RELATIVE_PATH, RELATIVE_PATH)
|
||||
put(MediaStore.Video.Media.IS_PENDING, 1)
|
||||
}
|
||||
}
|
||||
|
||||
val resolver = context.contentResolver
|
||||
val uri =
|
||||
resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, contentValues)
|
||||
?: return null
|
||||
try {
|
||||
val outputStream =
|
||||
resolver.openOutputStream(uri)
|
||||
?: throw IllegalStateException("Cannot open MediaStore output stream")
|
||||
outputStream.use { output ->
|
||||
FileInputStream(sourceFile).use { input -> input.copyTo(output) }
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
val publishedValues =
|
||||
ContentValues().apply { put(MediaStore.Video.Media.IS_PENDING, 0) }
|
||||
resolver.update(uri, publishedValues, null, null)
|
||||
}
|
||||
return uri.toString()
|
||||
} catch (error: Exception) {
|
||||
resolver.delete(uri, null, null)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
fun publishPartToMediaStore(
|
||||
context: Context,
|
||||
displayName: String?,
|
||||
sourceFile: File,
|
||||
partIndex: Int,
|
||||
): String? {
|
||||
val resolvedName = resolveFileName(displayName)
|
||||
val partName = resolvedName.replace(".mp4", "_part$partIndex.mp4")
|
||||
return publishToMediaStore(context, partName, sourceFile)
|
||||
}
|
||||
|
||||
fun resolveFileName(displayName: String?): String {
|
||||
val trimmed = displayName?.trim().orEmpty()
|
||||
if (trimmed.isNotEmpty()) {
|
||||
return if (trimmed.lowercase(Locale.US).endsWith(".mp4")) {
|
||||
trimmed
|
||||
} else {
|
||||
"$trimmed.mp4"
|
||||
}
|
||||
}
|
||||
val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())
|
||||
return "REC_$timestamp.mp4"
|
||||
}
|
||||
}
|
||||
+25
-7
@@ -1,12 +1,12 @@
|
||||
package com.qxy.dronex.recording
|
||||
package com.dronex.rec.recording
|
||||
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import androidx.core.view.WindowCompat
|
||||
import androidx.core.view.WindowInsetsCompat
|
||||
import androidx.core.view.WindowInsetsControllerCompat
|
||||
import com.qxy.dronex.AppConstants
|
||||
import com.qxy.dronex.MainActivity
|
||||
import com.dronex.rec.AppConstants
|
||||
import com.dronex.rec.MainActivity
|
||||
import io.flutter.plugin.common.BinaryMessenger
|
||||
import io.flutter.plugin.common.EventChannel
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
@@ -50,6 +50,11 @@ class RecordingPlatformHandler(
|
||||
startRecording(withAudio, enableDnd, displayName, result)
|
||||
}
|
||||
"stopRecording" -> stopRecording(result)
|
||||
"getZoomCapabilities" -> result.success(controller.zoomCapabilitiesMap())
|
||||
"setZoomRatio" -> {
|
||||
val ratio = call.argument<Double>("zoomRatio") ?: 1.0
|
||||
setZoomRatio(ratio, result)
|
||||
}
|
||||
"disposePreview" -> {
|
||||
controller.unbind()
|
||||
result.success(null)
|
||||
@@ -172,16 +177,29 @@ class RecordingPlatformHandler(
|
||||
}
|
||||
}
|
||||
|
||||
private fun setZoomRatio(ratio: Double, result: MethodChannel.Result) {
|
||||
controller.setZoomRatio(ratio) { success, capabilities, message ->
|
||||
mainHandler.post {
|
||||
if (success) {
|
||||
result.success(capabilities)
|
||||
} else {
|
||||
result.error("ZOOM_FAILED", message ?: "Failed to set camera zoom", null)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun deliverStopResult(result: MethodChannel.Result, path: String?) {
|
||||
val gallerySaved = path != null && controller.status.state != RecordingState.ERROR
|
||||
val fileSaved = path != null && controller.status.state != RecordingState.ERROR
|
||||
val payload =
|
||||
mutableMapOf<String, Any?>(
|
||||
"outputPath" to path,
|
||||
"status" to controller.status.toMap(),
|
||||
"gallerySaved" to gallerySaved,
|
||||
"fileSaved" to fileSaved,
|
||||
"segmentOutputPaths" to controller.segmentOutputPaths(),
|
||||
)
|
||||
if (!gallerySaved) {
|
||||
payload["galleryErrorMessage"] = controller.status.message ?: "保存到相册失败"
|
||||
if (!fileSaved) {
|
||||
payload["fileErrorMessage"] = controller.status.message ?: "保存到文件夹失败"
|
||||
}
|
||||
result.success(payload)
|
||||
}
|
||||
+2
-2
@@ -1,9 +1,9 @@
|
||||
package com.qxy.dronex.recording
|
||||
package com.dronex.rec.recording
|
||||
|
||||
import android.content.Context
|
||||
import android.view.View
|
||||
import androidx.camera.view.PreviewView
|
||||
import com.qxy.dronex.MainActivity
|
||||
import com.dronex.rec.MainActivity
|
||||
import io.flutter.plugin.common.StandardMessageCodec
|
||||
import io.flutter.plugin.platform.PlatformView
|
||||
import io.flutter.plugin.platform.PlatformViewFactory
|
||||
@@ -0,0 +1,174 @@
|
||||
package com.dronex.rec.recording
|
||||
|
||||
import android.media.MediaCodec
|
||||
import android.media.MediaExtractor
|
||||
import android.media.MediaFormat
|
||||
import android.media.MediaMuxer
|
||||
import java.io.File
|
||||
import java.io.FileInputStream
|
||||
import java.io.FileOutputStream
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
object RecordingSegmentMuxer {
|
||||
fun mergeOrCopy(
|
||||
segments: List<File>,
|
||||
outputFile: File,
|
||||
) {
|
||||
val validSegments = segments.filter { it.exists() && it.length() > 0L }
|
||||
require(validSegments.isNotEmpty()) { "No recording segments were generated" }
|
||||
if (validSegments.size == 1) {
|
||||
copyFile(validSegments.first(), outputFile)
|
||||
return
|
||||
}
|
||||
|
||||
MediaMuxer(outputFile.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4).use {
|
||||
muxer ->
|
||||
val firstTracks = readTrackFormats(validSegments.first())
|
||||
val videoTrack = firstTracks.video?.let { muxer.addTrack(it) }
|
||||
val audioTrack = firstTracks.audio?.let { muxer.addTrack(it) }
|
||||
require(videoTrack != null) { "No video track in recording segment" }
|
||||
|
||||
muxer.start()
|
||||
var offsetUs = 0L
|
||||
validSegments.forEach { segment ->
|
||||
val durationUs =
|
||||
copySegmentTracks(
|
||||
segment = segment,
|
||||
muxer = muxer,
|
||||
videoOutputTrack = videoTrack,
|
||||
audioOutputTrack = audioTrack,
|
||||
offsetUs = offsetUs,
|
||||
)
|
||||
offsetUs += durationUs + 1L
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun copyFile(source: File, target: File) {
|
||||
FileInputStream(source).use { input ->
|
||||
FileOutputStream(target).use { output -> input.copyTo(output) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun readTrackFormats(file: File): TrackFormats {
|
||||
val extractor = MediaExtractor()
|
||||
extractor.setDataSource(file.absolutePath)
|
||||
try {
|
||||
var video: MediaFormat? = null
|
||||
var audio: MediaFormat? = null
|
||||
for (index in 0 until extractor.trackCount) {
|
||||
val format = extractor.getTrackFormat(index)
|
||||
val mime = format.getString(MediaFormat.KEY_MIME).orEmpty()
|
||||
when {
|
||||
mime.startsWith("video/") && video == null -> video = format
|
||||
mime.startsWith("audio/") && audio == null -> audio = format
|
||||
}
|
||||
}
|
||||
return TrackFormats(video = video, audio = audio)
|
||||
} finally {
|
||||
extractor.release()
|
||||
}
|
||||
}
|
||||
|
||||
private fun copySegmentTracks(
|
||||
segment: File,
|
||||
muxer: MediaMuxer,
|
||||
videoOutputTrack: Int,
|
||||
audioOutputTrack: Int?,
|
||||
offsetUs: Long,
|
||||
): Long {
|
||||
var segmentDurationUs = 0L
|
||||
segmentDurationUs =
|
||||
maxOf(
|
||||
segmentDurationUs,
|
||||
copyTrack(segment, muxer, "video/", videoOutputTrack, offsetUs),
|
||||
)
|
||||
if (audioOutputTrack != null) {
|
||||
segmentDurationUs =
|
||||
maxOf(
|
||||
segmentDurationUs,
|
||||
copyTrack(segment, muxer, "audio/", audioOutputTrack, offsetUs),
|
||||
)
|
||||
}
|
||||
return segmentDurationUs
|
||||
}
|
||||
|
||||
private fun copyTrack(
|
||||
segment: File,
|
||||
muxer: MediaMuxer,
|
||||
mimePrefix: String,
|
||||
outputTrack: Int,
|
||||
offsetUs: Long,
|
||||
): Long {
|
||||
val extractor = MediaExtractor()
|
||||
extractor.setDataSource(segment.absolutePath)
|
||||
try {
|
||||
val inputTrack = findTrack(extractor, mimePrefix) ?: return 0L
|
||||
extractor.selectTrack(inputTrack)
|
||||
val bufferSize = trackBufferSize(extractor.getTrackFormat(inputTrack))
|
||||
val buffer = ByteBuffer.allocate(bufferSize)
|
||||
val info = MediaCodec.BufferInfo()
|
||||
var firstSampleTimeUs: Long? = null
|
||||
var lastSampleTimeUs = 0L
|
||||
|
||||
while (true) {
|
||||
buffer.clear()
|
||||
val sampleSize = extractor.readSampleData(buffer, 0)
|
||||
if (sampleSize < 0) break
|
||||
|
||||
val sampleTimeUs = extractor.sampleTime
|
||||
val baseTimeUs = firstSampleTimeUs ?: sampleTimeUs.also { firstSampleTimeUs = it }
|
||||
val normalizedTimeUs = (sampleTimeUs - baseTimeUs).coerceAtLeast(0L)
|
||||
info.set(
|
||||
0,
|
||||
sampleSize,
|
||||
offsetUs + normalizedTimeUs,
|
||||
extractor.sampleFlags,
|
||||
)
|
||||
muxer.writeSampleData(outputTrack, buffer, info)
|
||||
lastSampleTimeUs = normalizedTimeUs
|
||||
extractor.advance()
|
||||
}
|
||||
return lastSampleTimeUs
|
||||
} finally {
|
||||
extractor.release()
|
||||
}
|
||||
}
|
||||
|
||||
private fun findTrack(extractor: MediaExtractor, mimePrefix: String): Int? {
|
||||
for (index in 0 until extractor.trackCount) {
|
||||
val mime = extractor.getTrackFormat(index).getString(MediaFormat.KEY_MIME).orEmpty()
|
||||
if (mime.startsWith(mimePrefix)) {
|
||||
return index
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun trackBufferSize(format: MediaFormat): Int {
|
||||
return if (format.containsKey(MediaFormat.KEY_MAX_INPUT_SIZE)) {
|
||||
format.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE).coerceAtLeast(DEFAULT_BUFFER_SIZE)
|
||||
} else {
|
||||
DEFAULT_BUFFER_SIZE
|
||||
}
|
||||
}
|
||||
|
||||
private data class TrackFormats(
|
||||
val video: MediaFormat?,
|
||||
val audio: MediaFormat?,
|
||||
)
|
||||
|
||||
private const val DEFAULT_BUFFER_SIZE = 2 * 1024 * 1024
|
||||
}
|
||||
|
||||
private inline fun MediaMuxer.use(block: (MediaMuxer) -> Unit) {
|
||||
try {
|
||||
block(this)
|
||||
} finally {
|
||||
try {
|
||||
stop()
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
release()
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.qxy.dronex.recording
|
||||
package com.dronex.rec.recording
|
||||
|
||||
import android.content.Context
|
||||
import androidx.lifecycle.LifecycleService
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.qxy.dronex.recording
|
||||
package com.dronex.rec.recording
|
||||
|
||||
enum class RecordingState {
|
||||
IDLE,
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.qxy.dronex
|
||||
|
||||
object AppConstants {
|
||||
const val PACKAGE_NAME = "com.qxy.dronex"
|
||||
const val PLATFORM_INFO_CHANNEL = "$PACKAGE_NAME/platform_info"
|
||||
const val RECORDING_METHOD_CHANNEL = "$PACKAGE_NAME/recording"
|
||||
const val RECORDING_EVENT_CHANNEL = "$PACKAGE_NAME/recording_events"
|
||||
const val RECORDING_ACTION_START = "$PACKAGE_NAME.recording.START"
|
||||
const val RECORDING_ACTION_STOP = "$PACKAGE_NAME.recording.STOP"
|
||||
}
|
||||
@@ -1,248 +0,0 @@
|
||||
package com.qxy.dronex.recording
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.camera.core.CameraSelector
|
||||
import androidx.camera.core.Preview
|
||||
import androidx.camera.lifecycle.ProcessCameraProvider
|
||||
import androidx.camera.video.Quality
|
||||
import androidx.camera.video.QualitySelector
|
||||
import androidx.camera.video.Recorder
|
||||
import androidx.camera.video.Recording
|
||||
import androidx.camera.video.VideoCapture
|
||||
import androidx.camera.video.VideoRecordEvent
|
||||
import androidx.camera.view.PreviewView
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import java.util.concurrent.Executor
|
||||
|
||||
class RecordingCameraController(
|
||||
private val appContext: Context,
|
||||
) {
|
||||
private val mainExecutor: Executor = ContextCompat.getMainExecutor(appContext)
|
||||
|
||||
private var cameraProvider: ProcessCameraProvider? = null
|
||||
private var preview: Preview? = null
|
||||
private var videoCapture: VideoCapture<Recorder>? = null
|
||||
private var activeRecording: Recording? = null
|
||||
private var boundLifecycleOwner: LifecycleOwner? = null
|
||||
|
||||
var status: RecordingStatus = RecordingStatus(RecordingState.IDLE)
|
||||
private set
|
||||
|
||||
var statusListener: ((RecordingStatus) -> Unit)? = null
|
||||
|
||||
private var recordingStartedAt: Long = 0L
|
||||
private var latestOutputPath: String? = null
|
||||
private var pendingStopCallback: ((String?) -> Unit)? = null
|
||||
|
||||
fun bindPreview(
|
||||
lifecycleOwner: LifecycleOwner,
|
||||
previewView: PreviewView,
|
||||
onReady: (Boolean) -> Unit,
|
||||
) {
|
||||
val future = ProcessCameraProvider.getInstance(appContext)
|
||||
future.addListener(
|
||||
{
|
||||
try {
|
||||
val provider = future.get()
|
||||
cameraProvider = provider
|
||||
boundLifecycleOwner = lifecycleOwner
|
||||
|
||||
preview =
|
||||
Preview.Builder().build().also {
|
||||
it.surfaceProvider = previewView.surfaceProvider
|
||||
}
|
||||
|
||||
val recorder =
|
||||
Recorder.Builder()
|
||||
.setQualitySelector(QualitySelector.from(Quality.HD))
|
||||
.build()
|
||||
videoCapture = VideoCapture.withOutput(recorder)
|
||||
|
||||
provider.unbindAll()
|
||||
provider.bindToLifecycle(
|
||||
lifecycleOwner,
|
||||
CameraSelector.DEFAULT_BACK_CAMERA,
|
||||
preview,
|
||||
videoCapture,
|
||||
)
|
||||
|
||||
updateStatus(RecordingStatus(RecordingState.PREVIEWING))
|
||||
onReady(true)
|
||||
} catch (error: Exception) {
|
||||
Log.e(TAG, "bindPreview failed", error)
|
||||
updateStatus(
|
||||
RecordingStatus(
|
||||
RecordingState.ERROR,
|
||||
message = error.message,
|
||||
),
|
||||
)
|
||||
onReady(false)
|
||||
}
|
||||
},
|
||||
mainExecutor,
|
||||
)
|
||||
}
|
||||
|
||||
fun rebindForRecording(
|
||||
lifecycleOwner: LifecycleOwner,
|
||||
previewView: PreviewView,
|
||||
onReady: (Boolean) -> Unit,
|
||||
) {
|
||||
val provider = cameraProvider
|
||||
if (provider == null) {
|
||||
bindPreview(lifecycleOwner, previewView, onReady)
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
boundLifecycleOwner === lifecycleOwner &&
|
||||
preview != null &&
|
||||
videoCapture != null
|
||||
) {
|
||||
onReady(true)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
boundLifecycleOwner = lifecycleOwner
|
||||
provider.unbindAll()
|
||||
provider.bindToLifecycle(
|
||||
lifecycleOwner,
|
||||
CameraSelector.DEFAULT_BACK_CAMERA,
|
||||
preview,
|
||||
videoCapture,
|
||||
)
|
||||
onReady(true)
|
||||
} catch (error: Exception) {
|
||||
Log.e(TAG, "rebindForRecording failed", error)
|
||||
onReady(false)
|
||||
}
|
||||
}
|
||||
|
||||
fun startRecording(
|
||||
withAudio: Boolean,
|
||||
displayName: String?,
|
||||
onStarted: (Boolean, String?) -> Unit,
|
||||
) {
|
||||
val capture = videoCapture
|
||||
if (capture == null || boundLifecycleOwner == null) {
|
||||
onStarted(false, "Camera not ready")
|
||||
return
|
||||
}
|
||||
|
||||
if (activeRecording != null) {
|
||||
onStarted(false, "Already recording")
|
||||
return
|
||||
}
|
||||
|
||||
val outputOptions =
|
||||
RecordingOutputFactory.buildMediaStoreOutputOptions(
|
||||
appContext,
|
||||
displayName,
|
||||
)
|
||||
latestOutputPath = null
|
||||
|
||||
val pending =
|
||||
capture.output.prepareRecording(appContext, outputOptions).apply {
|
||||
if (withAudio) {
|
||||
val granted =
|
||||
ContextCompat.checkSelfPermission(
|
||||
appContext,
|
||||
android.Manifest.permission.RECORD_AUDIO,
|
||||
) == android.content.pm.PackageManager.PERMISSION_GRANTED
|
||||
if (granted) {
|
||||
withAudioEnabled()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
recordingStartedAt = System.currentTimeMillis()
|
||||
updateStatus(
|
||||
RecordingStatus(
|
||||
RecordingState.RECORDING,
|
||||
outputPath = latestOutputPath,
|
||||
),
|
||||
)
|
||||
|
||||
activeRecording =
|
||||
pending.start(mainExecutor) { event ->
|
||||
when (event) {
|
||||
is VideoRecordEvent.Start -> Unit
|
||||
is VideoRecordEvent.Finalize -> {
|
||||
activeRecording = null
|
||||
if (event.hasError()) {
|
||||
updateStatus(
|
||||
RecordingStatus(
|
||||
RecordingState.ERROR,
|
||||
message = event.cause?.message
|
||||
?: "Recording failed",
|
||||
),
|
||||
)
|
||||
} else {
|
||||
latestOutputPath = event.outputResults.outputUri.toString()
|
||||
updateStatus(
|
||||
RecordingStatus(
|
||||
RecordingState.PREVIEWING,
|
||||
outputPath = latestOutputPath,
|
||||
elapsedMillis =
|
||||
System.currentTimeMillis() -
|
||||
recordingStartedAt,
|
||||
),
|
||||
)
|
||||
}
|
||||
val stopCallback = pendingStopCallback
|
||||
pendingStopCallback = null
|
||||
stopCallback?.invoke(latestOutputPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onStarted(true, latestOutputPath ?: "recording")
|
||||
}
|
||||
|
||||
fun stopRecording(onStopped: (String?) -> Unit) {
|
||||
val recording = activeRecording
|
||||
if (recording == null) {
|
||||
onStopped(latestOutputPath)
|
||||
return
|
||||
}
|
||||
|
||||
pendingStopCallback = onStopped
|
||||
updateStatus(
|
||||
RecordingStatus(
|
||||
RecordingState.STOPPING,
|
||||
outputPath = latestOutputPath,
|
||||
),
|
||||
)
|
||||
|
||||
recording.stop()
|
||||
activeRecording = null
|
||||
}
|
||||
|
||||
fun unbind() {
|
||||
activeRecording?.stop()
|
||||
activeRecording = null
|
||||
cameraProvider?.unbindAll()
|
||||
cameraProvider = null
|
||||
preview = null
|
||||
videoCapture = null
|
||||
boundLifecycleOwner = null
|
||||
updateStatus(RecordingStatus(RecordingState.IDLE))
|
||||
}
|
||||
|
||||
fun elapsedMillis(): Long {
|
||||
if (status.state != RecordingState.RECORDING) return 0L
|
||||
return System.currentTimeMillis() - recordingStartedAt
|
||||
}
|
||||
|
||||
private fun updateStatus(next: RecordingStatus) {
|
||||
status = next
|
||||
statusListener?.invoke(next)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "RecordingCamera"
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.qxy.dronex.recording
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.provider.MediaStore
|
||||
import androidx.camera.video.MediaStoreOutputOptions
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
object RecordingOutputFactory {
|
||||
private const val RELATIVE_PATH = "Movies/飞行极控录像工作台"
|
||||
private const val MIME_TYPE = "video/mp4"
|
||||
|
||||
fun buildMediaStoreOutputOptions(
|
||||
context: Context,
|
||||
displayName: String?,
|
||||
): MediaStoreOutputOptions {
|
||||
val fileName = resolveFileName(displayName)
|
||||
val contentValues =
|
||||
ContentValues().apply {
|
||||
put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
|
||||
put(MediaStore.MediaColumns.MIME_TYPE, MIME_TYPE)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
put(MediaStore.Video.Media.RELATIVE_PATH, RELATIVE_PATH)
|
||||
}
|
||||
}
|
||||
|
||||
return MediaStoreOutputOptions.Builder(
|
||||
context.contentResolver,
|
||||
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
|
||||
)
|
||||
.setContentValues(contentValues)
|
||||
.build()
|
||||
}
|
||||
|
||||
fun resolveFileName(displayName: String?): String {
|
||||
val trimmed = displayName?.trim().orEmpty()
|
||||
if (trimmed.isNotEmpty()) {
|
||||
return if (trimmed.lowercase(Locale.US).endsWith(".mp4")) {
|
||||
trimmed
|
||||
} else {
|
||||
"$trimmed.mp4"
|
||||
}
|
||||
}
|
||||
val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())
|
||||
return "REC_$timestamp.mp4"
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "xcode build server",
|
||||
"version": "1.3.0",
|
||||
"bspVersion": "2.2.0",
|
||||
"languages": [
|
||||
"c",
|
||||
"cpp",
|
||||
"objective-c",
|
||||
"objective-cpp",
|
||||
"swift"
|
||||
],
|
||||
"argv": [
|
||||
"/opt/homebrew/bin/xcode-build-server"
|
||||
],
|
||||
"workspace": "/Users/ZhuanZ/Documents/gdfw/record-tool/ios/Runner.xcworkspace",
|
||||
"build_root": "/Users/ZhuanZ/Library/Developer/Xcode/DerivedData/Runner-ckjfuyjdkgumnpbnnftroxddsppq",
|
||||
"scheme": "Runner",
|
||||
"kind": "xcode"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
flutter clean
|
||||
flutter pub get
|
||||
rm -rf ios/Pods
|
||||
rm -rf ios/Podfile.lock
|
||||
cd ios
|
||||
pod install
|
||||
cd ..
|
||||
@@ -1,2 +1,3 @@
|
||||
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
|
||||
#include "Generated.xcconfig"
|
||||
FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}"
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
|
||||
#include "Generated.xcconfig"
|
||||
FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}"
|
||||
|
||||
+27
-2
@@ -45,9 +45,34 @@ post_install do |installer|
|
||||
'$(inherited)',
|
||||
'PERMISSION_CAMERA=1',
|
||||
'PERMISSION_MICROPHONE=1',
|
||||
'PERMISSION_PHOTOS=1',
|
||||
'PERMISSION_PHOTOS_ADD_ONLY=1',
|
||||
]
|
||||
end
|
||||
end
|
||||
|
||||
pods_runner_dir = File.join(
|
||||
installer.sandbox.root,
|
||||
'Target Support Files',
|
||||
'Pods-Runner'
|
||||
)
|
||||
Dir.glob(File.join(pods_runner_dir, 'Pods-Runner.*.xcconfig')).each do |config_path|
|
||||
config = File.read(config_path)
|
||||
config.gsub!(
|
||||
'FRAMEWORK_SEARCH_PATHS = $(inherited)',
|
||||
'FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}"'
|
||||
)
|
||||
File.write(config_path, config)
|
||||
end
|
||||
|
||||
Dir.glob(File.join(pods_runner_dir, 'Pods-Runner-frameworks-*input-files.xcfilelist')).each do |file_list_path|
|
||||
file_list = File.read(file_list_path)
|
||||
file_list.gsub!('${BUILT_PRODUCTS_DIR}/', '${PODS_CONFIGURATION_BUILD_DIR}/')
|
||||
File.write(file_list_path, file_list)
|
||||
end
|
||||
|
||||
frameworks_script = File.join(pods_runner_dir, 'Pods-Runner-frameworks.sh')
|
||||
if File.exist?(frameworks_script)
|
||||
script = File.read(frameworks_script)
|
||||
script.gsub!('${BUILT_PRODUCTS_DIR}/', '${PODS_CONFIGURATION_BUILD_DIR}/')
|
||||
File.write(frameworks_script, script)
|
||||
end
|
||||
end
|
||||
|
||||
+1
-8
@@ -2,9 +2,6 @@ PODS:
|
||||
- connectivity_plus (0.0.1):
|
||||
- Flutter
|
||||
- Flutter (1.0.0)
|
||||
- path_provider_foundation (0.0.1):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- permission_handler_apple (9.4.8):
|
||||
- Flutter
|
||||
- shared_preferences_foundation (0.0.1):
|
||||
@@ -19,7 +16,6 @@ PODS:
|
||||
DEPENDENCIES:
|
||||
- connectivity_plus (from `.symlinks/plugins/connectivity_plus/ios`)
|
||||
- Flutter (from `Flutter`)
|
||||
- path_provider_foundation (from `.symlinks/plugins/path_provider_foundation/darwin`)
|
||||
- permission_handler_apple (from `.symlinks/plugins/permission_handler_apple/ios`)
|
||||
- shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`)
|
||||
- sqflite_darwin (from `.symlinks/plugins/sqflite_darwin/darwin`)
|
||||
@@ -30,8 +26,6 @@ EXTERNAL SOURCES:
|
||||
:path: ".symlinks/plugins/connectivity_plus/ios"
|
||||
Flutter:
|
||||
:path: Flutter
|
||||
path_provider_foundation:
|
||||
:path: ".symlinks/plugins/path_provider_foundation/darwin"
|
||||
permission_handler_apple:
|
||||
:path: ".symlinks/plugins/permission_handler_apple/ios"
|
||||
shared_preferences_foundation:
|
||||
@@ -44,12 +38,11 @@ EXTERNAL SOURCES:
|
||||
SPEC CHECKSUMS:
|
||||
connectivity_plus: cb623214f4e1f6ef8fe7403d580fdad517d2f7dd
|
||||
Flutter: cabc95a1d2626b1b06e7179b784ebcf0c0cde467
|
||||
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
|
||||
permission_handler_apple: 92d754bbaa7361d436db2d6c3c1c2a0fdcec462e
|
||||
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
|
||||
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
|
||||
url_launcher_ios: 7a95fa5b60cc718a708b8f2966718e93db0cef1b
|
||||
|
||||
PODFILE CHECKSUM: 5a82b772179df87e6518bddc6f9bb8b4053ce48b
|
||||
PODFILE CHECKSUM: 858401fbd980bedce6ecd2f9b429bf271f11f74b
|
||||
|
||||
COCOAPODS: 1.16.2
|
||||
|
||||
@@ -495,16 +495,22 @@
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CODE_SIGN_IDENTITY = "Apple Development";
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
|
||||
DEVELOPMENT_TEAM = 35634V629S;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
"DEVELOPMENT_TEAM[sdk=iphoneos*]" = MT26BPCKF6;
|
||||
ENABLE_BITCODE = NO;
|
||||
INFOPLIST_FILE = Runner/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.qxy.dronex;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.dronex.rec;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = "dev-profile-dronex";
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
|
||||
SWIFT_VERSION = 5.0;
|
||||
VERSIONING_SYSTEM = "apple-generic";
|
||||
@@ -678,16 +684,22 @@
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CODE_SIGN_IDENTITY = "Apple Development";
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
|
||||
DEVELOPMENT_TEAM = 35634V629S;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
"DEVELOPMENT_TEAM[sdk=iphoneos*]" = MT26BPCKF6;
|
||||
ENABLE_BITCODE = NO;
|
||||
INFOPLIST_FILE = Runner/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.qxy.dronex;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.dronex.rec;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = "dev-profile-dronex";
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
@@ -701,16 +713,22 @@
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CODE_SIGN_IDENTITY = "Apple Development";
|
||||
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
|
||||
CODE_SIGN_STYLE = Manual;
|
||||
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
|
||||
DEVELOPMENT_TEAM = 35634V629S;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
"DEVELOPMENT_TEAM[sdk=iphoneos*]" = MT26BPCKF6;
|
||||
ENABLE_BITCODE = NO;
|
||||
INFOPLIST_FILE = Runner/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.qxy.dronex;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.dronex.rec;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]" = "dev-profile-dronex";
|
||||
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
|
||||
SWIFT_VERSION = 5.0;
|
||||
VERSIONING_SYSTEM = "apple-generic";
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"filename" : "startup_background.png",
|
||||
"idiom" : "universal",
|
||||
"scale" : "1x"
|
||||
}
|
||||
],
|
||||
"info" : {
|
||||
"author" : "xcode",
|
||||
"version" : 1
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 262 KiB |
@@ -16,13 +16,15 @@
|
||||
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<subviews>
|
||||
<imageView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" image="LaunchImage" translatesAutoresizingMaskIntoConstraints="NO" id="YRO-k0-Ey4">
|
||||
<imageView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" image="StartupBackground" translatesAutoresizingMaskIntoConstraints="NO" id="YRO-k0-Ey4">
|
||||
</imageView>
|
||||
</subviews>
|
||||
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<constraints>
|
||||
<constraint firstItem="YRO-k0-Ey4" firstAttribute="centerX" secondItem="Ze5-6b-2t3" secondAttribute="centerX" id="1a2-6s-vTC"/>
|
||||
<constraint firstItem="YRO-k0-Ey4" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="centerY" id="4X2-HB-R7a"/>
|
||||
<constraint firstItem="YRO-k0-Ey4" firstAttribute="top" secondItem="Ze5-6b-2t3" secondAttribute="top" id="1a2-6s-vTC"/>
|
||||
<constraint firstItem="YRO-k0-Ey4" firstAttribute="bottom" secondItem="Ze5-6b-2t3" secondAttribute="bottom" id="4X2-HB-R7a"/>
|
||||
<constraint firstItem="YRO-k0-Ey4" firstAttribute="leading" secondItem="Ze5-6b-2t3" secondAttribute="leading" id="E8f-e3-JEx"/>
|
||||
<constraint firstItem="YRO-k0-Ey4" firstAttribute="trailing" secondItem="Ze5-6b-2t3" secondAttribute="trailing" id="rwG-Bh-0uU"/>
|
||||
</constraints>
|
||||
</view>
|
||||
</viewController>
|
||||
@@ -32,6 +34,6 @@
|
||||
</scene>
|
||||
</scenes>
|
||||
<resources>
|
||||
<image name="LaunchImage" width="168" height="185"/>
|
||||
<image name="StartupBackground" width="750" height="1624"/>
|
||||
</resources>
|
||||
</document>
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="24412" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
|
||||
<device id="retina6_12" orientation="portrait" appearance="light"/>
|
||||
<dependencies>
|
||||
<deployment identifier="iOS"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="24405"/>
|
||||
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
|
||||
</dependencies>
|
||||
<scenes>
|
||||
<!--Flutter View Controller-->
|
||||
@@ -14,13 +16,28 @@
|
||||
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
|
||||
</layoutGuides>
|
||||
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
|
||||
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="393" height="852"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
|
||||
<subviews>
|
||||
<imageView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="scaleToFill" image="StartupBackground" translatesAutoresizingMaskIntoConstraints="NO" id="YQm-Ov-qw7">
|
||||
<rect key="frame" x="0.0" y="0.0" width="393" height="852"/>
|
||||
</imageView>
|
||||
</subviews>
|
||||
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<constraints>
|
||||
<constraint firstItem="YQm-Ov-qw7" firstAttribute="top" secondItem="8bC-Xf-vdC" secondAttribute="top" id="7pp-OK-Dgk"/>
|
||||
<constraint firstItem="YQm-Ov-qw7" firstAttribute="bottom" secondItem="8bC-Xf-vdC" secondAttribute="bottom" id="Hbf-gY-rbf"/>
|
||||
<constraint firstItem="YQm-Ov-qw7" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leading" id="WPc-7k-20p"/>
|
||||
<constraint firstItem="YQm-Ov-qw7" firstAttribute="trailing" secondItem="8bC-Xf-vdC" secondAttribute="trailing" id="w1G-WA-3QR"/>
|
||||
</constraints>
|
||||
</view>
|
||||
</viewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="139" y="122"/>
|
||||
</scene>
|
||||
</scenes>
|
||||
<resources>
|
||||
<image name="StartupBackground" width="750" height="1624"/>
|
||||
</resources>
|
||||
</document>
|
||||
|
||||
@@ -30,8 +30,10 @@
|
||||
<string>需要访问相机以显示预览并录制视频。</string>
|
||||
<key>NSMicrophoneUsageDescription</key>
|
||||
<string>需要访问麦克风以录制视频声音;未授权时将静音录制。</string>
|
||||
<key>NSPhotoLibraryAddUsageDescription</key>
|
||||
<string>需要将录制的视频保存到相册。</string>
|
||||
<key>UIFileSharingEnabled</key>
|
||||
<true/>
|
||||
<key>LSSupportsOpeningDocumentsInPlace</key>
|
||||
<true/>
|
||||
<key>UIApplicationSceneManifest</key>
|
||||
<dict>
|
||||
<key>UIApplicationSupportsMultipleScenes</key>
|
||||
|
||||
@@ -4,7 +4,7 @@ import UIKit
|
||||
final class PlatformInfoPlugin: NSObject, FlutterPlugin {
|
||||
static func register(with registrar: FlutterPluginRegistrar) {
|
||||
let channel = FlutterMethodChannel(
|
||||
name: "com.qxy.dronex/platform_info",
|
||||
name: "app.record_tool/platform_info",
|
||||
binaryMessenger: registrar.messenger()
|
||||
)
|
||||
let plugin = PlatformInfoPlugin()
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import AVFoundation
|
||||
import Flutter
|
||||
import Photos
|
||||
import UIKit
|
||||
|
||||
private enum RecordingState: String {
|
||||
@@ -110,12 +109,13 @@ private final class RecordingCameraController: NSObject, AVCaptureFileOutputReco
|
||||
private var audioInput: AVCaptureDeviceInput?
|
||||
private var configured = false
|
||||
private var latestOutputPath: String?
|
||||
private var latestGallerySaved = true
|
||||
private var latestGalleryErrorMessage: String?
|
||||
private var latestFileSaved = true
|
||||
private var latestFileErrorMessage: String?
|
||||
private var pendingDisplayName: String?
|
||||
private var recordingStartedAt: Date?
|
||||
private var elapsedTimer: Timer?
|
||||
private var pendingStopResult: FlutterResult?
|
||||
private var currentZoomRatio: CGFloat = 1.0
|
||||
|
||||
private(set) var status = RecordingStatus(state: .idle) {
|
||||
didSet {
|
||||
@@ -215,10 +215,10 @@ private final class RecordingCameraController: NSObject, AVCaptureFileOutputReco
|
||||
}
|
||||
|
||||
self.pendingDisplayName = displayName
|
||||
self.latestGallerySaved = true
|
||||
self.latestGalleryErrorMessage = nil
|
||||
self.latestFileSaved = true
|
||||
self.latestFileErrorMessage = nil
|
||||
let outputURL = try self.createOutputURL(displayName: displayName)
|
||||
self.latestOutputPath = outputURL.lastPathComponent
|
||||
self.latestOutputPath = outputURL.path
|
||||
self.recordingStartedAt = Date()
|
||||
self.updateStatus(RecordingStatus(state: .recording, outputPath: outputURL.path))
|
||||
self.movieOutput.startRecording(to: outputURL, recordingDelegate: self)
|
||||
@@ -254,11 +254,11 @@ private final class RecordingCameraController: NSObject, AVCaptureFileOutputReco
|
||||
var payload: [String: Any] = [
|
||||
"outputPath": self.latestOutputPath as Any,
|
||||
"status": self.currentStatusMap(),
|
||||
"gallerySaved": self.latestGallerySaved,
|
||||
"fileSaved": self.latestFileSaved,
|
||||
]
|
||||
if !self.latestGallerySaved {
|
||||
payload["galleryErrorMessage"] =
|
||||
self.latestGalleryErrorMessage ?? "保存到相册失败"
|
||||
if !self.latestFileSaved {
|
||||
payload["fileErrorMessage"] =
|
||||
self.latestFileErrorMessage ?? "保存到文件夹失败"
|
||||
}
|
||||
result(payload)
|
||||
}
|
||||
@@ -291,6 +291,7 @@ private final class RecordingCameraController: NSObject, AVCaptureFileOutputReco
|
||||
self.session.commitConfiguration()
|
||||
self.videoInput = nil
|
||||
self.audioInput = nil
|
||||
self.currentZoomRatio = 1.0
|
||||
self.configured = false
|
||||
self.updateStatus(RecordingStatus(state: .idle))
|
||||
|
||||
@@ -312,6 +313,54 @@ private final class RecordingCameraController: NSObject, AVCaptureFileOutputReco
|
||||
return status.toMap()
|
||||
}
|
||||
|
||||
func zoomCapabilities(result: @escaping FlutterResult) {
|
||||
sessionQueue.async { [weak self] in
|
||||
guard let self else { return }
|
||||
let capabilities = self.currentZoomCapabilitiesMap()
|
||||
DispatchQueue.main.async {
|
||||
result(capabilities)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func setZoomRatio(_ ratio: CGFloat, result: @escaping FlutterResult) {
|
||||
sessionQueue.async { [weak self] in
|
||||
guard let self else { return }
|
||||
guard let device = self.videoInput?.device else {
|
||||
self.currentZoomRatio = max(1.0, ratio)
|
||||
let capabilities = self.currentZoomCapabilitiesMap()
|
||||
DispatchQueue.main.async {
|
||||
result(capabilities)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
// 入参是显示倍率(1.0x = 主摄),按 S 基准换算回设备 zoomFactor。
|
||||
let baseline = self.mainBaselineFactor(for: device)
|
||||
let nextZoom = self.clampedZoomRatio(ratio * baseline, for: device)
|
||||
try device.lockForConfiguration()
|
||||
device.videoZoomFactor = nextZoom
|
||||
device.unlockForConfiguration()
|
||||
self.currentZoomRatio = nextZoom
|
||||
let capabilities = self.currentZoomCapabilitiesMap()
|
||||
DispatchQueue.main.async {
|
||||
result(capabilities)
|
||||
}
|
||||
} catch {
|
||||
DispatchQueue.main.async {
|
||||
result(
|
||||
FlutterError(
|
||||
code: "ZOOM_FAILED",
|
||||
message: error.localizedDescription,
|
||||
details: nil
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func fileOutput(
|
||||
_ output: AVCaptureFileOutput,
|
||||
didFinishRecordingTo outputFileURL: URL,
|
||||
@@ -322,8 +371,8 @@ private final class RecordingCameraController: NSObject, AVCaptureFileOutputReco
|
||||
pendingStopResult = nil
|
||||
|
||||
if let error {
|
||||
latestGallerySaved = false
|
||||
latestGalleryErrorMessage = error.localizedDescription
|
||||
latestFileSaved = false
|
||||
latestFileErrorMessage = error.localizedDescription
|
||||
updateStatus(
|
||||
RecordingStatus(
|
||||
state: .error, outputPath: latestOutputPath, message: error.localizedDescription))
|
||||
@@ -331,29 +380,30 @@ private final class RecordingCameraController: NSObject, AVCaptureFileOutputReco
|
||||
return
|
||||
}
|
||||
|
||||
saveVideoToPhotoLibrary(fileURL: outputFileURL) { [weak self] success, message in
|
||||
guard let self else { return }
|
||||
self.latestGallerySaved = success
|
||||
self.latestGalleryErrorMessage = message
|
||||
if success {
|
||||
self.updateStatus(
|
||||
RecordingStatus(
|
||||
state: .previewing,
|
||||
outputPath: self.latestOutputPath,
|
||||
elapsedMillis: self.elapsedMillis()
|
||||
)
|
||||
latestFileSaved = true
|
||||
latestFileErrorMessage = nil
|
||||
latestOutputPath = outputFileURL.path
|
||||
guard FileManager.default.fileExists(atPath: outputFileURL.path) else {
|
||||
latestFileSaved = false
|
||||
latestFileErrorMessage = "录制文件未生成"
|
||||
updateStatus(
|
||||
RecordingStatus(
|
||||
state: .error,
|
||||
outputPath: latestOutputPath,
|
||||
message: latestFileErrorMessage
|
||||
)
|
||||
} else {
|
||||
self.updateStatus(
|
||||
RecordingStatus(
|
||||
state: .error,
|
||||
outputPath: self.latestOutputPath,
|
||||
message: message ?? "保存到相册失败"
|
||||
)
|
||||
)
|
||||
}
|
||||
self.finishStopRecording(stopResult: stopResult)
|
||||
)
|
||||
finishStopRecording(stopResult: stopResult)
|
||||
return
|
||||
}
|
||||
updateStatus(
|
||||
RecordingStatus(
|
||||
state: .previewing,
|
||||
outputPath: latestOutputPath,
|
||||
elapsedMillis: elapsedMillis()
|
||||
)
|
||||
)
|
||||
finishStopRecording(stopResult: stopResult)
|
||||
}
|
||||
|
||||
private func finishStopRecording(stopResult: FlutterResult?) {
|
||||
@@ -363,79 +413,23 @@ private final class RecordingCameraController: NSObject, AVCaptureFileOutputReco
|
||||
var payload: [String: Any] = [
|
||||
"outputPath": self.latestOutputPath as Any,
|
||||
"status": self.currentStatusMap(),
|
||||
"gallerySaved": self.latestGallerySaved,
|
||||
"fileSaved": self.latestFileSaved,
|
||||
]
|
||||
if !self.latestGallerySaved {
|
||||
payload["galleryErrorMessage"] =
|
||||
self.latestGalleryErrorMessage ?? "保存到相册失败,请开启相册权限"
|
||||
if !self.latestFileSaved {
|
||||
payload["fileErrorMessage"] =
|
||||
self.latestFileErrorMessage ?? "保存到文件夹失败,请检查文件保存权限"
|
||||
}
|
||||
stopResult?(payload)
|
||||
}
|
||||
}
|
||||
|
||||
private func saveVideoToPhotoLibrary(
|
||||
fileURL: URL,
|
||||
completion: @escaping (Bool, String?) -> Void
|
||||
) {
|
||||
let performSave = {
|
||||
PHPhotoLibrary.shared().performChanges({
|
||||
PHAssetCreationRequest.forAsset().addResource(with: .video, fileURL: fileURL, options: nil)
|
||||
}) { success, error in
|
||||
if success {
|
||||
try? FileManager.default.removeItem(at: fileURL)
|
||||
completion(true, nil)
|
||||
} else {
|
||||
completion(false, error?.localizedDescription ?? "保存到相册失败")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if #available(iOS 14, *) {
|
||||
let status = PHPhotoLibrary.authorizationStatus(for: .addOnly)
|
||||
switch status {
|
||||
case .authorized, .limited:
|
||||
performSave()
|
||||
case .notDetermined:
|
||||
PHPhotoLibrary.requestAuthorization(for: .addOnly) { newStatus in
|
||||
if newStatus == .authorized || newStatus == .limited {
|
||||
performSave()
|
||||
} else {
|
||||
completion(false, "未授予相册权限")
|
||||
}
|
||||
}
|
||||
default:
|
||||
completion(false, "未授予相册权限")
|
||||
}
|
||||
} else {
|
||||
let status = PHPhotoLibrary.authorizationStatus()
|
||||
switch status {
|
||||
case .authorized:
|
||||
performSave()
|
||||
case .notDetermined:
|
||||
PHPhotoLibrary.requestAuthorization { newStatus in
|
||||
if newStatus == .authorized {
|
||||
performSave()
|
||||
} else {
|
||||
completion(false, "未授予相册权限")
|
||||
}
|
||||
}
|
||||
default:
|
||||
completion(false, "未授予相册权限")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func configureSession(withAudio: Bool) throws {
|
||||
if configured {
|
||||
try configureAudioInput(enabled: withAudio)
|
||||
return
|
||||
}
|
||||
|
||||
guard
|
||||
let videoDevice = AVCaptureDevice.default(
|
||||
.builtInWideAngleCamera, for: .video, position: .back)
|
||||
?? AVCaptureDevice.default(for: .video)
|
||||
else {
|
||||
guard let videoDevice = Self.preferredVideoDevice() else {
|
||||
throw NSError(
|
||||
domain: "RecordingCamera", code: 1,
|
||||
userInfo: [NSLocalizedDescriptionKey: "No camera device available"])
|
||||
@@ -465,9 +459,74 @@ private final class RecordingCameraController: NSObject, AVCaptureFileOutputReco
|
||||
session.commitConfiguration()
|
||||
|
||||
configured = true
|
||||
// 默认以主摄(显示 1.0x)开场:虚拟多摄设备里主摄对应的 zoomFactor 是 S。
|
||||
currentZoomRatio = mainBaselineFactor(for: videoDevice)
|
||||
try applyCurrentZoom()
|
||||
try configureAudioInput(enabled: withAudio)
|
||||
}
|
||||
|
||||
/// 优先选用包含超广角的虚拟多摄设备,使 minAvailableVideoZoomFactor 能低于主摄(从而支持 0.6x)。
|
||||
private static func preferredVideoDevice() -> AVCaptureDevice? {
|
||||
let preferredTypes: [AVCaptureDevice.DeviceType] = [
|
||||
.builtInTripleCamera,
|
||||
.builtInDualWideCamera,
|
||||
.builtInWideAngleCamera,
|
||||
]
|
||||
for type in preferredTypes {
|
||||
if let device = AVCaptureDevice.default(type, for: .video, position: .back) {
|
||||
return device
|
||||
}
|
||||
}
|
||||
return AVCaptureDevice.default(for: .video)
|
||||
}
|
||||
|
||||
/// 虚拟多摄设备中「主摄(显示 1.0x)」对应的设备 zoomFactor 基准 S。
|
||||
/// 取 ultra-wide → wide 的切换点;非虚拟设备无切换点时返回 1.0(向后兼容)。
|
||||
private func mainBaselineFactor(for device: AVCaptureDevice) -> CGFloat {
|
||||
if let first = device.virtualDeviceSwitchOverVideoZoomFactors.first {
|
||||
let value = CGFloat(truncating: first)
|
||||
if value > 0 {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return 1.0
|
||||
}
|
||||
|
||||
private func currentZoomCapabilitiesMap() -> [String: Any] {
|
||||
guard let device = videoInput?.device else {
|
||||
return [
|
||||
"zoomRatio": Double(currentZoomRatio),
|
||||
"minZoomRatio": 1.0,
|
||||
"maxZoomRatio": 3.0,
|
||||
]
|
||||
}
|
||||
|
||||
// 设备 zoomFactor 以 S 为基准换算成 App 使用的「显示倍率」(1.0x = 主摄)。
|
||||
let baseline = mainBaselineFactor(for: device)
|
||||
let minZoom = device.minAvailableVideoZoomFactor
|
||||
let maxZoom = device.maxAvailableVideoZoomFactor
|
||||
let zoom = clampedZoomRatio(device.videoZoomFactor, for: device)
|
||||
currentZoomRatio = zoom
|
||||
return [
|
||||
"zoomRatio": Double(zoom / baseline),
|
||||
"minZoomRatio": Double(minZoom / baseline),
|
||||
"maxZoomRatio": Double(maxZoom / baseline),
|
||||
]
|
||||
}
|
||||
|
||||
private func applyCurrentZoom() throws {
|
||||
guard let device = videoInput?.device else { return }
|
||||
let nextZoom = clampedZoomRatio(currentZoomRatio, for: device)
|
||||
try device.lockForConfiguration()
|
||||
device.videoZoomFactor = nextZoom
|
||||
device.unlockForConfiguration()
|
||||
currentZoomRatio = nextZoom
|
||||
}
|
||||
|
||||
private func clampedZoomRatio(_ ratio: CGFloat, for device: AVCaptureDevice) -> CGFloat {
|
||||
min(max(ratio, device.minAvailableVideoZoomFactor), device.maxAvailableVideoZoomFactor)
|
||||
}
|
||||
|
||||
private func configureAudioInput(enabled: Bool) throws {
|
||||
session.beginConfiguration()
|
||||
defer { session.commitConfiguration() }
|
||||
@@ -502,7 +561,30 @@ private final class RecordingCameraController: NSObject, AVCaptureFileOutputReco
|
||||
try FileManager.default.createDirectory(at: recordingsURL, withIntermediateDirectories: true)
|
||||
|
||||
let fileName = Self.resolveFileName(displayName: displayName)
|
||||
return recordingsURL.appendingPathComponent(fileName)
|
||||
return uniqueOutputURL(in: recordingsURL, preferredFileName: fileName)
|
||||
}
|
||||
|
||||
private func uniqueOutputURL(in directoryURL: URL, preferredFileName: String) -> URL {
|
||||
let preferredURL = directoryURL.appendingPathComponent(preferredFileName)
|
||||
guard !FileManager.default.fileExists(atPath: preferredURL.path) else {
|
||||
let fileExtension = preferredURL.pathExtension
|
||||
let baseName = preferredURL.deletingPathExtension().lastPathComponent
|
||||
let timestamp = Self.fileNameDateFormatter.string(from: Date())
|
||||
|
||||
var index = 0
|
||||
while true {
|
||||
let suffix = index == 0 ? timestamp : "\(timestamp)_\(index)"
|
||||
let nextName = fileExtension.isEmpty
|
||||
? "\(baseName)_\(suffix)"
|
||||
: "\(baseName)_\(suffix).\(fileExtension)"
|
||||
let nextURL = directoryURL.appendingPathComponent(nextName)
|
||||
if !FileManager.default.fileExists(atPath: nextURL.path) {
|
||||
return nextURL
|
||||
}
|
||||
index += 1
|
||||
}
|
||||
}
|
||||
return preferredURL
|
||||
}
|
||||
|
||||
private static func resolveFileName(displayName: String?) -> String {
|
||||
@@ -520,6 +602,13 @@ private final class RecordingCameraController: NSObject, AVCaptureFileOutputReco
|
||||
return "REC_\(formatter.string(from: Date())).mov"
|
||||
}
|
||||
|
||||
private static let fileNameDateFormatter: DateFormatter = {
|
||||
let formatter = DateFormatter()
|
||||
formatter.locale = Locale(identifier: "en_US_POSIX")
|
||||
formatter.dateFormat = "yyyyMMdd_HHmmss"
|
||||
return formatter
|
||||
}()
|
||||
|
||||
private func updateStatus(_ next: RecordingStatus) {
|
||||
status = next
|
||||
}
|
||||
@@ -544,9 +633,9 @@ private final class RecordingCameraController: NSObject, AVCaptureFileOutputReco
|
||||
}
|
||||
|
||||
private enum RecordingChannelNames {
|
||||
static let packageName = "com.qxy.dronex"
|
||||
static let method = "\(packageName)/recording"
|
||||
static let events = "\(packageName)/recording_events"
|
||||
static let namespace = "app.record_tool"
|
||||
static let method = "\(namespace)/recording"
|
||||
static let events = "\(namespace)/recording_events"
|
||||
}
|
||||
|
||||
final class RecordingPlugin: NSObject, FlutterPlugin, FlutterStreamHandler {
|
||||
@@ -587,6 +676,12 @@ final class RecordingPlugin: NSObject, FlutterPlugin, FlutterStreamHandler {
|
||||
controller.startRecording(withAudio: withAudio, displayName: displayName, result: result)
|
||||
case "stopRecording":
|
||||
controller.stopRecording(result: result)
|
||||
case "getZoomCapabilities":
|
||||
controller.zoomCapabilities(result: result)
|
||||
case "setZoomRatio":
|
||||
let args = call.arguments as? [String: Any]
|
||||
let ratio = args?["zoomRatio"] as? Double ?? 1.0
|
||||
controller.setZoomRatio(CGFloat(ratio), result: result)
|
||||
case "disposePreview":
|
||||
controller.disposePreview(result: result)
|
||||
case "getStatus":
|
||||
|
||||
+2
-2
@@ -7,7 +7,7 @@ import 'package:pull_to_refresh/pull_to_refresh.dart';
|
||||
import 'package:recording_tool/app/config/app_config.dart';
|
||||
import 'package:recording_tool/app/router/app_navigator.dart';
|
||||
import 'package:recording_tool/app/theme/app_theme.dart';
|
||||
import 'package:recording_tool/features/recording/pages/page_record.dart';
|
||||
import 'package:recording_tool/features/auth/pages/page_auth.dart';
|
||||
import 'package:recording_tool/features/recording/view-model/view_model_recording.dart';
|
||||
|
||||
class FlutterTemplateApp extends ConsumerStatefulWidget {
|
||||
@@ -74,7 +74,7 @@ class _FlutterTemplateAppState extends ConsumerState<FlutterTemplateApp>
|
||||
home: RefreshConfiguration(
|
||||
enableLoadingWhenNoData: false,
|
||||
headerTriggerDistance: 80.h,
|
||||
child: const RecordingPage(),
|
||||
child: const AuthPageWidget(),
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
@@ -37,12 +37,12 @@ class AppConfig {
|
||||
),
|
||||
AppEnvironment.staging => const EnvironmentValues(
|
||||
environment: AppEnvironment.staging,
|
||||
baseUrl: 'https://staging.example.com/api',
|
||||
baseUrl: 'https://example.com/api',
|
||||
enableNetworkLog: true,
|
||||
),
|
||||
AppEnvironment.prod => const EnvironmentValues(
|
||||
environment: AppEnvironment.prod,
|
||||
baseUrl: 'https://api.example.com',
|
||||
baseUrl: 'https://example.com/api',
|
||||
enableNetworkLog: false,
|
||||
),
|
||||
};
|
||||
|
||||
@@ -60,7 +60,7 @@ class AppPlatformInfo {
|
||||
AppPlatformInfo._();
|
||||
|
||||
static const MethodChannel _channel = MethodChannel(
|
||||
'com.qxy.dronex/platform_info',
|
||||
'app.record_tool/platform_info',
|
||||
);
|
||||
|
||||
static Future<AppPackageInfo> packageInfo() async {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_screenutil/flutter_screenutil.dart';
|
||||
import 'package:recording_tool/app/router/app_navigator.dart';
|
||||
import 'package:recording_tool/features/scan_qrcode/pages/page_scan_qrcode.dart';
|
||||
import 'package:recording_tool/shared/widgets/widgets.dart';
|
||||
|
||||
class AuthPageWidget extends StatefulWidget {
|
||||
const AuthPageWidget({super.key});
|
||||
|
||||
@override
|
||||
State<AuthPageWidget> createState() => _AuthPageWidgetState();
|
||||
}
|
||||
|
||||
class _AuthPageWidgetState extends State<AuthPageWidget> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Center(
|
||||
child: Column(
|
||||
children: [
|
||||
SizedBox(height: 180.h),
|
||||
Text('裁判工作台', style: TextStyle(fontSize: 50, color: Colors.black)),
|
||||
SizedBox(height: 20.h),
|
||||
Text(
|
||||
'Auth Page',
|
||||
style: TextStyle(fontSize: 30, color: Colors.black),
|
||||
),
|
||||
SizedBox(height: 20.h),
|
||||
|
||||
SizedBox(
|
||||
width: 280.w,
|
||||
height: 80.h,
|
||||
child: AppTextField(initialValue: 'hhh'),
|
||||
),
|
||||
SizedBox(height: 20.h),
|
||||
SizedBox(
|
||||
width: 280.w,
|
||||
height: 80.h,
|
||||
child: AppButton(
|
||||
label: '确定',
|
||||
onPressed: () {
|
||||
AppNavigator.push(const ScanQrCodePage());
|
||||
},
|
||||
variant: AppButtonVariant.secondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -7,30 +7,40 @@ class RecordingSessionState {
|
||||
this.isTouchLocked = true,
|
||||
this.isPreviewReady = false,
|
||||
this.isStartingRecording = false,
|
||||
this.isSwitchingLens = false,
|
||||
this.hasDndAccess = false,
|
||||
this.isBatteryOptimizedIgnored = true,
|
||||
this.notificationsGranted = true,
|
||||
this.isMicrophoneGranted = false,
|
||||
this.zoomRatio = 1.0,
|
||||
this.minZoomRatio = 1.0,
|
||||
this.maxZoomRatio = 3.0,
|
||||
this.lastOutputPath,
|
||||
this.lastSavedDisplayName,
|
||||
this.errorMessage,
|
||||
this.permissionWarning,
|
||||
this.gallerySaveFailed = false,
|
||||
this.fileSaveFailed = false,
|
||||
this.segmentOutputPaths = const [],
|
||||
});
|
||||
|
||||
final RecordingStatus status;
|
||||
final bool isTouchLocked;
|
||||
final bool isPreviewReady;
|
||||
final bool isStartingRecording;
|
||||
final bool isSwitchingLens;
|
||||
final bool hasDndAccess;
|
||||
final bool isBatteryOptimizedIgnored;
|
||||
final bool notificationsGranted;
|
||||
final bool isMicrophoneGranted;
|
||||
final double zoomRatio;
|
||||
final double minZoomRatio;
|
||||
final double maxZoomRatio;
|
||||
final String? lastOutputPath;
|
||||
final String? lastSavedDisplayName;
|
||||
final String? errorMessage;
|
||||
final String? permissionWarning;
|
||||
final bool gallerySaveFailed;
|
||||
final bool fileSaveFailed;
|
||||
final List<String> segmentOutputPaths;
|
||||
|
||||
bool get isRecording => status.isRecording;
|
||||
|
||||
@@ -47,15 +57,20 @@ class RecordingSessionState {
|
||||
bool? isTouchLocked,
|
||||
bool? isPreviewReady,
|
||||
bool? isStartingRecording,
|
||||
bool? isSwitchingLens,
|
||||
bool? hasDndAccess,
|
||||
bool? isBatteryOptimizedIgnored,
|
||||
bool? notificationsGranted,
|
||||
bool? isMicrophoneGranted,
|
||||
double? zoomRatio,
|
||||
double? minZoomRatio,
|
||||
double? maxZoomRatio,
|
||||
String? lastOutputPath,
|
||||
String? lastSavedDisplayName,
|
||||
String? errorMessage,
|
||||
String? permissionWarning,
|
||||
bool? gallerySaveFailed,
|
||||
bool? fileSaveFailed,
|
||||
List<String>? segmentOutputPaths,
|
||||
bool clearPermissionWarning = false,
|
||||
bool clearLastSaved = false,
|
||||
}) {
|
||||
@@ -64,11 +79,15 @@ class RecordingSessionState {
|
||||
isTouchLocked: isTouchLocked ?? this.isTouchLocked,
|
||||
isPreviewReady: isPreviewReady ?? this.isPreviewReady,
|
||||
isStartingRecording: isStartingRecording ?? this.isStartingRecording,
|
||||
isSwitchingLens: isSwitchingLens ?? this.isSwitchingLens,
|
||||
hasDndAccess: hasDndAccess ?? this.hasDndAccess,
|
||||
isBatteryOptimizedIgnored:
|
||||
isBatteryOptimizedIgnored ?? this.isBatteryOptimizedIgnored,
|
||||
notificationsGranted: notificationsGranted ?? this.notificationsGranted,
|
||||
isMicrophoneGranted: isMicrophoneGranted ?? this.isMicrophoneGranted,
|
||||
zoomRatio: zoomRatio ?? this.zoomRatio,
|
||||
minZoomRatio: minZoomRatio ?? this.minZoomRatio,
|
||||
maxZoomRatio: maxZoomRatio ?? this.maxZoomRatio,
|
||||
lastOutputPath: lastOutputPath ?? this.lastOutputPath,
|
||||
lastSavedDisplayName: clearLastSaved
|
||||
? null
|
||||
@@ -77,7 +96,8 @@ class RecordingSessionState {
|
||||
permissionWarning: clearPermissionWarning
|
||||
? null
|
||||
: (permissionWarning ?? this.permissionWarning),
|
||||
gallerySaveFailed: gallerySaveFailed ?? this.gallerySaveFailed,
|
||||
fileSaveFailed: fileSaveFailed ?? this.fileSaveFailed,
|
||||
segmentOutputPaths: segmentOutputPaths ?? this.segmentOutputPaths,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,8 +172,12 @@ class _RecordingPageState extends ConsumerState<RecordingPage> {
|
||||
await ref.read(recordingViewModelProvider.notifier).stopRecording();
|
||||
if (!mounted) return;
|
||||
final latest = ref.read(recordingViewModelProvider).session;
|
||||
if (latest.gallerySaveFailed) {
|
||||
AppToast.show(latest.errorMessage ?? '保存到相册失败,请开启相册权限');
|
||||
if (latest.fileSaveFailed) {
|
||||
if (latest.segmentOutputPaths.isNotEmpty) {
|
||||
AppToast.show('视频合并失败,已为你保存分段文件,可在相册中查看');
|
||||
} else {
|
||||
AppToast.show(latest.errorMessage ?? '保存到文件夹失败,请检查文件保存权限');
|
||||
}
|
||||
return;
|
||||
}
|
||||
await _showRecordingSavedDialogIfNeeded();
|
||||
@@ -190,7 +194,7 @@ class _RecordingPageState extends ConsumerState<RecordingPage> {
|
||||
Future<void> _showRecordingSavedDialogIfNeeded() async {
|
||||
final recordingInfo = ref.read(recordingViewModelProvider);
|
||||
final session = recordingInfo.session;
|
||||
if (session.lastSavedDisplayName == null || session.gallerySaveFailed) {
|
||||
if (session.lastSavedDisplayName == null || session.fileSaveFailed) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -357,10 +361,7 @@ class _PreviewLoadingLayer extends ConsumerWidget {
|
||||
}
|
||||
|
||||
class _RecordingHudLayer extends ConsumerWidget {
|
||||
const _RecordingHudLayer({
|
||||
required this.onStart,
|
||||
required this.onStop,
|
||||
});
|
||||
const _RecordingHudLayer({required this.onStart, required this.onStop});
|
||||
|
||||
final Future<void> Function() onStart;
|
||||
final Future<void> Function() onStop;
|
||||
@@ -377,7 +378,11 @@ class _RecordingHudLayer extends ConsumerWidget {
|
||||
m.session.notificationsGranted,
|
||||
m.session.isRecording,
|
||||
m.session.isStartingRecording,
|
||||
m.session.isSwitchingLens,
|
||||
m.session.isTouchLocked,
|
||||
m.session.zoomRatio,
|
||||
m.session.minZoomRatio,
|
||||
m.session.maxZoomRatio,
|
||||
m.hasValidClipboardInfo,
|
||||
m.clipboardRecordingModel.address.trim(),
|
||||
),
|
||||
@@ -391,7 +396,11 @@ class _RecordingHudLayer extends ConsumerWidget {
|
||||
notificationsGranted,
|
||||
isRecording,
|
||||
isStartingRecording,
|
||||
isSwitchingLens,
|
||||
isTouchLocked,
|
||||
zoomRatio,
|
||||
minZoomRatio,
|
||||
maxZoomRatio,
|
||||
showClipboardHint,
|
||||
clipboardAddress,
|
||||
) = hudState;
|
||||
@@ -405,7 +414,11 @@ class _RecordingHudLayer extends ConsumerWidget {
|
||||
notificationsGranted: notificationsGranted,
|
||||
isRecording: isRecording,
|
||||
isStartingRecording: isStartingRecording,
|
||||
isSwitchingLens: isSwitchingLens,
|
||||
isTouchLocked: isTouchLocked,
|
||||
zoomRatio: zoomRatio,
|
||||
minZoomRatio: minZoomRatio,
|
||||
maxZoomRatio: maxZoomRatio,
|
||||
showClipboardHint: showClipboardHint,
|
||||
clipboardAddress: clipboardAddress,
|
||||
onStart: onStart,
|
||||
@@ -419,9 +432,15 @@ class _RecordingHudLayer extends ConsumerWidget {
|
||||
await viewModel.refreshBatteryOptimization();
|
||||
},
|
||||
onToggleTouchLock: () {
|
||||
final locked = ref.read(recordingViewModelProvider).session.isTouchLocked;
|
||||
final locked = ref
|
||||
.read(recordingViewModelProvider)
|
||||
.session
|
||||
.isTouchLocked;
|
||||
viewModel.setTouchLocked(!locked);
|
||||
},
|
||||
onZoomSelected: (ratio) async {
|
||||
await viewModel.setZoomRatio(ratio);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
abstract final class RecordingChannelNames {
|
||||
static const packageName = 'com.qxy.dronex';
|
||||
static const method = '$packageName/recording';
|
||||
static const events = '$packageName/recording_events';
|
||||
static const namespace = 'app.record_tool';
|
||||
static const method = '$namespace/recording';
|
||||
static const events = '$namespace/recording_events';
|
||||
}
|
||||
|
||||
@@ -81,6 +81,21 @@ class RecordingPlatform {
|
||||
return RecordingStatus.fromMap(result ?? const {});
|
||||
}
|
||||
|
||||
static Future<RecordingZoomCapabilities> getZoomCapabilities() async {
|
||||
final result = await _channel.invokeMapMethod<String, dynamic>(
|
||||
'getZoomCapabilities',
|
||||
);
|
||||
return RecordingZoomCapabilities.fromMap(result);
|
||||
}
|
||||
|
||||
static Future<RecordingZoomCapabilities> setZoomRatio(double ratio) async {
|
||||
final result = await _channel.invokeMapMethod<String, dynamic>(
|
||||
'setZoomRatio',
|
||||
<String, dynamic>{'zoomRatio': ratio},
|
||||
);
|
||||
return RecordingZoomCapabilities.fromMap(result);
|
||||
}
|
||||
|
||||
static Future<RecordingStartResult> startRecording({
|
||||
bool withAudio = true,
|
||||
bool enableDoNotDisturb = true,
|
||||
@@ -156,6 +171,29 @@ class RecordingPlatform {
|
||||
}
|
||||
}
|
||||
|
||||
class RecordingZoomCapabilities {
|
||||
const RecordingZoomCapabilities({
|
||||
required this.zoomRatio,
|
||||
required this.minZoomRatio,
|
||||
required this.maxZoomRatio,
|
||||
});
|
||||
|
||||
final double zoomRatio;
|
||||
final double minZoomRatio;
|
||||
final double maxZoomRatio;
|
||||
|
||||
factory RecordingZoomCapabilities.fromMap(Map<String, dynamic>? map) {
|
||||
final minZoomRatio = (map?['minZoomRatio'] as num?)?.toDouble() ?? 1.0;
|
||||
final maxZoomRatio = (map?['maxZoomRatio'] as num?)?.toDouble() ?? 3.0;
|
||||
final zoomRatio = (map?['zoomRatio'] as num?)?.toDouble() ?? minZoomRatio;
|
||||
return RecordingZoomCapabilities(
|
||||
zoomRatio: zoomRatio.clamp(minZoomRatio, maxZoomRatio).toDouble(),
|
||||
minZoomRatio: minZoomRatio,
|
||||
maxZoomRatio: maxZoomRatio,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class RecordingStartResult {
|
||||
const RecordingStartResult({this.outputPath, required this.status});
|
||||
|
||||
@@ -167,14 +205,16 @@ class RecordingStopResult {
|
||||
const RecordingStopResult({
|
||||
this.outputPath,
|
||||
required this.status,
|
||||
this.gallerySaved = true,
|
||||
this.galleryErrorMessage,
|
||||
this.fileSaved = true,
|
||||
this.fileErrorMessage,
|
||||
this.segmentOutputPaths = const [],
|
||||
});
|
||||
|
||||
final String? outputPath;
|
||||
final RecordingStatus status;
|
||||
final bool gallerySaved;
|
||||
final String? galleryErrorMessage;
|
||||
final bool fileSaved;
|
||||
final String? fileErrorMessage;
|
||||
final List<String> segmentOutputPaths;
|
||||
|
||||
factory RecordingStopResult.fromMap(Map<String, dynamic>? result) {
|
||||
return RecordingStopResult(
|
||||
@@ -182,8 +222,13 @@ class RecordingStopResult {
|
||||
status: RecordingStatus.fromMap(
|
||||
Map<dynamic, dynamic>.from(result?['status'] as Map? ?? const {}),
|
||||
),
|
||||
gallerySaved: result?['gallerySaved'] as bool? ?? true,
|
||||
galleryErrorMessage: result?['galleryErrorMessage'] as String?,
|
||||
fileSaved: result?['fileSaved'] as bool? ?? true,
|
||||
fileErrorMessage: result?['fileErrorMessage'] as String?,
|
||||
segmentOutputPaths:
|
||||
(result?['segmentOutputPaths'] as List?)?.whereType<String>().toList(
|
||||
growable: false,
|
||||
) ??
|
||||
const [],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:permission_handler/permission_handler.dart';
|
||||
import 'package:recording_tool/core/logging/app_logger.dart';
|
||||
import 'package:recording_tool/core/permission/permission_service.dart';
|
||||
import 'package:recording_tool/core/platform/app_platform_info.dart';
|
||||
import 'package:recording_tool/features/recording/model/model_clipboard.dart';
|
||||
import 'package:recording_tool/features/recording/model/model_recording.dart';
|
||||
import 'package:recording_tool/features/recording/model/model_recording_session.dart';
|
||||
@@ -31,15 +32,19 @@ enum ClipboardReadResult {
|
||||
invalid,
|
||||
}
|
||||
|
||||
List<Permission> recordingGalleryPermissionsForHost({
|
||||
List<Permission> recordingFileSavePermissionsForHost({
|
||||
required bool isIOS,
|
||||
required bool isAndroid,
|
||||
int? androidSdkInt,
|
||||
}) {
|
||||
if (isIOS) {
|
||||
return [Permission.photosAddOnly];
|
||||
return const [];
|
||||
}
|
||||
if (isAndroid) {
|
||||
return [Permission.videos, Permission.storage];
|
||||
if (androidSdkInt != null && androidSdkInt <= 28) {
|
||||
return [Permission.storage];
|
||||
}
|
||||
return const [];
|
||||
}
|
||||
return const [];
|
||||
}
|
||||
@@ -144,11 +149,12 @@ class RecordingViewModel extends Notifier<RecordingModel> {
|
||||
return;
|
||||
}
|
||||
|
||||
final fileSavePermissions = await _fileSavePermissions();
|
||||
final permissions = await PermissionService.requestMissing([
|
||||
Permission.camera,
|
||||
Permission.microphone,
|
||||
if (Platform.isAndroid) Permission.notification,
|
||||
..._galleryPermissions(),
|
||||
...fileSavePermissions,
|
||||
]);
|
||||
|
||||
final cameraGranted = permissions[Permission.camera]?.isGranted ?? false;
|
||||
@@ -170,8 +176,8 @@ class RecordingViewModel extends Notifier<RecordingModel> {
|
||||
if (!microphoneGranted) {
|
||||
warnings.add('未授予麦克风权限,当前将以静音模式录制');
|
||||
}
|
||||
if (!_isGalleryPermissionGranted(permissions)) {
|
||||
warnings.add('未授予相册权限,录制结束后可能无法保存到相册');
|
||||
if (!_isFileSavePermissionGranted(permissions, fileSavePermissions)) {
|
||||
warnings.add('未授予文件保存权限,录制结束后可能无法保存到文件夹');
|
||||
}
|
||||
|
||||
final hasDnd = await RecordingPlatform.hasNotificationPolicyAccess();
|
||||
@@ -193,6 +199,7 @@ class RecordingViewModel extends Notifier<RecordingModel> {
|
||||
await _listenStatus();
|
||||
try {
|
||||
final status = await _initializePreviewWithRetry();
|
||||
await _refreshZoomCapabilities();
|
||||
_updateSession(
|
||||
(s) => s.copyWith(
|
||||
status: status,
|
||||
@@ -239,6 +246,7 @@ class RecordingViewModel extends Notifier<RecordingModel> {
|
||||
);
|
||||
try {
|
||||
final status = await _initializePreviewWithRetry();
|
||||
await _refreshZoomCapabilities();
|
||||
_updateSession(
|
||||
(s) => s.copyWith(
|
||||
status: status,
|
||||
@@ -258,24 +266,36 @@ class RecordingViewModel extends Notifier<RecordingModel> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前平台所需的相册/视频保存权限列表。
|
||||
List<Permission> _galleryPermissions() {
|
||||
return recordingGalleryPermissionsForHost(
|
||||
/// 当前平台所需的视频文件保存权限列表。
|
||||
Future<List<Permission>> _fileSavePermissions() async {
|
||||
int? androidSdkInt;
|
||||
if (Platform.isAndroid) {
|
||||
try {
|
||||
androidSdkInt = int.tryParse(
|
||||
(await AppPlatformInfo.deviceInfo()).values['sdkInt'] ?? '',
|
||||
);
|
||||
} on PlatformException {
|
||||
androidSdkInt = null;
|
||||
}
|
||||
}
|
||||
return recordingFileSavePermissionsForHost(
|
||||
isIOS: Platform.isIOS,
|
||||
isAndroid: Platform.isAndroid,
|
||||
androidSdkInt: androidSdkInt,
|
||||
);
|
||||
}
|
||||
|
||||
/// 判断相册相关权限是否至少有一项已授予。
|
||||
bool _isGalleryPermissionGranted(
|
||||
/// 判断文件保存相关权限是否至少有一项已授予。
|
||||
bool _isFileSavePermissionGranted(
|
||||
Map<Permission, PermissionStatus> permissions,
|
||||
List<Permission> fileSavePermissions,
|
||||
) {
|
||||
for (final permission in _galleryPermissions()) {
|
||||
for (final permission in fileSavePermissions) {
|
||||
if (permissions[permission]?.isGranted ?? false) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return _galleryPermissions().isEmpty;
|
||||
return fileSavePermissions.isEmpty;
|
||||
}
|
||||
|
||||
/// 检测并尝试申请相机、麦克风权限,同步更新 session 中的 isMicrophoneGranted。
|
||||
@@ -309,10 +329,62 @@ class RecordingViewModel extends Notifier<RecordingModel> {
|
||||
return status?.isGranted == true || status?.isLimited == true;
|
||||
}
|
||||
|
||||
/// 读取相机支持的倍距范围并同步当前倍距。
|
||||
Future<void> _refreshZoomCapabilities() async {
|
||||
try {
|
||||
final zoom = await RecordingPlatform.getZoomCapabilities();
|
||||
_updateSession(
|
||||
(s) => s.copyWith(
|
||||
zoomRatio: zoom.zoomRatio,
|
||||
minZoomRatio: zoom.minZoomRatio,
|
||||
maxZoomRatio: zoom.maxZoomRatio,
|
||||
errorMessage: null,
|
||||
),
|
||||
);
|
||||
} on PlatformException catch (error) {
|
||||
AppLogger.debug('读取相机倍距能力失败', error: error);
|
||||
}
|
||||
}
|
||||
|
||||
/// 设置相机倍距,原生层会返回设备实际应用后的倍距范围与当前值。
|
||||
Future<void> setZoomRatio(double ratio) async {
|
||||
final session = state.session;
|
||||
if (session.isSwitchingLens) {
|
||||
return;
|
||||
}
|
||||
final clamped = ratio
|
||||
.clamp(session.minZoomRatio, session.maxZoomRatio)
|
||||
.toDouble();
|
||||
|
||||
_updateSession((s) => s.copyWith(isSwitchingLens: true));
|
||||
try {
|
||||
final zoom = await RecordingPlatform.setZoomRatio(clamped);
|
||||
_updateSession(
|
||||
(s) => s.copyWith(
|
||||
zoomRatio: zoom.zoomRatio,
|
||||
minZoomRatio: zoom.minZoomRatio,
|
||||
maxZoomRatio: zoom.maxZoomRatio,
|
||||
errorMessage: null,
|
||||
),
|
||||
);
|
||||
} on PlatformException catch (error) {
|
||||
final message = error.code == 'ZOOM_FAILED'
|
||||
? '切换镜头失败,请重试'
|
||||
: (error.message ?? '相机倍距设置失败');
|
||||
_updateSession((s) => s.copyWith(errorMessage: message));
|
||||
} finally {
|
||||
_updateSession(
|
||||
(s) => s.copyWith(isSwitchingLens: false, errorMessage: s.errorMessage),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 开始录制,可选开启勿扰模式。
|
||||
Future<void> startRecording({bool enableDoNotDisturb = true}) async {
|
||||
final session = state.session;
|
||||
if (session.isRecording || session.isStartingRecording) {
|
||||
if (session.isRecording ||
|
||||
session.isStartingRecording ||
|
||||
session.isSwitchingLens) {
|
||||
return;
|
||||
}
|
||||
if (!session.isPreviewReady) {
|
||||
@@ -338,7 +410,8 @@ class RecordingViewModel extends Notifier<RecordingModel> {
|
||||
lastOutputPath: result.outputPath,
|
||||
isTouchLocked: true,
|
||||
errorMessage: null,
|
||||
gallerySaveFailed: false,
|
||||
fileSaveFailed: false,
|
||||
segmentOutputPaths: const [],
|
||||
clearLastSaved: true,
|
||||
),
|
||||
);
|
||||
@@ -351,13 +424,13 @@ class RecordingViewModel extends Notifier<RecordingModel> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 停止录制、保存到相册,并恢复相机预览。
|
||||
/// 停止录制、保存到文件夹,并恢复相机预览。
|
||||
Future<void> stopRecording() async {
|
||||
if (!state.session.isRecording) return;
|
||||
if (!state.session.isRecording || state.session.isSwitchingLens) return;
|
||||
|
||||
try {
|
||||
final result = await RecordingPlatform.stopRecording();
|
||||
final galleryFailed = !result.gallerySaved;
|
||||
final fileFailed = !result.fileSaved;
|
||||
final savedName = recordingFileNameForPlatform(
|
||||
state.clipboardRecordingModel.filename,
|
||||
);
|
||||
@@ -365,11 +438,12 @@ class RecordingViewModel extends Notifier<RecordingModel> {
|
||||
(s) => s.copyWith(
|
||||
status: result.status,
|
||||
lastOutputPath: result.outputPath ?? s.lastOutputPath,
|
||||
lastSavedDisplayName: galleryFailed ? null : savedName,
|
||||
errorMessage: galleryFailed
|
||||
? (result.galleryErrorMessage ?? '保存到相册失败,请开启相册权限')
|
||||
lastSavedDisplayName: fileFailed ? null : savedName,
|
||||
errorMessage: fileFailed
|
||||
? (result.fileErrorMessage ?? '保存到文件夹失败,请检查文件保存权限')
|
||||
: null,
|
||||
gallerySaveFailed: galleryFailed,
|
||||
fileSaveFailed: fileFailed,
|
||||
segmentOutputPaths: result.segmentOutputPaths,
|
||||
),
|
||||
);
|
||||
} on PlatformException catch (error) {
|
||||
|
||||
@@ -18,14 +18,19 @@ class RecordingHudWidget extends StatelessWidget {
|
||||
required this.notificationsGranted,
|
||||
required this.isRecording,
|
||||
required this.isStartingRecording,
|
||||
required this.isSwitchingLens,
|
||||
required this.isTouchLocked,
|
||||
this.showClipboardHint = false,
|
||||
this.clipboardAddress = '',
|
||||
required this.zoomRatio,
|
||||
required this.minZoomRatio,
|
||||
required this.maxZoomRatio,
|
||||
required this.onStart,
|
||||
required this.onStop,
|
||||
required this.onOpenDnd,
|
||||
required this.onOpenBattery,
|
||||
required this.onToggleTouchLock,
|
||||
required this.onZoomSelected,
|
||||
});
|
||||
|
||||
final String? errorMessage;
|
||||
@@ -35,14 +40,19 @@ class RecordingHudWidget extends StatelessWidget {
|
||||
final bool notificationsGranted;
|
||||
final bool isRecording;
|
||||
final bool isStartingRecording;
|
||||
final bool isSwitchingLens;
|
||||
final bool isTouchLocked;
|
||||
final bool showClipboardHint;
|
||||
final String clipboardAddress;
|
||||
final double zoomRatio;
|
||||
final double minZoomRatio;
|
||||
final double maxZoomRatio;
|
||||
final Future<void> Function() onStart;
|
||||
final Future<void> Function() onStop;
|
||||
final VoidCallback onOpenDnd;
|
||||
final VoidCallback onOpenBattery;
|
||||
final VoidCallback onToggleTouchLock;
|
||||
final ValueChanged<double> onZoomSelected;
|
||||
|
||||
static double get _recordButtonSize => 70.r;
|
||||
static double get _recordButtonBottom => 63.r;
|
||||
@@ -133,6 +143,18 @@ class RecordingHudWidget extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
right: 16.r,
|
||||
bottom: 260.r,
|
||||
child: _ZoomPresetControl(
|
||||
enabled: !isSwitchingLens,
|
||||
zoomRatio: zoomRatio,
|
||||
minZoomRatio: minZoomRatio,
|
||||
maxZoomRatio: maxZoomRatio,
|
||||
presets: _zoomPresetsForRange(minZoomRatio),
|
||||
onSelected: onZoomSelected,
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
@@ -141,7 +163,7 @@ class RecordingHudWidget extends StatelessWidget {
|
||||
child: RecordingControlButton(
|
||||
isRecording: isRecording,
|
||||
isStartingRecording: isStartingRecording,
|
||||
enabled: !isStartingRecording,
|
||||
enabled: !isStartingRecording && !isSwitchingLens,
|
||||
size: _recordButtonSize,
|
||||
onTap: () {
|
||||
if (isRecording) {
|
||||
@@ -170,4 +192,140 @@ class RecordingHudWidget extends StatelessWidget {
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
List<double> _zoomPresetsForRange(double minZoomRatio) {
|
||||
return [if (minZoomRatio < 1.0) minZoomRatio, 1.0];
|
||||
}
|
||||
}
|
||||
|
||||
class _ZoomPresetControl extends StatelessWidget {
|
||||
const _ZoomPresetControl({
|
||||
required this.enabled,
|
||||
required this.zoomRatio,
|
||||
required this.minZoomRatio,
|
||||
required this.maxZoomRatio,
|
||||
required this.presets,
|
||||
required this.onSelected,
|
||||
});
|
||||
|
||||
final bool enabled;
|
||||
final double zoomRatio;
|
||||
final double minZoomRatio;
|
||||
final double maxZoomRatio;
|
||||
final List<double> presets;
|
||||
final ValueChanged<double> onSelected;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final availablePresets = presets
|
||||
.where(_isPresetAvailable)
|
||||
.toList(growable: false);
|
||||
if (availablePresets.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
return DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.46),
|
||||
borderRadius: BorderRadius.circular(18.r),
|
||||
border: Border.all(color: Colors.white.withValues(alpha: 0.18)),
|
||||
),
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(3.r),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
for (final preset in availablePresets)
|
||||
_ZoomPresetButton(
|
||||
displayRatio: preset,
|
||||
requestRatio: preset,
|
||||
selected: _isPresetSelected(preset),
|
||||
enabled: enabled,
|
||||
onSelected: onSelected,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
bool _isPresetAvailable(double preset) {
|
||||
if (preset < 1.0) {
|
||||
return minZoomRatio <= preset && maxZoomRatio >= preset;
|
||||
}
|
||||
return preset >= minZoomRatio && preset <= maxZoomRatio;
|
||||
}
|
||||
|
||||
bool _isPresetSelected(double preset) {
|
||||
if (preset < 1.0) {
|
||||
return zoomRatio < 1.0;
|
||||
}
|
||||
return (zoomRatio - preset).abs() < 0.05;
|
||||
}
|
||||
}
|
||||
|
||||
class _ZoomPresetButton extends StatelessWidget {
|
||||
const _ZoomPresetButton({
|
||||
required this.displayRatio,
|
||||
required this.requestRatio,
|
||||
required this.selected,
|
||||
required this.enabled,
|
||||
required this.onSelected,
|
||||
});
|
||||
|
||||
final double displayRatio;
|
||||
final double requestRatio;
|
||||
final bool selected;
|
||||
final bool enabled;
|
||||
final ValueChanged<double> onSelected;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 1.r),
|
||||
child: TextButton(
|
||||
onPressed: selected || !enabled
|
||||
? null
|
||||
: () => RateLimit.instance.debounce<void>(
|
||||
key:
|
||||
'recording.session.zoom.${requestRatio.toStringAsFixed(1)}',
|
||||
value: null,
|
||||
duration: Duration(milliseconds: 300),
|
||||
onCallback: (_) async {
|
||||
onSelected(requestRatio);
|
||||
},
|
||||
),
|
||||
style: TextButton.styleFrom(
|
||||
minimumSize: Size(38.r, 32.r),
|
||||
padding: EdgeInsets.zero,
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
foregroundColor: selected ? Colors.black : Colors.white,
|
||||
disabledForegroundColor: Colors.black,
|
||||
backgroundColor: selected ? Colors.white : Colors.transparent,
|
||||
disabledBackgroundColor: Colors.white,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(15.r),
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
_formatZoomRatio(displayRatio),
|
||||
style: TextStyle(
|
||||
fontSize: 13.sp,
|
||||
fontWeight: FontWeight.w700,
|
||||
letterSpacing: 0,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
String _formatZoomRatio(double ratio) {
|
||||
if (ratio < 1.0) {
|
||||
return '广角';
|
||||
}
|
||||
if (ratio == ratio.roundToDouble()) {
|
||||
return '${ratio.toStringAsFixed(0)}x';
|
||||
}
|
||||
return '${ratio.toStringAsFixed(1)}x';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:recording_tool/features/dialog/dialog-record.dart';
|
||||
|
||||
/// 录制结束并保存到相册后的后续操作弹窗。
|
||||
/// 录制结束并保存到文件夹后的后续操作弹窗。
|
||||
Future<void> showRecordingSavedDialog(
|
||||
BuildContext context, {
|
||||
required String sessionTitle,
|
||||
@@ -10,7 +10,7 @@ Future<void> showRecordingSavedDialog(
|
||||
}) {
|
||||
return RecordDialog.showDouble(
|
||||
context,
|
||||
title: '本轮比赛视频已保存到相册\n请选择后续录制信息',
|
||||
title: '本轮比赛视频已保存到文件夹\n请选择后续录制信息',
|
||||
leftText: '继续本轮',
|
||||
rightText: '录制新轮',
|
||||
onLeftPressed: onContinueRound,
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_screenutil/flutter_screenutil.dart';
|
||||
import 'package:recording_tool/app/router/app_navigator.dart';
|
||||
import 'package:recording_tool/shared/widgets/app_button.dart';
|
||||
import 'package:recording_tool/shared/widgets/app_qr_scanner_dialog.dart';
|
||||
import 'package:recording_tool/shared/widgets/app_webview.dart';
|
||||
|
||||
class ScanQrCodePage extends StatefulWidget {
|
||||
const ScanQrCodePage({super.key});
|
||||
|
||||
@override
|
||||
State<ScanQrCodePage> createState() => _AuthPageWidgetState();
|
||||
}
|
||||
|
||||
class _AuthPageWidgetState extends State<ScanQrCodePage> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
onPressed: () {
|
||||
Navigator.of(context).maybePop();
|
||||
},
|
||||
),
|
||||
centerTitle: true,
|
||||
elevation: 0,
|
||||
backgroundColor: Colors.transparent,
|
||||
foregroundColor: Colors.black,
|
||||
),
|
||||
body: Center(
|
||||
child: Column(
|
||||
children: [
|
||||
SizedBox(height: 100.h),
|
||||
Text('裁判工作台', style: TextStyle(fontSize: 30, color: Colors.black)),
|
||||
SizedBox(height: 100.h),
|
||||
Text(
|
||||
'扫描选手参赛凭证进行执裁',
|
||||
style: TextStyle(fontSize: 30, color: Colors.black),
|
||||
),
|
||||
SizedBox(height: 20.h),
|
||||
|
||||
SizedBox(
|
||||
width: 280.w,
|
||||
height: 80.h,
|
||||
child: AppButton(
|
||||
label: '扫码',
|
||||
onPressed: () async {
|
||||
final result = await AppQrScannerDialog.show(context);
|
||||
if (result == null || result.isEmpty) return;
|
||||
debugPrint('扫码结果: $result');
|
||||
AppNavigator.push(
|
||||
const WebviewPage(url: 'https://www.dronex.cc/'),
|
||||
);
|
||||
},
|
||||
variant: AppButtonVariant.secondary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_screenutil/flutter_screenutil.dart';
|
||||
import 'package:mobile_scanner/mobile_scanner.dart';
|
||||
|
||||
class AppQrScannerDialog extends StatefulWidget {
|
||||
const AppQrScannerDialog({super.key});
|
||||
|
||||
static Future<String?> show(BuildContext context) {
|
||||
return showGeneralDialog<String>(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
|
||||
barrierColor: Colors.black,
|
||||
transitionDuration: const Duration(milliseconds: 180),
|
||||
pageBuilder: (dialogContext, animation, secondaryAnimation) {
|
||||
return const AppQrScannerDialog();
|
||||
},
|
||||
transitionBuilder: (context, animation, secondaryAnimation, child) {
|
||||
return FadeTransition(opacity: animation, child: child);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
State<AppQrScannerDialog> createState() => _AppQrScannerDialogState();
|
||||
}
|
||||
|
||||
class _AppQrScannerDialogState extends State<AppQrScannerDialog>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late final MobileScannerController _controller;
|
||||
late final AnimationController _scanLineController;
|
||||
bool _hasScanned = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = MobileScannerController(
|
||||
detectionSpeed: DetectionSpeed.noDuplicates,
|
||||
facing: CameraFacing.back,
|
||||
formats: const [BarcodeFormat.qrCode],
|
||||
);
|
||||
_scanLineController = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 1800),
|
||||
)..repeat(reverse: true);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_scanLineController.dispose();
|
||||
unawaited(_controller.dispose());
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _handleDetect(BarcodeCapture capture) async {
|
||||
if (_hasScanned || capture.barcodes.isEmpty) return;
|
||||
|
||||
final value = capture.barcodes.first.rawValue;
|
||||
if (value == null || value.isEmpty) return;
|
||||
|
||||
_hasScanned = true;
|
||||
final navigator = Navigator.of(context, rootNavigator: true);
|
||||
try {
|
||||
await _controller.stop();
|
||||
} catch (error) {
|
||||
debugPrint('停止扫码相机失败: $error');
|
||||
}
|
||||
|
||||
if (!mounted) return;
|
||||
navigator.pop(value);
|
||||
}
|
||||
|
||||
void _close() {
|
||||
Navigator.of(context, rootNavigator: true).pop();
|
||||
}
|
||||
|
||||
Rect _scanWindowFor(Size size) {
|
||||
final scanSize = math.min(size.width * 0.72, 300.w);
|
||||
final center = Offset(size.width / 2, size.height * 0.46);
|
||||
return Rect.fromCenter(center: center, width: scanSize, height: scanSize);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Material(
|
||||
color: Colors.black,
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final size = constraints.biggest;
|
||||
final scanWindow = _scanWindowFor(size);
|
||||
|
||||
return Stack(
|
||||
children: [
|
||||
Positioned.fill(
|
||||
child: MobileScanner(
|
||||
controller: _controller,
|
||||
fit: BoxFit.cover,
|
||||
scanWindow: scanWindow,
|
||||
onDetect: _handleDetect,
|
||||
errorBuilder: _buildCameraError,
|
||||
placeholderBuilder: (_) => const ColoredBox(
|
||||
color: Colors.black,
|
||||
child: Center(
|
||||
child: CircularProgressIndicator(color: Colors.white),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Positioned.fill(
|
||||
child: CustomPaint(
|
||||
painter: _ScannerOverlayPainter(scanWindow: scanWindow),
|
||||
),
|
||||
),
|
||||
_ScanLine(animation: _scanLineController, scanWindow: scanWindow),
|
||||
Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
top: 0,
|
||||
child: SafeArea(
|
||||
bottom: false,
|
||||
child: SizedBox(
|
||||
height: 56.h,
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: IconButton(
|
||||
onPressed: _close,
|
||||
icon: const Icon(Icons.close),
|
||||
color: Colors.white,
|
||||
tooltip: '关闭',
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'扫一扫',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 18.sp,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
top: scanWindow.bottom + 28.h,
|
||||
left: 24.w,
|
||||
right: 24.w,
|
||||
child: Text(
|
||||
'将二维码放入框内,即可自动扫描',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
color: Colors.white.withValues(alpha: 0.86),
|
||||
fontSize: 15.sp,
|
||||
height: 1.4,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCameraError(BuildContext context, MobileScannerException error) {
|
||||
return ColoredBox(
|
||||
color: Colors.black,
|
||||
child: Center(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 32.w),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.camera_alt_outlined,
|
||||
color: Colors.white.withValues(alpha: 0.82),
|
||||
size: 44.r,
|
||||
),
|
||||
SizedBox(height: 16.h),
|
||||
Text(
|
||||
'无法启动相机,请检查相机权限后重试',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 16.sp,
|
||||
height: 1.45,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 8.h),
|
||||
Text(
|
||||
error.errorDetails?.message ?? error.errorCode.message,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
color: Colors.white.withValues(alpha: 0.58),
|
||||
fontSize: 12.sp,
|
||||
height: 1.35,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 24.h),
|
||||
TextButton(
|
||||
onPressed: _close,
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: Colors.white,
|
||||
side: BorderSide(color: Colors.white.withValues(alpha: 0.44)),
|
||||
),
|
||||
child: const Text('关闭'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ScanLine extends StatelessWidget {
|
||||
const _ScanLine({required this.animation, required this.scanWindow});
|
||||
|
||||
final Animation<double> animation;
|
||||
final Rect scanWindow;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AnimatedBuilder(
|
||||
animation: animation,
|
||||
builder: (context, child) {
|
||||
final inset = 14.r;
|
||||
final top =
|
||||
scanWindow.top +
|
||||
inset +
|
||||
(scanWindow.height - inset * 2) * animation.value;
|
||||
|
||||
return Positioned(
|
||||
left: scanWindow.left + inset,
|
||||
top: top,
|
||||
width: scanWindow.width - inset * 2,
|
||||
child: child!,
|
||||
);
|
||||
},
|
||||
child: Container(
|
||||
height: 2.h,
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF1BD760),
|
||||
borderRadius: BorderRadius.circular(2.r),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: const Color(0xFF1BD760).withValues(alpha: 0.65),
|
||||
blurRadius: 12.r,
|
||||
spreadRadius: 2.r,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ScannerOverlayPainter extends CustomPainter {
|
||||
const _ScannerOverlayPainter({required this.scanWindow});
|
||||
|
||||
final Rect scanWindow;
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final overlayPaint = Paint()..color = Colors.black.withValues(alpha: 0.58);
|
||||
final outerPath = Path()..addRect(Offset.zero & size);
|
||||
final innerPath = Path()
|
||||
..addRRect(RRect.fromRectAndRadius(scanWindow, Radius.circular(8.r)));
|
||||
final overlayPath = Path.combine(
|
||||
PathOperation.difference,
|
||||
outerPath,
|
||||
innerPath,
|
||||
);
|
||||
canvas.drawPath(overlayPath, overlayPaint);
|
||||
|
||||
final borderPaint = Paint()
|
||||
..color = Colors.white.withValues(alpha: 0.38)
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.r;
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(scanWindow, Radius.circular(8.r)),
|
||||
borderPaint,
|
||||
);
|
||||
|
||||
final cornerPaint = Paint()
|
||||
..color = const Color(0xFF1BD760)
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeCap = StrokeCap.round
|
||||
..strokeWidth = 4.r;
|
||||
final cornerLength = 28.r;
|
||||
|
||||
void drawCorner(Offset start, Offset horizontalEnd, Offset verticalEnd) {
|
||||
canvas
|
||||
..drawLine(start, horizontalEnd, cornerPaint)
|
||||
..drawLine(start, verticalEnd, cornerPaint);
|
||||
}
|
||||
|
||||
drawCorner(
|
||||
scanWindow.topLeft,
|
||||
scanWindow.topLeft.translate(cornerLength, 0),
|
||||
scanWindow.topLeft.translate(0, cornerLength),
|
||||
);
|
||||
drawCorner(
|
||||
scanWindow.topRight,
|
||||
scanWindow.topRight.translate(-cornerLength, 0),
|
||||
scanWindow.topRight.translate(0, cornerLength),
|
||||
);
|
||||
drawCorner(
|
||||
scanWindow.bottomLeft,
|
||||
scanWindow.bottomLeft.translate(cornerLength, 0),
|
||||
scanWindow.bottomLeft.translate(0, -cornerLength),
|
||||
);
|
||||
drawCorner(
|
||||
scanWindow.bottomRight,
|
||||
scanWindow.bottomRight.translate(-cornerLength, 0),
|
||||
scanWindow.bottomRight.translate(0, -cornerLength),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _ScannerOverlayPainter oldDelegate) {
|
||||
return oldDelegate.scanWindow != scanWindow;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:webview_flutter/webview_flutter.dart';
|
||||
import 'package:webview_flutter_android/webview_flutter_android.dart';
|
||||
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';
|
||||
|
||||
class WebviewPage extends StatefulWidget {
|
||||
final String url;
|
||||
final String? title;
|
||||
|
||||
const WebviewPage({super.key, required this.url, this.title});
|
||||
|
||||
@override
|
||||
State<WebviewPage> createState() => WebviewPageState();
|
||||
}
|
||||
|
||||
class WebviewPageState extends State<WebviewPage> {
|
||||
WebViewController? _controller;
|
||||
bool _isLoading = true;
|
||||
String? _errorMessage;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_initController();
|
||||
}
|
||||
|
||||
Future<void> _initController() async {
|
||||
if (widget.url?.isEmpty ?? true) {
|
||||
return;
|
||||
}
|
||||
final params = _createPlatformParams();
|
||||
final controller = WebViewController.fromPlatformCreationParams(params)
|
||||
..setJavaScriptMode(JavaScriptMode.unrestricted)
|
||||
..setBackgroundColor(Colors.transparent)
|
||||
..setNavigationDelegate(
|
||||
NavigationDelegate(
|
||||
onProgress: (int progress) {
|
||||
debugPrint('webview - progress: $progress');
|
||||
},
|
||||
onPageStarted: (String url) {
|
||||
debugPrint('webview - page started: $url');
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
_errorMessage = null;
|
||||
});
|
||||
},
|
||||
onPageFinished: (String url) {
|
||||
debugPrint('webview - page finished: $url');
|
||||
if (!mounted) return;
|
||||
setState(() => _isLoading = false);
|
||||
},
|
||||
onHttpError: (HttpResponseError error) {
|
||||
debugPrint(
|
||||
'webview - http error: ${error.response?.uri}, code: ${error.response?.statusCode}',
|
||||
);
|
||||
},
|
||||
onWebResourceError: (WebResourceError error) {
|
||||
debugPrint(
|
||||
'webview error: ${error.description}, code: ${error.errorCode}, url: ${error.url}',
|
||||
);
|
||||
if (!mounted || error.isForMainFrame != true) return;
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
_errorMessage = error.description;
|
||||
});
|
||||
},
|
||||
onNavigationRequest: (NavigationRequest request) {
|
||||
return NavigationDecision.navigate;
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
if (controller.platform is AndroidWebViewController) {
|
||||
AndroidWebViewController.enableDebugging(kDebugMode);
|
||||
await (controller.platform as AndroidWebViewController)
|
||||
.setMediaPlaybackRequiresUserGesture(false);
|
||||
}
|
||||
|
||||
final targetUrl = widget.url ?? '';
|
||||
try {
|
||||
await controller.loadRequest(Uri.parse(targetUrl));
|
||||
} catch (e) {
|
||||
debugPrint('webview - loadRequest failed: $e');
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_isLoading = false;
|
||||
_errorMessage = e.toString();
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!mounted) return;
|
||||
setState(() => _controller = controller);
|
||||
}
|
||||
|
||||
PlatformWebViewControllerCreationParams _createPlatformParams() {
|
||||
if (WebViewPlatform.instance is WebKitWebViewPlatform) {
|
||||
return WebKitWebViewControllerCreationParams(
|
||||
allowsInlineMediaPlayback: true,
|
||||
mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
|
||||
);
|
||||
}
|
||||
return const PlatformWebViewControllerCreationParams();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: Colors.transparent,
|
||||
extendBodyBehindAppBar: true,
|
||||
appBar: AppBar(
|
||||
backgroundColor: Colors.transparent,
|
||||
elevation: 0,
|
||||
title: Text(
|
||||
widget.title ?? '',
|
||||
style: const TextStyle(color: Colors.white),
|
||||
),
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back, color: Colors.white),
|
||||
onPressed: () async {
|
||||
final controller = _controller;
|
||||
if (controller != null && await controller.canGoBack()) {
|
||||
await controller.goBack();
|
||||
} else {
|
||||
if (context.mounted) Navigator.of(context).maybePop();
|
||||
}
|
||||
},
|
||||
),
|
||||
iconTheme: const IconThemeData(color: Colors.white),
|
||||
),
|
||||
|
||||
body: _buildBody(),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildBody() {
|
||||
if (_errorMessage != null) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Text(
|
||||
'页面加载失败\n$_errorMessage',
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(color: Colors.white, fontSize: 14),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final controller = _controller;
|
||||
if (controller == null) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
return Stack(
|
||||
children: [
|
||||
Positioned.fill(child: WebViewWidget(controller: controller)),
|
||||
if (_isLoading) const Center(child: CircularProgressIndicator()),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ export 'app_empty_view.dart';
|
||||
export 'app_error_view.dart';
|
||||
export 'app_loading_view.dart';
|
||||
export 'app_network_image.dart';
|
||||
export 'app_qr_scanner_dialog.dart';
|
||||
export 'app_refresh_list.dart';
|
||||
export 'app_search_bar.dart';
|
||||
export 'app_status_view.dart';
|
||||
|
||||
+5
-1
@@ -16,7 +16,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev
|
||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||
# In Windows, build-name is used as the major, minor, and patch parts
|
||||
# of the product and file versions while build-number is used as the build suffix.
|
||||
version: 1.0.0+2002
|
||||
version: 1.0.0
|
||||
|
||||
environment:
|
||||
sdk: ^3.9.0
|
||||
@@ -47,6 +47,10 @@ dependencies:
|
||||
shared_preferences: ^2.5.5
|
||||
url_launcher: ^6.3.2
|
||||
uuid: ^4.5.3
|
||||
mobile_scanner: ^7.2.0
|
||||
webview_flutter_android: ^4.13.0
|
||||
webview_flutter_wkwebview: ^3.26.0
|
||||
webview_flutter: ^4.14.0
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
@@ -1,131 +0,0 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
// ignore: depend_on_referenced_packages
|
||||
import 'package:permission_handler_platform_interface/permission_handler_platform_interface.dart';
|
||||
|
||||
import 'package:recording_tool/core/permission/permission_service.dart';
|
||||
|
||||
void main() {
|
||||
group('PermissionService.requestMissing', () {
|
||||
late PermissionHandlerPlatform originalPlatform;
|
||||
|
||||
setUp(() {
|
||||
originalPlatform = PermissionHandlerPlatform.instance;
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
PermissionHandlerPlatform.instance = originalPlatform;
|
||||
});
|
||||
|
||||
test('requests only missing permissions and skips granted ones', () async {
|
||||
final platform = FakePermissionHandlerPlatform(
|
||||
statuses: <Permission, PermissionStatus>{
|
||||
Permission.camera: PermissionStatus.granted,
|
||||
Permission.microphone: PermissionStatus.denied,
|
||||
},
|
||||
requestResults: <Permission, PermissionStatus>{
|
||||
Permission.microphone: PermissionStatus.granted,
|
||||
},
|
||||
);
|
||||
PermissionHandlerPlatform.instance = platform;
|
||||
|
||||
final result = await PermissionService.requestMissing(<Permission>[
|
||||
Permission.camera,
|
||||
Permission.microphone,
|
||||
]);
|
||||
|
||||
expect(platform.requestCalls, <List<Permission>>[
|
||||
<Permission>[Permission.microphone],
|
||||
]);
|
||||
expect(result[Permission.camera], PermissionStatus.granted);
|
||||
expect(result[Permission.microphone], PermissionStatus.granted);
|
||||
});
|
||||
|
||||
test(
|
||||
'preserves permanently denied permissions without requesting them',
|
||||
() async {
|
||||
final platform = FakePermissionHandlerPlatform(
|
||||
statuses: <Permission, PermissionStatus>{
|
||||
Permission.camera: PermissionStatus.permanentlyDenied,
|
||||
Permission.microphone: PermissionStatus.denied,
|
||||
},
|
||||
requestResults: <Permission, PermissionStatus>{
|
||||
Permission.microphone: PermissionStatus.granted,
|
||||
},
|
||||
);
|
||||
PermissionHandlerPlatform.instance = platform;
|
||||
|
||||
final result = await PermissionService.requestMissing(<Permission>[
|
||||
Permission.camera,
|
||||
Permission.microphone,
|
||||
]);
|
||||
|
||||
expect(platform.requestCalls, <List<Permission>>[
|
||||
<Permission>[Permission.microphone],
|
||||
]);
|
||||
expect(result[Permission.camera], PermissionStatus.permanentlyDenied);
|
||||
expect(result[Permission.microphone], PermissionStatus.granted);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
group('iOS permission configuration', () {
|
||||
test('Podfile enables camera, microphone and photos permission macros', () {
|
||||
final podfile = File('ios/Podfile').readAsStringSync();
|
||||
|
||||
expect(
|
||||
podfile,
|
||||
contains('flutter_additional_ios_build_settings(target)'),
|
||||
);
|
||||
expect(podfile, contains("'PERMISSION_CAMERA=1'"));
|
||||
expect(podfile, contains("'PERMISSION_MICROPHONE=1'"));
|
||||
expect(podfile, contains("'PERMISSION_PHOTOS=1'"));
|
||||
expect(podfile, contains("'PERMISSION_PHOTOS_ADD_ONLY=1'"));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
class FakePermissionHandlerPlatform extends PermissionHandlerPlatform {
|
||||
FakePermissionHandlerPlatform({
|
||||
required this.statuses,
|
||||
required this.requestResults,
|
||||
});
|
||||
|
||||
final Map<Permission, PermissionStatus> statuses;
|
||||
final Map<Permission, PermissionStatus> requestResults;
|
||||
final List<List<Permission>> requestCalls = <List<Permission>>[];
|
||||
|
||||
@override
|
||||
Future<PermissionStatus> checkPermissionStatus(Permission permission) async {
|
||||
return statuses[permission] ?? PermissionStatus.denied;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<ServiceStatus> checkServiceStatus(Permission permission) async {
|
||||
return ServiceStatus.enabled;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> openAppSettings() async {
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Map<Permission, PermissionStatus>> requestPermissions(
|
||||
List<Permission> permissions,
|
||||
) async {
|
||||
requestCalls.add(List<Permission>.unmodifiable(permissions));
|
||||
return <Permission, PermissionStatus>{
|
||||
for (final permission in permissions)
|
||||
permission: requestResults[permission] ?? PermissionStatus.granted,
|
||||
};
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> shouldShowRequestPermissionRationale(
|
||||
Permission permission,
|
||||
) async {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:recording_tool/core/platform/device_health_checker.dart';
|
||||
import 'package:recording_tool/core/platform/device_health_snapshot.dart';
|
||||
|
||||
void main() {
|
||||
group('DeviceHealthChecker.warningLines', () {
|
||||
test('returns empty when battery and storage are healthy', () {
|
||||
const snapshot = DeviceHealthSnapshot(
|
||||
batteryLevelPercent: 50,
|
||||
storageAvailablePercent: 50,
|
||||
);
|
||||
|
||||
expect(DeviceHealthChecker.warningLines(snapshot), isEmpty);
|
||||
});
|
||||
|
||||
test('returns low battery message only', () {
|
||||
const snapshot = DeviceHealthSnapshot(
|
||||
batteryLevelPercent: 9,
|
||||
storageAvailablePercent: 50,
|
||||
);
|
||||
|
||||
expect(
|
||||
DeviceHealthChecker.warningLines(snapshot),
|
||||
[DeviceHealthChecker.lowBatteryMessage],
|
||||
);
|
||||
});
|
||||
|
||||
test('returns low storage message only', () {
|
||||
const snapshot = DeviceHealthSnapshot(
|
||||
batteryLevelPercent: 50,
|
||||
storageAvailablePercent: 9.9,
|
||||
);
|
||||
|
||||
expect(
|
||||
DeviceHealthChecker.warningLines(snapshot),
|
||||
[DeviceHealthChecker.lowStorageMessage],
|
||||
);
|
||||
});
|
||||
|
||||
test('returns both messages when battery and storage are low', () {
|
||||
const snapshot = DeviceHealthSnapshot(
|
||||
batteryLevelPercent: 5,
|
||||
storageAvailablePercent: 5,
|
||||
);
|
||||
|
||||
expect(
|
||||
DeviceHealthChecker.warningLines(snapshot),
|
||||
[
|
||||
DeviceHealthChecker.lowBatteryMessage,
|
||||
DeviceHealthChecker.lowStorageMessage,
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test('does not warn at exactly threshold percent', () {
|
||||
const snapshot = DeviceHealthSnapshot(
|
||||
batteryLevelPercent: 10,
|
||||
storageAvailablePercent: 10,
|
||||
);
|
||||
|
||||
expect(DeviceHealthChecker.warningLines(snapshot), isEmpty);
|
||||
});
|
||||
|
||||
test('skips battery warning when level is unknown', () {
|
||||
const snapshot = DeviceHealthSnapshot(
|
||||
batteryLevelPercent: null,
|
||||
storageAvailablePercent: 5,
|
||||
);
|
||||
|
||||
expect(
|
||||
DeviceHealthChecker.warningLines(snapshot),
|
||||
[DeviceHealthChecker.lowStorageMessage],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('DeviceHealthSnapshot.fromMap', () {
|
||||
test('parses native map fields', () {
|
||||
final snapshot = DeviceHealthSnapshot.fromMap({
|
||||
'batteryLevelPercent': 42,
|
||||
'storageAvailablePercent': 12.5,
|
||||
});
|
||||
|
||||
expect(snapshot.batteryLevelPercent, 42);
|
||||
expect(snapshot.storageAvailablePercent, 12.5);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_screenutil/flutter_screenutil.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:recording_tool/features/dialog/dialog-record.dart';
|
||||
import 'package:recording_tool/features/recording/widgets/widget_recording_saved_dialog.dart';
|
||||
import 'package:recording_tool/gen/assets.gen.dart';
|
||||
|
||||
void main() {
|
||||
Future<void> pumpDialogHost(WidgetTester tester, Widget child) async {
|
||||
await tester.pumpWidget(
|
||||
ScreenUtilInit(
|
||||
designSize: const Size(375, 812),
|
||||
builder: (context, _) {
|
||||
return MaterialApp(home: Scaffold(body: child));
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets('single button dialog shows configured content and closes', (
|
||||
tester,
|
||||
) async {
|
||||
var tapped = false;
|
||||
|
||||
await pumpDialogHost(
|
||||
tester,
|
||||
Builder(
|
||||
builder: (context) {
|
||||
return TextButton(
|
||||
onPressed: () {
|
||||
RecordDialog.showSingle(
|
||||
context,
|
||||
title: '无选手信息!',
|
||||
buttonText: '粘贴',
|
||||
onPressed: () => tapped = true,
|
||||
);
|
||||
},
|
||||
child: const Text('show'),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
await tester.tap(find.text('show'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.byType(Image), findsOneWidget);
|
||||
expect(find.image(AssetImage(Assets.images.imageDialogBg.path)), findsOne);
|
||||
expect(find.text('无选手信息!'), findsOneWidget);
|
||||
expect(find.text('粘贴'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.text('粘贴'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(tapped, isTrue);
|
||||
expect(find.text('无选手信息!'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('double button dialog dispatches each action', (tester) async {
|
||||
var leftTapped = false;
|
||||
var rightTapped = false;
|
||||
|
||||
await pumpDialogHost(
|
||||
tester,
|
||||
Builder(
|
||||
builder: (context) {
|
||||
return TextButton(
|
||||
onPressed: () {
|
||||
RecordDialog.showDouble(
|
||||
context,
|
||||
title: '本轮比赛视频已保存到相册\n请选择后续录制信息',
|
||||
leftText: '继续本轮',
|
||||
rightText: '录制新轮',
|
||||
onLeftPressed: () => leftTapped = true,
|
||||
onRightPressed: () => rightTapped = true,
|
||||
);
|
||||
},
|
||||
child: const Text('show'),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
await tester.tap(find.text('show'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('继续本轮'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(leftTapped, isTrue);
|
||||
expect(rightTapped, isFalse);
|
||||
|
||||
await tester.tap(find.text('show'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('录制新轮'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(rightTapped, isTrue);
|
||||
});
|
||||
|
||||
testWidgets('recording saved dialog follows design title only', (
|
||||
tester,
|
||||
) async {
|
||||
await pumpDialogHost(
|
||||
tester,
|
||||
Builder(
|
||||
builder: (context) {
|
||||
return TextButton(
|
||||
onPressed: () {
|
||||
showRecordingSavedDialog(
|
||||
context,
|
||||
sessionTitle: '王东方 丨李想 空中格斗赛',
|
||||
onContinueRound: () {},
|
||||
onRecordNewRound: () {},
|
||||
);
|
||||
},
|
||||
child: const Text('show'),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
await tester.tap(find.text('show'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('王东方 丨李想 空中格斗赛'), findsNothing);
|
||||
expect(find.text('本轮比赛视频已保存到相册\n请选择后续录制信息'), findsOneWidget);
|
||||
expect(find.text('继续本轮'), findsOneWidget);
|
||||
expect(find.text('录制新轮'), findsOneWidget);
|
||||
});
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:recording_tool/features/recording/model/model_clipboard.dart';
|
||||
|
||||
void main() {
|
||||
group('ClipboardRecordingModel', () {
|
||||
const clipboardJson = {
|
||||
'title': '王东方 丨李想 空中格斗赛',
|
||||
'startTimestamp': 1717334400,
|
||||
'endTimestamp': 1717334400,
|
||||
'address': '广州市番禺区·粤港澳大湾区青年人才双创小镇',
|
||||
};
|
||||
|
||||
test('parses mini program clipboard JSON', () {
|
||||
final model = ClipboardRecordingModel.fromJson(clipboardJson);
|
||||
|
||||
expect(model.title, '王东方 丨李想 空中格斗赛');
|
||||
expect(model.startTimestamp, 1717334400);
|
||||
expect(model.endTimestamp, 1717334400);
|
||||
expect(model.address, '广州市番禺区·粤港澳大湾区青年人才双创小镇');
|
||||
expect(model.filename, isNull);
|
||||
expect(model.toJson(), clipboardJson);
|
||||
});
|
||||
|
||||
test('parses JSON without optional timestamps', () {
|
||||
final json = {
|
||||
'title': '郑昌梦 丨黄伟依 空中格斗赛 小学组',
|
||||
'address': '广东省汕头市番禺区青蓝街 111 号',
|
||||
'filename': '郑昌梦_黄伟依_6月3日测试-1_空中格斗赛',
|
||||
};
|
||||
final model = ClipboardRecordingModel.fromJson(json);
|
||||
|
||||
expect(model.title, json['title']);
|
||||
expect(model.address, json['address']);
|
||||
expect(model.filename, json['filename']);
|
||||
expect(model.startTimestamp, isNull);
|
||||
expect(model.endTimestamp, isNull);
|
||||
});
|
||||
|
||||
test('parses optional filename from mini program JSON', () {
|
||||
final json = {
|
||||
...clipboardJson,
|
||||
'filename': '选手名称_选手ID_赛事名称_赛项',
|
||||
};
|
||||
final model = ClipboardRecordingModel.fromJson(json);
|
||||
|
||||
expect(model.filename, '选手名称_选手ID_赛事名称_赛项');
|
||||
expect(model.toJson(), json);
|
||||
});
|
||||
|
||||
test('throws FormatException when required field is missing', () {
|
||||
final json = Map<String, dynamic>.from(clipboardJson)..remove('title');
|
||||
|
||||
expect(
|
||||
() => ClipboardRecordingModel.fromJson(json),
|
||||
throwsA(isA<FormatException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('throws FormatException when optional int field has wrong type', () {
|
||||
final json = {...clipboardJson, 'startTimestamp': '1717334400'};
|
||||
|
||||
expect(
|
||||
() => ClipboardRecordingModel.fromJson(json),
|
||||
throwsA(isA<FormatException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('throws FormatException when required address is missing', () {
|
||||
final json = Map<String, dynamic>.from(clipboardJson)..remove('address');
|
||||
|
||||
expect(
|
||||
() => ClipboardRecordingModel.fromJson(json),
|
||||
throwsA(isA<FormatException>()),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:recording_tool/features/recording/utils/recording_display_name.dart';
|
||||
|
||||
void main() {
|
||||
group('sanitizeRecordingBaseName', () {
|
||||
test('removes invalid path characters', () {
|
||||
expect(
|
||||
sanitizeRecordingBaseName(r'a/b:c*d?e"f<g>h|i'),
|
||||
'a_b_c_d_e_f_g_h_i',
|
||||
);
|
||||
});
|
||||
|
||||
test('returns null for blank input', () {
|
||||
expect(sanitizeRecordingBaseName(' '), isNull);
|
||||
});
|
||||
|
||||
test('truncates overly long names', () {
|
||||
final long = 'a' * 200;
|
||||
expect(sanitizeRecordingBaseName(long)!.length, 120);
|
||||
});
|
||||
});
|
||||
|
||||
group('resolveRecordingDisplayName', () {
|
||||
test('uses sanitized clipboard filename when present', () {
|
||||
expect(
|
||||
resolveRecordingDisplayName('选手名称_选手ID_赛事名称_赛项'),
|
||||
'选手名称_选手ID_赛事名称_赛项',
|
||||
);
|
||||
});
|
||||
|
||||
test('falls back to REC_ prefix when clipboard filename is empty', () {
|
||||
expect(resolveRecordingDisplayName(null), startsWith('REC_'));
|
||||
expect(resolveRecordingDisplayName(''), startsWith('REC_'));
|
||||
});
|
||||
});
|
||||
|
||||
group('withVideoExtension', () {
|
||||
test('appends mp4 on Android', () {
|
||||
expect(
|
||||
withVideoExtension('match', isIOS: false),
|
||||
'match.mp4',
|
||||
);
|
||||
});
|
||||
|
||||
test('appends mov on iOS', () {
|
||||
expect(
|
||||
withVideoExtension('match', isIOS: true),
|
||||
'match.mov',
|
||||
);
|
||||
});
|
||||
|
||||
test('keeps existing extension', () {
|
||||
expect(withVideoExtension('a.mp4', isIOS: false), 'a.mp4');
|
||||
expect(withVideoExtension('a.MOV', isIOS: true), 'a.MOV');
|
||||
});
|
||||
});
|
||||
|
||||
group('recordingFileNameForPlatform', () {
|
||||
test('combines clipboard name with platform extension', () {
|
||||
expect(
|
||||
recordingFileNameForPlatform(
|
||||
'选手名称_选手ID_赛事名称_赛项',
|
||||
isIOS: false,
|
||||
),
|
||||
'选手名称_选手ID_赛事名称_赛项.mp4',
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:recording_tool/features/recording/platform/recording_platform.dart';
|
||||
|
||||
void main() {
|
||||
group('RecordingPlatform support', () {
|
||||
test('supports Android and iOS hosts only', () {
|
||||
expect(
|
||||
RecordingPlatform.supportsHost(isAndroid: true, isIOS: false),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
RecordingPlatform.supportsHost(isAndroid: false, isIOS: true),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
RecordingPlatform.supportsHost(isAndroid: false, isIOS: false),
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,223 +0,0 @@
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:permission_handler/permission_handler.dart';
|
||||
import 'package:recording_tool/features/recording/view-model/view_model_recording.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
const defaultClipboardTitle = '';
|
||||
const validClipboardText =
|
||||
'{"title":"王东方 丨李想 空中格斗赛","startTimestamp":1717334400,"endTimestamp":1717334400,"filename":"选手名称_选手ID_赛事名称_赛项","address":"广州市番禺区·粤港澳大湾区青年人才双创小镇"}';
|
||||
|
||||
Future<void> setClipboardText(String? text) async {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(SystemChannels.platform, (call) async {
|
||||
if (call.method == 'Clipboard.getData') {
|
||||
return text == null ? null : <String, dynamic>{'text': text};
|
||||
}
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
tearDown(() {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(SystemChannels.platform, null);
|
||||
});
|
||||
|
||||
group('RecordingViewModel', () {
|
||||
test('initializes with default clipboard and session state', () {
|
||||
final container = ProviderContainer();
|
||||
addTearDown(container.dispose);
|
||||
|
||||
final model = container.read(recordingViewModelProvider);
|
||||
expect(model.hasValidClipboardInfo, isFalse);
|
||||
expect(model.clipboardRecordingModel.title, defaultClipboardTitle);
|
||||
expect(model.session.isPreviewReady, isFalse);
|
||||
expect(model.session.isRecording, isFalse);
|
||||
});
|
||||
});
|
||||
|
||||
group('recordingGalleryPermissionsForHost', () {
|
||||
test('requests only add-only photo permission on iOS', () {
|
||||
final permissions = recordingGalleryPermissionsForHost(
|
||||
isIOS: true,
|
||||
isAndroid: false,
|
||||
);
|
||||
|
||||
expect(permissions, <Permission>[Permission.photosAddOnly]);
|
||||
expect(permissions, isNot(contains(Permission.photos)));
|
||||
});
|
||||
|
||||
test('keeps Android gallery permissions unchanged', () {
|
||||
final permissions = recordingGalleryPermissionsForHost(
|
||||
isIOS: false,
|
||||
isAndroid: true,
|
||||
);
|
||||
|
||||
expect(permissions, <Permission>[Permission.videos, Permission.storage]);
|
||||
});
|
||||
});
|
||||
|
||||
group('RecordingViewModel.getClipboardContent', () {
|
||||
test(
|
||||
'updates state when clipboard contains valid mini program JSON',
|
||||
() async {
|
||||
await setClipboardText(validClipboardText);
|
||||
final container = ProviderContainer();
|
||||
addTearDown(container.dispose);
|
||||
|
||||
final result = await container
|
||||
.read(recordingViewModelProvider.notifier)
|
||||
.getClipboardContent();
|
||||
|
||||
expect(result, ClipboardReadResult.success);
|
||||
final model = container.read(recordingViewModelProvider);
|
||||
expect(model.hasValidClipboardInfo, isTrue);
|
||||
expect(model.clipboardRecordingModel.title, '王东方 丨李想 空中格斗赛');
|
||||
expect(model.clipboardRecordingModel.startTimestamp, 1717334400);
|
||||
expect(model.clipboardRecordingModel.endTimestamp, 1717334400);
|
||||
expect(model.clipboardRecordingModel.address, '广州市番禺区·粤港澳大湾区青年人才双创小镇');
|
||||
expect(model.clipboardRecordingModel.filename, '选手名称_选手ID_赛事名称_赛项');
|
||||
},
|
||||
);
|
||||
|
||||
test('returns empty when clipboard is empty', () async {
|
||||
await setClipboardText('');
|
||||
final container = ProviderContainer();
|
||||
addTearDown(container.dispose);
|
||||
|
||||
final result = await container
|
||||
.read(recordingViewModelProvider.notifier)
|
||||
.getClipboardContent();
|
||||
|
||||
expect(result, ClipboardReadResult.empty);
|
||||
final model = container.read(recordingViewModelProvider);
|
||||
expect(model.hasValidClipboardInfo, isFalse);
|
||||
expect(model.clipboardRecordingModel.title, defaultClipboardTitle);
|
||||
});
|
||||
|
||||
test('returns invalid when clipboard is not JSON', () async {
|
||||
await setClipboardText('hello');
|
||||
final container = ProviderContainer();
|
||||
addTearDown(container.dispose);
|
||||
|
||||
final result = await container
|
||||
.read(recordingViewModelProvider.notifier)
|
||||
.getClipboardContent();
|
||||
|
||||
expect(result, ClipboardReadResult.invalid);
|
||||
expect(
|
||||
container
|
||||
.read(recordingViewModelProvider)
|
||||
.clipboardRecordingModel
|
||||
.title,
|
||||
defaultClipboardTitle,
|
||||
);
|
||||
expect(
|
||||
container.read(recordingViewModelProvider).hasValidClipboardInfo,
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
|
||||
test('returns invalid when clipboard JSON is not an object', () async {
|
||||
await setClipboardText('[1,2,3]');
|
||||
final container = ProviderContainer();
|
||||
addTearDown(container.dispose);
|
||||
|
||||
final result = await container
|
||||
.read(recordingViewModelProvider.notifier)
|
||||
.getClipboardContent();
|
||||
|
||||
expect(result, ClipboardReadResult.invalid);
|
||||
expect(
|
||||
container
|
||||
.read(recordingViewModelProvider)
|
||||
.clipboardRecordingModel
|
||||
.title,
|
||||
defaultClipboardTitle,
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'returns invalid when clipboard JSON misses required address',
|
||||
() async {
|
||||
await setClipboardText('{"title":"王东方 丨李想 空中格斗赛"}');
|
||||
final container = ProviderContainer();
|
||||
addTearDown(container.dispose);
|
||||
|
||||
final result = await container
|
||||
.read(recordingViewModelProvider.notifier)
|
||||
.getClipboardContent();
|
||||
|
||||
expect(result, ClipboardReadResult.invalid);
|
||||
expect(
|
||||
container
|
||||
.read(recordingViewModelProvider)
|
||||
.clipboardRecordingModel
|
||||
.title,
|
||||
defaultClipboardTitle,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('updates state when clipboard omits optional timestamps', () async {
|
||||
await setClipboardText(
|
||||
'{"title":"郑昌梦 丨黄伟依 空中格斗赛 小学组","address":"广东省汕头市番禺区青蓝街 111 号","filename":"郑昌梦_黄伟依_6月3日测试-1_空中格斗赛"}',
|
||||
);
|
||||
final container = ProviderContainer();
|
||||
addTearDown(container.dispose);
|
||||
|
||||
final result = await container
|
||||
.read(recordingViewModelProvider.notifier)
|
||||
.getClipboardContent();
|
||||
|
||||
expect(result, ClipboardReadResult.success);
|
||||
final model = container.read(recordingViewModelProvider);
|
||||
expect(model.hasValidClipboardInfo, isTrue);
|
||||
expect(model.clipboardRecordingModel.startTimestamp, isNull);
|
||||
expect(model.clipboardRecordingModel.endTimestamp, isNull);
|
||||
expect(model.clipboardRecordingModel.filename, '郑昌梦_黄伟依_6月3日测试-1_空中格斗赛');
|
||||
});
|
||||
|
||||
test('returns invalid when clipboard JSON has wrong field type', () async {
|
||||
await setClipboardText(
|
||||
'{"title":"王东方 丨李想 空中格斗赛","startTimestamp":"1717334400","endTimestamp":1717334400,"address":"广州市番禺区·粤港澳大湾区青年人才双创小镇"}',
|
||||
);
|
||||
final container = ProviderContainer();
|
||||
addTearDown(container.dispose);
|
||||
|
||||
final result = await container
|
||||
.read(recordingViewModelProvider.notifier)
|
||||
.getClipboardContent();
|
||||
|
||||
expect(result, ClipboardReadResult.invalid);
|
||||
expect(
|
||||
container
|
||||
.read(recordingViewModelProvider)
|
||||
.clipboardRecordingModel
|
||||
.title,
|
||||
defaultClipboardTitle,
|
||||
);
|
||||
});
|
||||
|
||||
test('returns invalid when title is blank', () async {
|
||||
await setClipboardText(
|
||||
'{"title":" ","startTimestamp":1717334400,"endTimestamp":1717334400,"address":"广州市"}',
|
||||
);
|
||||
final container = ProviderContainer();
|
||||
addTearDown(container.dispose);
|
||||
|
||||
final result = await container
|
||||
.read(recordingViewModelProvider.notifier)
|
||||
.getClipboardContent();
|
||||
|
||||
expect(result, ClipboardReadResult.invalid);
|
||||
expect(
|
||||
container.read(recordingViewModelProvider).hasValidClipboardInfo,
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_screenutil/flutter_screenutil.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:recording_tool/features/recording/widgets/widget_record_header.dart';
|
||||
import 'package:recording_tool/gen/assets.gen.dart';
|
||||
|
||||
void main() {
|
||||
Future<void> pumpHeader(
|
||||
WidgetTester tester, {
|
||||
required bool hasValidClipboardInfo,
|
||||
String? eventTitle,
|
||||
}) async {
|
||||
await tester.pumpWidget(
|
||||
ScreenUtilInit(
|
||||
designSize: const Size(375, 812),
|
||||
builder: (context, _) {
|
||||
return MaterialApp(
|
||||
home: Scaffold(
|
||||
body: RecordHeaderWidget(
|
||||
hasValidClipboardInfo: hasValidClipboardInfo,
|
||||
eventTitle: eventTitle,
|
||||
isRecording: false,
|
||||
onPasteEventInfo: () async {},
|
||||
onClearEventInfo: () {},
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets('paste player info button uses copy image asset', (tester) async {
|
||||
await pumpHeader(tester, hasValidClipboardInfo: false);
|
||||
|
||||
expect(find.text('粘贴选手信息'), findsOneWidget);
|
||||
expect(find.image(AssetImage(Assets.images.imageCopy.path)), findsOne);
|
||||
});
|
||||
|
||||
testWidgets('clear player info button uses delete image asset', (
|
||||
tester,
|
||||
) async {
|
||||
await pumpHeader(
|
||||
tester,
|
||||
hasValidClipboardInfo: true,
|
||||
eventTitle: '王东方 丨李想 空中格斗赛',
|
||||
);
|
||||
|
||||
expect(find.text('王东方 丨李想 空中格斗赛'), findsOneWidget);
|
||||
expect(find.image(AssetImage(Assets.images.imageDelete.path)), findsOne);
|
||||
});
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_screenutil/flutter_screenutil.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:recording_tool/features/recording/widgets/widget_recording_button.dart';
|
||||
|
||||
void main() {
|
||||
const designSize = Size(375, 812);
|
||||
const morphDuration = Duration(milliseconds: 380);
|
||||
|
||||
Future<void> pumpButton(
|
||||
WidgetTester tester, {
|
||||
required bool isRecording,
|
||||
bool isStartingRecording = false,
|
||||
}) async {
|
||||
await tester.pumpWidget(
|
||||
ScreenUtilInit(
|
||||
designSize: designSize,
|
||||
builder: (context, _) {
|
||||
return MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Center(
|
||||
child: RecordingControlButton(
|
||||
isRecording: isRecording,
|
||||
isStartingRecording: isStartingRecording,
|
||||
onTap: () {},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
Size innerCoreSize(WidgetTester tester) {
|
||||
final finder = find.byWidgetPredicate(
|
||||
(widget) =>
|
||||
widget is Container &&
|
||||
widget.decoration is BoxDecoration &&
|
||||
(widget.decoration! as BoxDecoration).color == Colors.red,
|
||||
);
|
||||
return tester.getSize(finder);
|
||||
}
|
||||
|
||||
testWidgets('idle state uses large circular inner core', (tester) async {
|
||||
await pumpButton(tester, isRecording: false);
|
||||
|
||||
final size = innerCoreSize(tester);
|
||||
expect(size.width, closeTo(62.r, 0.5));
|
||||
expect(size.height, closeTo(62.r, 0.5));
|
||||
});
|
||||
|
||||
testWidgets('isStartingRecording morphs to stop square before isRecording', (
|
||||
tester,
|
||||
) async {
|
||||
await pumpButton(
|
||||
tester,
|
||||
isRecording: false,
|
||||
isStartingRecording: true,
|
||||
);
|
||||
|
||||
await tester.pump(morphDuration);
|
||||
await tester.pump();
|
||||
|
||||
final size = innerCoreSize(tester);
|
||||
expect(size.width, closeTo(22.r, 0.5));
|
||||
expect(size.height, closeTo(22.r, 0.5));
|
||||
});
|
||||
|
||||
testWidgets('isRecording forward and reverse morph without errors', (
|
||||
tester,
|
||||
) async {
|
||||
await pumpButton(tester, isRecording: false);
|
||||
|
||||
await tester.pumpWidget(
|
||||
ScreenUtilInit(
|
||||
designSize: designSize,
|
||||
builder: (context, _) {
|
||||
return MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Center(
|
||||
child: RecordingControlButton(
|
||||
isRecording: true,
|
||||
onTap: () {},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
await tester.pump(morphDuration);
|
||||
await tester.pump();
|
||||
|
||||
expect(innerCoreSize(tester).width, closeTo(22.r, 0.5));
|
||||
|
||||
await tester.pumpWidget(
|
||||
ScreenUtilInit(
|
||||
designSize: designSize,
|
||||
builder: (context, _) {
|
||||
return MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Center(
|
||||
child: RecordingControlButton(
|
||||
isRecording: false,
|
||||
onTap: () {},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
await tester.pump(morphDuration);
|
||||
await tester.pump();
|
||||
|
||||
expect(innerCoreSize(tester).width, closeTo(62.r, 0.5));
|
||||
});
|
||||
|
||||
testWidgets('failed start rolls morph back to idle circle', (tester) async {
|
||||
await pumpButton(
|
||||
tester,
|
||||
isRecording: false,
|
||||
isStartingRecording: true,
|
||||
);
|
||||
await tester.pump(morphDuration);
|
||||
await tester.pump();
|
||||
|
||||
expect(innerCoreSize(tester).width, closeTo(22.r, 0.5));
|
||||
|
||||
await pumpButton(tester, isRecording: false, isStartingRecording: false);
|
||||
await tester.pump(morphDuration);
|
||||
await tester.pump();
|
||||
|
||||
expect(innerCoreSize(tester).width, closeTo(62.r, 0.5));
|
||||
});
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_screenutil/flutter_screenutil.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:recording_tool/features/recording/widgets/widget_recording_touch_lock_overlay.dart';
|
||||
|
||||
void main() {
|
||||
group('resolveRecordingTouchLockUnlockIntent', () {
|
||||
test('returns stopRecording for portrait bottom 30 percent', () {
|
||||
final intent = resolveRecordingTouchLockUnlockIntent(
|
||||
position: const Offset(120, 466.9),
|
||||
size: const Size(375, 667),
|
||||
);
|
||||
|
||||
expect(intent, RecordingTouchLockUnlockIntent.stopRecording);
|
||||
});
|
||||
|
||||
test('returns unlockOnly for portrait area outside bottom 30 percent', () {
|
||||
final intent = resolveRecordingTouchLockUnlockIntent(
|
||||
position: const Offset(120, 320),
|
||||
size: const Size(375, 667),
|
||||
);
|
||||
|
||||
expect(intent, RecordingTouchLockUnlockIntent.unlockOnly);
|
||||
});
|
||||
|
||||
test('returns stopRecording for landscape right 30 percent', () {
|
||||
final intent = resolveRecordingTouchLockUnlockIntent(
|
||||
position: const Offset(466.9, 120),
|
||||
size: const Size(667, 375),
|
||||
);
|
||||
|
||||
expect(intent, RecordingTouchLockUnlockIntent.stopRecording);
|
||||
});
|
||||
|
||||
test('returns unlockOnly for landscape area outside right 30 percent', () {
|
||||
final intent = resolveRecordingTouchLockUnlockIntent(
|
||||
position: const Offset(320, 120),
|
||||
size: const Size(667, 375),
|
||||
);
|
||||
|
||||
expect(intent, RecordingTouchLockUnlockIntent.unlockOnly);
|
||||
});
|
||||
});
|
||||
|
||||
group('RecordingTouchLockOverlayWidget', () {
|
||||
Future<void> pumpOverlay(
|
||||
WidgetTester tester, {
|
||||
required Size surfaceSize,
|
||||
required ValueChanged<RecordingTouchLockUnlockIntent> onUnlocked,
|
||||
}) async {
|
||||
await tester.binding.setSurfaceSize(surfaceSize);
|
||||
addTearDown(() => tester.binding.setSurfaceSize(null));
|
||||
|
||||
await tester.pumpWidget(
|
||||
ScreenUtilInit(
|
||||
designSize: const Size(375, 812),
|
||||
builder: (context, _) {
|
||||
return MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Stack(
|
||||
children: [
|
||||
RecordingTouchLockOverlayWidget(
|
||||
enabled: true,
|
||||
unlockHoldDuration: const Duration(seconds: 2),
|
||||
onUnlocked: onUnlocked,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets('long press in portrait bottom 30 percent stops recording', (
|
||||
tester,
|
||||
) async {
|
||||
RecordingTouchLockUnlockIntent? receivedIntent;
|
||||
await pumpOverlay(
|
||||
tester,
|
||||
surfaceSize: const Size(375, 667),
|
||||
onUnlocked: (intent) => receivedIntent = intent,
|
||||
);
|
||||
|
||||
final gesture = await tester.startGesture(const Offset(120, 600));
|
||||
await tester.pump(const Duration(seconds: 2));
|
||||
await gesture.up();
|
||||
|
||||
expect(receivedIntent, RecordingTouchLockUnlockIntent.stopRecording);
|
||||
});
|
||||
|
||||
testWidgets('long press outside stop area only unlocks', (tester) async {
|
||||
RecordingTouchLockUnlockIntent? receivedIntent;
|
||||
await pumpOverlay(
|
||||
tester,
|
||||
surfaceSize: const Size(375, 667),
|
||||
onUnlocked: (intent) => receivedIntent = intent,
|
||||
);
|
||||
|
||||
final gesture = await tester.startGesture(const Offset(120, 320));
|
||||
await tester.pump(const Duration(seconds: 2));
|
||||
await gesture.up();
|
||||
|
||||
expect(receivedIntent, RecordingTouchLockUnlockIntent.unlockOnly);
|
||||
});
|
||||
|
||||
testWidgets('releasing before hold duration does not unlock', (
|
||||
tester,
|
||||
) async {
|
||||
RecordingTouchLockUnlockIntent? receivedIntent;
|
||||
await pumpOverlay(
|
||||
tester,
|
||||
surfaceSize: const Size(375, 667),
|
||||
onUnlocked: (intent) => receivedIntent = intent,
|
||||
);
|
||||
|
||||
final gesture = await tester.startGesture(const Offset(120, 600));
|
||||
await tester.pump(const Duration(milliseconds: 1500));
|
||||
await gesture.up();
|
||||
await tester.pump(const Duration(seconds: 1));
|
||||
|
||||
expect(receivedIntent, isNull);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:recording_tool/app/app.dart';
|
||||
import 'package:recording_tool/features/recording/widgets/widget_recording_button.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
const validClipboardText =
|
||||
'{"title":"王东方 丨李想 空中格斗赛","startTimestamp":1717334400,"endTimestamp":1717334400,"filename":"选手名称_选手ID_赛事名称_赛项","address":"广州市番禺区·粤港澳大湾区青年人才双创小镇"}';
|
||||
|
||||
String? clipboardText;
|
||||
|
||||
setUp(() {
|
||||
clipboardText = null;
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(SystemChannels.platform, (call) async {
|
||||
if (call.method == 'Clipboard.getData') {
|
||||
return clipboardText == null
|
||||
? null
|
||||
: <String, dynamic>{'text': clipboardText};
|
||||
}
|
||||
return null;
|
||||
});
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(SystemChannels.platform, null);
|
||||
});
|
||||
|
||||
Future<void> pumpRecordingApp(WidgetTester tester) async {
|
||||
await tester.pumpWidget(const ProviderScope(child: FlutterTemplateApp()));
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 500));
|
||||
await tester.pump(const Duration(seconds: 1));
|
||||
}
|
||||
|
||||
testWidgets('recording app renders recording page', (tester) async {
|
||||
await pumpRecordingApp(tester);
|
||||
|
||||
final recordButton = find.byType(RecordingControlButton);
|
||||
|
||||
expect(recordButton, findsOneWidget);
|
||||
expect(
|
||||
tester.getCenter(recordButton).dx,
|
||||
closeTo(tester.getCenter(find.byType(Scaffold)).dx, 0.5),
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('shows paste event info button when title is empty', (
|
||||
tester,
|
||||
) async {
|
||||
clipboardText = '';
|
||||
|
||||
await pumpRecordingApp(tester);
|
||||
|
||||
expect(find.text('粘贴选手信息'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('pastes valid event info from clipboard', (tester) async {
|
||||
clipboardText = '';
|
||||
|
||||
await pumpRecordingApp(tester);
|
||||
|
||||
clipboardText = validClipboardText;
|
||||
await tester.tap(find.text('粘贴选手信息'));
|
||||
await tester.pump(const Duration(milliseconds: 700));
|
||||
|
||||
expect(find.text('王东方 丨李想 空中格斗赛'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('shows no event info toast when pasted clipboard is invalid', (
|
||||
tester,
|
||||
) async {
|
||||
clipboardText = '';
|
||||
|
||||
await pumpRecordingApp(tester);
|
||||
|
||||
clipboardText = 'hello';
|
||||
await tester.tap(find.text('粘贴选手信息'));
|
||||
await tester.pump();
|
||||
|
||||
expect(find.text('王东方 丨李想 空中格斗赛'), findsNothing);
|
||||
expect(find.text('无选手信息'), findsOneWidget);
|
||||
|
||||
await tester.pump(const Duration(seconds: 2));
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user