diff --git a/Front/android/app/src/main/AndroidManifest.xml b/Front/android/app/src/main/AndroidManifest.xml index 2ab0a0a..969b7f2 100644 --- a/Front/android/app/src/main/AndroidManifest.xml +++ b/Front/android/app/src/main/AndroidManifest.xml @@ -22,6 +22,11 @@ android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize"> + + + + + + + diff --git a/call/android/app/src/main/AndroidManifest.xml b/call/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..60bf473 --- /dev/null +++ b/call/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/call/android/app/src/main/kotlin/com/example/call/AudioEngine.kt b/call/android/app/src/main/kotlin/com/example/call/AudioEngine.kt new file mode 100644 index 0000000..3cee2be --- /dev/null +++ b/call/android/app/src/main/kotlin/com/example/call/AudioEngine.kt @@ -0,0 +1,288 @@ +package com.example.call + +import android.content.Context +import android.media.* +import android.os.Handler +import android.os.Looper +import android.util.Log +import io.flutter.plugin.common.BinaryMessenger +import io.flutter.plugin.common.EventChannel +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel +import java.nio.ByteBuffer +import java.util.concurrent.atomic.AtomicBoolean + +/** + * AudioEngine — Android native layer for low-latency audio I/O. + * + * MethodChannel "com.example.call/audio_control" + * startCapture(sampleRate: Int, source: Int) → "ok" + * stopCapture() → "ok" + * startPlayback(sampleRate: Int) → "ok" + * stopPlayback() → "ok" + * writePlayback(samples: ByteArray) → "ok" (Int16 LE samples) + * setSpeakerMode(enabled: Boolean) → "ok" + * getAudioRouteInfo() → Map + * + * EventChannel "com.example.call/audio_capture" + * Streams ByteArray (Int16 LE) chunks captured from AudioRecord. + * Each event is exactly CAPTURE_CHUNK_SAMPLES × 2 bytes. + */ +object AudioEngine { + + private const val TAG = "AudioEngine" + + // ── Channel names ──────────────────────────────────────────────── + const val METHOD_CHANNEL = "com.example.call/audio_control" + const val EVENT_CHANNEL = "com.example.call/audio_capture" + + // ── Audio parameters ───────────────────────────────────────────── + // Matches the modem sample rate; must be 8000 Hz for cellular compatibility. + private const val SAMPLE_RATE = 8000 + + // Number of Int16 samples delivered per EventChannel event. + // 160 samples = 20 ms at 8 kHz → one LPC subframe. + private const val CAPTURE_CHUNK_SAMPLES = 160 + + // Internal AudioRecord buffer: 4× chunk size to reduce overruns. + private const val RECORD_BUFFER_SAMPLES = CAPTURE_CHUNK_SAMPLES * 4 + + // Internal AudioTrack buffer: 80 ms headroom. + private const val PLAYBACK_BUFFER_SAMPLES = SAMPLE_RATE / 1000 * 80 + + // ── State ──────────────────────────────────────────────────────── + private var audioRecord: AudioRecord? = null + private var audioTrack: AudioTrack? = null + private var captureThread: Thread? = null + private val capturing = AtomicBoolean(false) + private val playing = AtomicBoolean(false) + + private var eventSink: EventChannel.EventSink? = null + private val mainHandler = Handler(Looper.getMainLooper()) + + private lateinit var appContext: Context + + // ── Registration ───────────────────────────────────────────────── + fun register(context: Context, messenger: BinaryMessenger) { + appContext = context.applicationContext + + MethodChannel(messenger, METHOD_CHANNEL).setMethodCallHandler { call, result -> + handleMethod(call, result) + } + EventChannel(messenger, EVENT_CHANNEL).setStreamHandler(object : EventChannel.StreamHandler { + override fun onListen(args: Any?, sink: EventChannel.EventSink?) { + eventSink = sink + } + override fun onCancel(args: Any?) { + eventSink = null + } + }) + } + + // ── Method handler ─────────────────────────────────────────────── + private fun handleMethod(call: MethodCall, result: MethodChannel.Result) { + when (call.method) { + "startCapture" -> { + val rate = call.argument("sampleRate") ?: SAMPLE_RATE + val source = call.argument("source") ?: MediaRecorder.AudioSource.UNPROCESSED + startCapture(rate, source) + result.success("ok") + } + "stopCapture" -> { + stopCapture() + result.success("ok") + } + "startPlayback" -> { + val rate = call.argument("sampleRate") ?: SAMPLE_RATE + startPlayback(rate) + result.success("ok") + } + "stopPlayback" -> { + stopPlayback() + result.success("ok") + } + "writePlayback" -> { + val bytes = call.argument("samples") + if (bytes != null) writePlayback(bytes) + result.success("ok") + } + "setSpeakerMode" -> { + val enabled = call.argument("enabled") ?: true + setSpeakerMode(enabled) + result.success("ok") + } + "getAudioRouteInfo" -> { + result.success(getAudioRouteInfo()) + } + else -> result.notImplemented() + } + } + + // ── Capture ────────────────────────────────────────────────────── + + /** + * Start capturing audio from the microphone. + * + * Source priority (best for FSK demodulation): + * 1. UNPROCESSED (API 24+) — raw mic, no AEC/NS + * 2. VOICE_COMMUNICATION — VoIP-tuned processing + * 3. MIC — standard mic + * + * @param sampleRate Hz + * @param preferredSource MediaRecorder.AudioSource constant + */ + private fun startCapture(sampleRate: Int, preferredSource: Int) { + if (capturing.get()) { + Log.w(TAG, "startCapture called while already capturing") + return + } + + val sources = listOf( + preferredSource, + MediaRecorder.AudioSource.UNPROCESSED, + MediaRecorder.AudioSource.VOICE_COMMUNICATION, + MediaRecorder.AudioSource.MIC + ).distinct() + + val bufferBytes = RECORD_BUFFER_SAMPLES * 2 // Int16 → 2 bytes each + val format = AudioFormat.Builder() + .setSampleRate(sampleRate) + .setEncoding(AudioFormat.ENCODING_PCM_16BIT) + .setChannelMask(AudioFormat.CHANNEL_IN_MONO) + .build() + + var record: AudioRecord? = null + for (src in sources) { + try { + val rec = AudioRecord.Builder() + .setAudioSource(src) + .setAudioFormat(format) + .setBufferSizeInBytes(bufferBytes) + .build() + if (rec.state == AudioRecord.STATE_INITIALIZED) { + record = rec + Log.i(TAG, "AudioRecord opened with source=$src") + break + } else { + rec.release() + } + } catch (e: Exception) { + Log.w(TAG, "Source $src failed: ${e.message}") + } + } + + if (record == null) { + Log.e(TAG, "Could not open AudioRecord with any source") + return + } + + audioRecord = record + capturing.set(true) + + captureThread = Thread({ + android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO) + val chunk = ShortArray(CAPTURE_CHUNK_SAMPLES) + record.startRecording() + while (capturing.get()) { + val read = record.read(chunk, 0, chunk.size) + if (read > 0) { + // Convert ShortArray → ByteArray (Int16 LE) for Dart + val bytes = ByteArray(read * 2) + val buf = ByteBuffer.wrap(bytes).order(java.nio.ByteOrder.LITTLE_ENDIAN) + for (i in 0 until read) buf.putShort(chunk[i]) + // Dispatch to Dart via EventChannel on main thread + val payload = bytes.copyOf() + mainHandler.post { eventSink?.success(payload) } + } + } + record.stop() + record.release() + }, "AudioCapture") + captureThread!!.start() + } + + private fun stopCapture() { + capturing.set(false) + captureThread?.join(500) + captureThread = null + audioRecord = null + } + + // ── Playback ───────────────────────────────────────────────────── + + /** + * Start the AudioTrack in streaming mode. + * Dart pushes PCM chunks via writePlayback(). + */ + private fun startPlayback(sampleRate: Int) { + if (playing.get()) return + + val bufBytes = PLAYBACK_BUFFER_SAMPLES * 2 + val track = AudioTrack.Builder() + .setAudioAttributes( + AudioAttributes.Builder() + .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION) + .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH) + .build() + ) + .setAudioFormat( + AudioFormat.Builder() + .setSampleRate(sampleRate) + .setEncoding(AudioFormat.ENCODING_PCM_16BIT) + .setChannelMask(AudioFormat.CHANNEL_OUT_MONO) + .build() + ) + .setBufferSizeInBytes(bufBytes) + .setTransferMode(AudioTrack.MODE_STREAM) + .build() + + track.play() + audioTrack = track + playing.set(true) + Log.i(TAG, "AudioTrack started, sampleRate=$sampleRate") + } + + /** + * Write Int16 LE PCM bytes to the AudioTrack buffer. + * Called from Dart whenever the FSK modulator or LPC decoder produces output. + */ + private fun writePlayback(bytes: ByteArray) { + val track = audioTrack ?: return + if (!playing.get()) return + // Write non-blocking; discard if buffer full (transient) + track.write(bytes, 0, bytes.size, AudioTrack.WRITE_NON_BLOCKING) + } + + private fun stopPlayback() { + playing.set(false) + audioTrack?.stop() + audioTrack?.release() + audioTrack = null + } + + // ── Routing ────────────────────────────────────────────────────── + + /** + * Switch between speakerphone (loudspeaker mode) and earpiece. + * + * FSK acoustic coupling requires SPEAKER mode so the phone's bottom mic + * can pick up audio coming from the speaker. When receiving decoded voice, + * you may optionally switch to earpiece for privacy. + */ + private fun setSpeakerMode(enabled: Boolean) { + val am = appContext.getSystemService(Context.AUDIO_SERVICE) as AudioManager + am.mode = AudioManager.MODE_IN_COMMUNICATION + am.isSpeakerphoneOn = enabled + Log.i(TAG, "Speaker mode: $enabled") + } + + private fun getAudioRouteInfo(): Map { + val am = appContext.getSystemService(Context.AUDIO_SERVICE) as AudioManager + return mapOf( + "speakerOn" to am.isSpeakerphoneOn, + "mode" to am.mode, + "sampleRate" to SAMPLE_RATE, + "chunkSize" to CAPTURE_CHUNK_SAMPLES + ) + } +} diff --git a/call/android/app/src/main/kotlin/com/example/call/MainActivity.kt b/call/android/app/src/main/kotlin/com/example/call/MainActivity.kt new file mode 100644 index 0000000..d37f110 --- /dev/null +++ b/call/android/app/src/main/kotlin/com/example/call/MainActivity.kt @@ -0,0 +1,12 @@ +package com.example.call + +import io.flutter.embedding.android.FlutterActivity +import io.flutter.embedding.engine.FlutterEngine + +class MainActivity : FlutterActivity() { + override fun configureFlutterEngine(flutterEngine: FlutterEngine) { + super.configureFlutterEngine(flutterEngine) + // Register the AudioEngine method channel and event channel. + AudioEngine.register(this, flutterEngine.dartExecutor.binaryMessenger) + } +} diff --git a/call/android/app/src/main/res/drawable-v21/launch_background.xml b/call/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/call/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/call/android/app/src/main/res/drawable/launch_background.xml b/call/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/call/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/call/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/call/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..db77bb4 Binary files /dev/null and b/call/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/call/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/call/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..17987b7 Binary files /dev/null and b/call/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/call/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/call/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..09d4391 Binary files /dev/null and b/call/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/call/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/call/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..d5f1c8d Binary files /dev/null and b/call/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/call/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/call/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..4d6372e Binary files /dev/null and b/call/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/call/android/app/src/main/res/values-night/styles.xml b/call/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/call/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/call/android/app/src/main/res/values/styles.xml b/call/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/call/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/call/android/app/src/profile/AndroidManifest.xml b/call/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/call/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/call/android/build.gradle.kts b/call/android/build.gradle.kts new file mode 100644 index 0000000..dbee657 --- /dev/null +++ b/call/android/build.gradle.kts @@ -0,0 +1,24 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/call/android/gradle.properties b/call/android/gradle.properties new file mode 100644 index 0000000..fbee1d8 --- /dev/null +++ b/call/android/gradle.properties @@ -0,0 +1,2 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true diff --git a/call/android/gradle/wrapper/gradle-wrapper.properties b/call/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..e4ef43f --- /dev/null +++ b/call/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip diff --git a/call/android/settings.gradle.kts b/call/android/settings.gradle.kts new file mode 100644 index 0000000..ca7fe06 --- /dev/null +++ b/call/android/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.11.1" apply false + id("org.jetbrains.kotlin.android") version "2.2.20" apply false +} + +include(":app") diff --git a/call/ios/.gitignore b/call/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/call/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/call/ios/Flutter/AppFrameworkInfo.plist b/call/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..391a902 --- /dev/null +++ b/call/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + + diff --git a/call/ios/Flutter/Debug.xcconfig b/call/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/call/ios/Flutter/Debug.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/call/ios/Flutter/Release.xcconfig b/call/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..592ceee --- /dev/null +++ b/call/ios/Flutter/Release.xcconfig @@ -0,0 +1 @@ +#include "Generated.xcconfig" diff --git a/call/ios/Runner.xcodeproj/project.pbxproj b/call/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..4b44901 --- /dev/null +++ b/call/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,620 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.call; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.call.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.call.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.call.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.call; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.call; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/call/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/call/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/call/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/call/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/call/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/call/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/call/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/call/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/call/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/call/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/call/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..e3773d4 --- /dev/null +++ b/call/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/call/ios/Runner.xcworkspace/contents.xcworkspacedata b/call/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/call/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/call/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/call/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/call/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/call/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/call/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/call/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/call/ios/Runner/AppDelegate.swift b/call/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..c30b367 --- /dev/null +++ b/call/ios/Runner/AppDelegate.swift @@ -0,0 +1,16 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + } +} diff --git a/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..dc9ada4 Binary files /dev/null and b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..7353c41 Binary files /dev/null and b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..6ed2d93 Binary files /dev/null and b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..4cd7b00 Binary files /dev/null and b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..fe73094 Binary files /dev/null and b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..321773c Binary files /dev/null and b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..797d452 Binary files /dev/null and b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..502f463 Binary files /dev/null and b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..0ec3034 Binary files /dev/null and b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..e9f5fea Binary files /dev/null and b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..84ac32a Binary files /dev/null and b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..8953cba Binary files /dev/null and b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..0467bf1 Binary files /dev/null and b/call/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/call/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/call/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/call/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/call/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/call/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/call/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/call/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/call/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/call/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/call/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/call/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/call/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/call/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/call/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100644 index 0000000..89c2725 --- /dev/null +++ b/call/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/call/ios/Runner/Base.lproj/LaunchScreen.storyboard b/call/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/call/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/call/ios/Runner/Base.lproj/Main.storyboard b/call/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/call/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/call/ios/Runner/Info.plist b/call/ios/Runner/Info.plist new file mode 100644 index 0000000..d5359b7 --- /dev/null +++ b/call/ios/Runner/Info.plist @@ -0,0 +1,70 @@ + + + + + CADisableMinimumFrameDurationOnPhone + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Call + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + call + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/call/ios/Runner/Runner-Bridging-Header.h b/call/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/call/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/call/ios/Runner/SceneDelegate.swift b/call/ios/Runner/SceneDelegate.swift new file mode 100644 index 0000000..b9ce8ea --- /dev/null +++ b/call/ios/Runner/SceneDelegate.swift @@ -0,0 +1,6 @@ +import Flutter +import UIKit + +class SceneDelegate: FlutterSceneDelegate { + +} diff --git a/call/ios/RunnerTests/RunnerTests.swift b/call/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/call/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/call/lib/core/codec/lpc_codec.dart b/call/lib/core/codec/lpc_codec.dart new file mode 100644 index 0000000..3f68da0 --- /dev/null +++ b/call/lib/core/codec/lpc_codec.dart @@ -0,0 +1,382 @@ +import 'dart:math' as math; +import 'dart:typed_data'; +import '../../utils/audio_math.dart'; +import '../../utils/constants.dart'; + +/// Simplified LPC-10 voice codec operating at ~360 bps. +/// +/// ── Super-frame structure (200 ms = 10 × 20 ms sub-frames) ───────────── +/// +/// Bits per super-frame (72 bits = 9 bytes): +/// 10 PARCOR reflection coefficients (k_1..k_10): 30 bits (3 bits each) +/// 10 sub-frame gain values (log energy): 20 bits (2 bits each) +/// 10 voiced/unvoiced flags: 10 bits (1 bit each) +/// 1 pitch period (shared across voiced sub-frames): 6 bits (0-63 → 20-83 samples) +/// 1 pitch-valid flag: 1 bit +/// padding to byte boundary: 5 bits +/// ──────────────────────────────────────────────────────── +/// Total: 72 bits = 9 bytes +/// +/// Voice quality is similar to HF digital radio (intelligible, robotic). +/// All analysis is done at 8 kHz with a 10th-order LPC predictor. +class LpcCodec { + // ── Configuration ───────────────────────────────────────────────── + static const int _p = C.lpcOrder; // 10 + static const int _subN = C.lpcSubframeSamples; // 160 samples = 20 ms + static const int _numSubs = C.lpcSubframesPerSuper; // 10 + static const int _superN = _subN * _numSubs; // 1600 samples = 200 ms + static const double _alpha = C.preEmphasis; // 0.97 + + // Encoder persistent state + double _encPrevSample = 0.0; + + // Decoder persistent state + final _synState = Float64List(_p); // IIR filter memory (synthesis filter) + double _decPrevOut = 0.0; // de-emphasis state + + // ── Public API ───────────────────────────────────────────────────── + + /// Encode [pcm] (exactly 1600 Int16 LE samples) into 9-byte bitstream. + Uint8List encode(Uint8List pcmBytes) { + assert(pcmBytes.length == _superN * 2, + 'LPC encode: expected ${_superN * 2} bytes, got ${pcmBytes.length}'); + + // Convert Int16 PCM → Float64 normalised. + final signal = AudioMath.int16BytesToFloat(pcmBytes); + + // Pre-emphasis filter (updates encoder state). + _applyPreEmphasis(signal); + + // ── LPC analysis over the whole super-frame ──────────────────── + // Window the super-frame and compute autocorrelation. + final windowed = Float64List(_superN); + final win = AudioMath.hammingWindow(_superN); + for (int i = 0; i < _superN; i++) { + windowed[i] = signal[i] * win[i]; + } + final r = AudioMath.autocorrelation(windowed, _p); + final kc = _levinsonDurbin(r); // reflection coefficients [-1,1] + final a = _parcorToLpc(kc); // LP filter coefficients + + // ── Pitch detection on the full super-frame residual ────────── + final residual = _computeResidual(signal, a); + final pitch = AudioMath.amdfPitch(residual, C.pitchMinSamples, C.pitchMaxSamples); + final hasVoice = pitch > 0; + + // ── Per-sub-frame gain and voiced/unvoiced ───────────────────── + final gains = List.filled(_numSubs, 0); + final vuv = List.filled(_numSubs, false); + + for (int s = 0; s < _numSubs; s++) { + final start = s * _subN; + final sub = Float64List.sublistView(signal, start, start + _subN); + final e = AudioMath.energy(sub); + gains[s] = _quantiseGain(e); + // Voiced if energy is above floor AND overall pitch was detected. + vuv[s] = hasVoice && e > 1e-4; + } + + // ── Quantise PARCOR coefficients (3 bits each = 8 levels) ──── + final kQuant = List.filled(_p, 0); + for (int i = 0; i < _p; i++) { + kQuant[i] = _quantiseParcor(kc[i]); + } + + // ── Pack into 72-bit bitstream ───────────────────────────────── + return _pack(kQuant, gains, vuv, hasVoice ? pitch : 0, hasVoice); + } + + /// Decode a 9-byte bitstream into PCM (returns 3200 bytes = 1600 Int16 LE). + Uint8List decode(Uint8List bits) { + assert(bits.length == 9, 'LPC decode: expected 9 bytes, got ${bits.length}'); + + final unpacked = _unpack(bits); + final kc = unpacked.$1; // List PARCOR coefficients + final gains = unpacked.$2; + final vuv = unpacked.$3; + final pitch = unpacked.$4; + final hasVoice = unpacked.$5; + + // Convert PARCOR back to LP filter coefficients. + final a = _parcorToLpc(kc); + + // Synthesise each sub-frame. + final output = Float64List(_superN); + + for (int s = 0; s < _numSubs; s++) { + final gainLinear = _dequantiseGain(gains[s]); + final voiced = vuv[s] && hasVoice; + final excitation = _generateExcitation(_subN, voiced, pitch, gainLinear); + + // IIR synthesis filter: y[n] = e[n] + Σ(a[k]·y[n-k]) + for (int i = 0; i < _subN; i++) { + double acc = excitation[i]; + for (int k = 0; k < _p; k++) { + final idx = i - k - 1; + acc += a[k] * (idx >= 0 ? output[s * _subN + idx] : _synState[k]); + } + output[s * _subN + i] = acc; + } + + // Update synthesis state (last P samples of this sub-frame). + for (int k = 0; k < _p; k++) { + final idx = _subN - 1 - k; + _synState[k] = idx >= 0 ? output[s * _subN + idx] : 0.0; + } + } + + // De-emphasis. + _applyDeEmphasis(output); + + // Soft-clip to prevent overflow. + for (int i = 0; i < _superN; i++) { + output[i] = output[i].clamp(-1.0, 1.0); + } + + return AudioMath.floatToInt16Bytes(output); + } + + // ── Pre/de-emphasis ──────────────────────────────────────────────── + + void _applyPreEmphasis(Float64List s) { + double prev = _encPrevSample; + for (int i = 0; i < s.length; i++) { + final cur = s[i]; + s[i] = cur - _alpha * prev; + prev = cur; + } + _encPrevSample = s[s.length - 1]; + } + + void _applyDeEmphasis(Float64List s) { + double prev = _decPrevOut; + for (int i = 0; i < s.length; i++) { + final cur = s[i] + _alpha * prev; + s[i] = cur; + prev = cur; + } + _decPrevOut = s[s.length - 1]; + } + + // ── Levinson-Durbin algorithm ────────────────────────────────────── + // + // Given autocorrelation r[0..p], returns p reflection (PARCOR) coefficients. + // The algorithm computes the LP predictor in O(p^2). + static List _levinsonDurbin(Float64List r) { + if (r[0] < 1e-10) return List.filled(_p, 0.0); + + final a = List.filled(_p + 1, 0.0); + final k = List.filled(_p, 0.0); + double e = r[0]; + + for (int i = 1; i <= _p; i++) { + // Reflection coefficient k_i = -(r[i] + Σ a[j]·r[i-j]) / e + double lambda = r[i]; + for (int j = 1; j < i; j++) { + lambda += a[j] * r[i - j]; + } + k[i - 1] = -lambda / e; + + // Clamp to (-1, 1) for stability. + k[i - 1] = k[i - 1].clamp(-0.999, 0.999); + + // Update predictor: a_new[j] = a[j] + k_i · a[i-j] + final newA = List.from(a); + newA[i] = k[i - 1]; + for (int j = 1; j < i; j++) { + newA[j] = a[j] + k[i - 1] * a[i - j]; + } + for (int j = 0; j <= i; j++) { + a[j] = newA[j]; + } + + e *= (1.0 - k[i - 1] * k[i - 1]); + if (e < 1e-15) break; + } + + return k; + } + + // ── PARCOR → LP coefficients ─────────────────────────────────────── + // + // Convert reflection coefficients back to the direct-form LP coefficients + // using the step-up recursion (inverse Levinson). + static List _parcorToLpc(List k) { + final a = List.filled(_p + 1, 0.0); + a[0] = 1.0; + for (int i = 0; i < _p; i++) { + a[i + 1] = k[i]; + for (int j = 1; j <= i; j++) { + final tmp = a[j] + k[i] * a[i + 1 - j]; + a[j] = tmp; + } + } + // Return a[1..p] (skip a[0]=1) + return a.sublist(1); + } + + // ── Residual computation ─────────────────────────────────────────── + // + // Apply the analysis (inverse) filter: e[n] = s[n] + Σ a[k]·s[n-k] + static Float64List _computeResidual(Float64List s, List a) { + final res = Float64List(s.length); + for (int n = 0; n < s.length; n++) { + double acc = s[n]; + for (int k = 0; k < _p; k++) { + if (n - k - 1 >= 0) { + acc += a[k] * s[n - k - 1]; + } + } + res[n] = acc; + } + return res; + } + + // ── Gain quantisation (2 bits = 4 levels) ───────────────────────── + // + // Map log10(energy) to integers 0-3. + static int _quantiseGain(double energy) { + if (energy < 1e-6) return 0; + final logE = math.log(energy + 1e-10) / math.ln10; + // Typical speech energy in float normalised to [-1,1]: logE ∈ [-6, 0]. + // Remap to [0,3]. + final mapped = ((logE + 6.0) / 6.0 * 3.0).round().clamp(0, 3); + return mapped; + } + + static double _dequantiseGain(int q) { + // Inverse of _quantiseGain. + final logE = q / 3.0 * 6.0 - 6.0; + return math.pow(10.0, logE).toDouble() * 0.1; // scale for excitation + } + + // ── PARCOR quantisation (3 bits = 8 levels, range [-1,1]) ───────── + static int _quantiseParcor(double k) { + // Map [-1, 1] → [0, 7]. + final idx = ((k + 1.0) / 2.0 * 7.0).round().clamp(0, 7); + return idx; + } + + static double _dequantiseParcor(int q) { + return (q / 7.0) * 2.0 - 1.0; + } + + // ── Excitation generation ────────────────────────────────────────── + // + // Voiced: periodic impulse train at pitch period with gain amplitude. + // Unvoiced: white Gaussian noise with gain amplitude. + static Float64List _generateExcitation( + int n, bool voiced, int pitch, double gain) { + if (!voiced || pitch <= 0) { + return AudioMath.whiteNoise(n, gain.clamp(0.0, 1.0)); + } + final ex = Float64List(n); + // Impulse at each pitch period boundary. + for (int i = 0; i < n; i += pitch) { + if (i < n) ex[i] = gain; + } + return ex; + } + + // ── Bit packing ──────────────────────────────────────────────────── + // + // Layout (72 bits, MSB first): + // Bits 0-29 : 10 × PARCOR (3 bits each) + // Bits 30-49 : 10 × gain (2 bits each) + // Bits 50-59 : 10 × V/UV (1 bit each) + // Bits 60-65 : pitch period (6 bits, value = pitch-20, range 0-63 → 20-83) + // Bit 66 : pitch-valid flag + // Bits 67-71 : padding (5 zeros) + + static Uint8List _pack(List kq, List gains, List vuv, + int pitch, bool hasVoice) { + final bits = List.filled(72, 0); + int pos = 0; + + // PARCOR coefficients (3 bits each). + for (int i = 0; i < _p; i++) { + bits[pos++] = (kq[i] >> 2) & 1; + bits[pos++] = (kq[i] >> 1) & 1; + bits[pos++] = kq[i] & 1; + } + + // Gains (2 bits each). + for (int i = 0; i < _numSubs; i++) { + bits[pos++] = (gains[i] >> 1) & 1; + bits[pos++] = gains[i] & 1; + } + + // V/UV flags. + for (int i = 0; i < _numSubs; i++) { + bits[pos++] = vuv[i] ? 1 : 0; + } + + // Pitch (6 bits, offset by 20). + final pitchEnc = hasVoice ? (pitch - 20).clamp(0, 63) : 0; + for (int b = 5; b >= 0; b--) { + bits[pos++] = (pitchEnc >> b) & 1; + } + + // Pitch-valid flag. + bits[pos++] = hasVoice ? 1 : 0; + + // Remaining bits (padding) are already 0. + + // Pack 72 bits into 9 bytes. + final out = Uint8List(9); + for (int i = 0; i < 9; i++) { + int byte = 0; + for (int b = 0; b < 8; b++) { + byte = (byte << 1) | bits[i * 8 + b]; + } + out[i] = byte; + } + return out; + } + + static (List, List, List, int, bool) _unpack( + Uint8List bytes) { + // Unpack 9 bytes into 72 bits. + final bits = List.filled(72, 0); + for (int i = 0; i < 9; i++) { + for (int b = 0; b < 8; b++) { + bits[i * 8 + b] = (bytes[i] >> (7 - b)) & 1; + } + } + + int pos = 0; + + // PARCOR. + final kq = List.filled(_p, 0); + for (int i = 0; i < _p; i++) { + kq[i] = (bits[pos] << 2) | (bits[pos + 1] << 1) | bits[pos + 2]; + pos += 3; + } + final kc = kq.map(_dequantiseParcor).toList(); + + // Gains. + final gains = List.filled(_numSubs, 0); + for (int i = 0; i < _numSubs; i++) { + gains[i] = (bits[pos] << 1) | bits[pos + 1]; + pos += 2; + } + + // V/UV. + final vuv = List.filled(_numSubs, false); + for (int i = 0; i < _numSubs; i++) { + vuv[i] = bits[pos++] == 1; + } + + // Pitch. + int pitchEnc = 0; + for (int b = 5; b >= 0; b--) { + pitchEnc |= bits[pos++] << b; + } + final pitch = pitchEnc + 20; + + // Pitch-valid. + final hasVoice = bits[pos] == 1; + + return (kc, gains, vuv, pitch, hasVoice); + } +} diff --git a/call/lib/core/crypto/aes_cipher.dart b/call/lib/core/crypto/aes_cipher.dart new file mode 100644 index 0000000..8acb77d --- /dev/null +++ b/call/lib/core/crypto/aes_cipher.dart @@ -0,0 +1,43 @@ +import 'dart:typed_data'; +import 'package:pointycastle/export.dart'; + +/// AES-256-CTR symmetric cipher wrapper. +/// +/// AES-CTR is a stream cipher: encryption and decryption use the same +/// operation (XOR with key-stream), and there is no padding. The output +/// length always equals the input length, making it ideal for our fixed-size +/// 11-byte voice payload. +/// +/// Security notes: +/// • Never reuse the same (key, nonce) pair. +/// • Nonce uniqueness is guaranteed by including the packet sequence +/// number in the nonce (see [KeyManager.buildNonce]). +/// • The key is zeroed from memory when the session ends. +abstract final class AesCipher { + // ── Core cipher op (encrypt = decrypt for CTR mode) ─────────────── + + /// Encrypt or decrypt [data] with [key] (32 bytes) and [nonce] (16 bytes). + /// + /// AES-256-CTR: keystream = AES_k(nonce ∥ counter), output = data ⊕ keystream. + /// [forEncryption] = true → encrypt; false → decrypt (same operation in CTR). + static Uint8List _ctr(Uint8List data, Uint8List key, Uint8List nonce, + {required bool forEncryption}) { + assert(key.length == 32, 'AES-256 requires a 32-byte key'); + assert(nonce.length == 16, 'CTR nonce must be 16 bytes (one AES block)'); + + final cipher = StreamCipher('AES/CTR') + ..init(forEncryption, ParametersWithIV(KeyParameter(key), nonce)); + + final out = Uint8List(data.length); + cipher.processBytes(data, 0, data.length, out, 0); + return out; + } + + /// Encrypt [plaintext] → ciphertext (same length as input). + static Uint8List encrypt(Uint8List plaintext, Uint8List key, Uint8List nonce) => + _ctr(plaintext, key, nonce, forEncryption: true); + + /// Decrypt [ciphertext] → plaintext (same length as input). + static Uint8List decrypt(Uint8List ciphertext, Uint8List key, Uint8List nonce) => + _ctr(ciphertext, key, nonce, forEncryption: false); +} diff --git a/call/lib/core/crypto/key_manager.dart b/call/lib/core/crypto/key_manager.dart new file mode 100644 index 0000000..4053920 --- /dev/null +++ b/call/lib/core/crypto/key_manager.dart @@ -0,0 +1,121 @@ +import 'dart:convert'; +import 'dart:typed_data'; +import 'package:pointycastle/export.dart'; + +/// Derives and stores the 256-bit session key from a user-supplied passphrase. +/// +/// Key derivation: PBKDF2-HMAC-SHA256 with a random salt. +/// The salt is kept in memory for the session; both peers must use the SAME +/// passphrase and DIFFERENT salts are handled by transmitting the salt +/// in the handshake packet before the session starts. +class KeyManager { + static const int _keyLen = 32; // AES-256 + static const int _saltLen = 16; + static const int _iters = 100000; + + Uint8List? _key; + Uint8List? _salt; + + /// True once [deriveKey] has been called successfully. + bool get hasKey => _key != null; + + /// The derived 32-byte key (throws if not yet derived). + Uint8List get key { + final k = _key; + if (k == null) throw StateError('Key not derived yet'); + return k; + } + + /// The 16-byte salt used during derivation (for sharing with the peer). + Uint8List get salt { + final s = _salt; + if (s == null) throw StateError('Salt not available'); + return s; + } + + // ── Derivation ───────────────────────────────────────────────────── + + /// Derive a 256-bit key from [passphrase] using PBKDF2-HMAC-SHA256. + /// + /// If [salt] is provided (received from the peer during handshake), + /// it is used directly. Otherwise a fresh random salt is generated. + /// + /// Throws [ArgumentError] if the passphrase is empty. + void deriveKey(String passphrase, {Uint8List? salt}) { + if (passphrase.isEmpty) { + throw ArgumentError('Passphrase must not be empty'); + } + + // Use provided salt or generate one. + final usedSalt = salt ?? _generateSalt(); + _salt = usedSalt; + + final passwordBytes = Uint8List.fromList(utf8.encode(passphrase)); + + // PBKDF2-HMAC-SHA256 via PointyCastle. + final pbkdf2 = PBKDF2KeyDerivator(HMac(SHA256Digest(), 64)) + ..init(Pbkdf2Parameters(usedSalt, _iters, _keyLen)); + + _key = pbkdf2.process(passwordBytes); + } + + /// Load a raw 32-byte key directly (for testing or pre-shared key import). + void loadRawKey(Uint8List rawKey) { + if (rawKey.length != _keyLen) { + throw ArgumentError('Raw key must be $_keyLen bytes'); + } + _key = Uint8List.fromList(rawKey); + _salt = Uint8List(_saltLen); // zero salt when using raw key + } + + /// Clear the key from memory (call on session teardown). + void clear() { + if (_key != null) { + _key!.fillRange(0, _key!.length, 0); + _key = null; + } + _salt = null; + } + + // ── Nonce construction ───────────────────────────────────────────── + + /// Build a 16-byte AES-CTR nonce for a given packet sequence number. + /// + /// Layout: [salt[0..7] ∥ sessionId[0..3] ∥ seqHigh ∥ seqLow ∥ 00 00 00 00] + /// (128-bit nonce; the counter part at the end starts at 0 per-block.) + /// + /// Using the salt's first 8 bytes + session ID + seq ensures that + /// each packet has a unique nonce without transmitting the full nonce. + Uint8List buildNonce(Uint8List sessionId, int seq) { + final nonce = Uint8List(16); + // First 8 bytes from salt (or zeros if salt unavailable). + final s = _salt; + if (s != null) { + for (int i = 0; i < 8 && i < s.length; i++) { nonce[i] = s[i]; } + } + // Next 4 bytes: session ID. + for (int i = 0; i < 4 && i < sessionId.length; i++) { + nonce[8 + i] = sessionId[i]; + } + // Last 4 bytes: packet sequence number (big-endian). + nonce[12] = (seq >> 24) & 0xFF; + nonce[13] = (seq >> 16) & 0xFF; + nonce[14] = (seq >> 8) & 0xFF; + nonce[15] = seq & 0xFF; + return nonce; + } + + // ── Private helpers ──────────────────────────────────────────────── + + static Uint8List _generateSalt() { + final rng = FortunaRandom(); + // Seed Fortuna with timestamp + hash-spread bytes. + final seed = Uint8List(32); + final ts = DateTime.now().microsecondsSinceEpoch; + for (int i = 0; i < 8; i++) { + seed[i] = (ts >> (i * 8)) & 0xFF; + } + rng.seed(KeyParameter(seed)); + return rng.nextBytes(_saltLen); + } +} diff --git a/call/lib/core/fec/reed_solomon.dart b/call/lib/core/fec/reed_solomon.dart new file mode 100644 index 0000000..2e65478 --- /dev/null +++ b/call/lib/core/fec/reed_solomon.dart @@ -0,0 +1,294 @@ +import 'dart:typed_data'; + +/// Reed-Solomon codec RS(15,11) over GF(16). +/// +/// GF(16) = GF(2^4) with primitive polynomial p(x) = x^4 + x + 1 (0x13). +/// Primitive element α has order 15 (α^15 = 1). +/// +/// Parameters: +/// n = 15 (codeword length in nibbles) +/// k = 11 (data symbols per codeword) +/// t = 2 (corrects up to 2 nibble-errors per codeword) +/// +/// Wire mapping: +/// 11 data nibbles + 4 parity nibbles = 15 nibbles = 7.5 bytes. +/// To keep byte alignment the codec works on full-byte streams: +/// encode(Uint8List data) where data.length must be a multiple of 5.5 B +/// Callers pack/unpack nibbles via [packNibbles] / [unpackNibbles]. +/// +/// Usage (encode 11-byte block → 15-byte codeword): +/// final cw = ReedSolomon.encodeBlock(data11Bytes); // Uint8List(15) +/// final ok = ReedSolomon.decodeBlock(cw); // corrects in-place +abstract final class ReedSolomon { + // ── GF(16) tables ───────────────────────────────────────────────── + // + // Computed offline for p(x) = x^4 + x + 1 = 0x13. + // α^0 = 1 α^1 = 2 α^2 = 4 α^3 = 8 + // α^4 = 3 α^5 = 6 α^6 = 12 α^7 = 11 + // α^8 = 5 α^9 = 10 α^10 = 7 α^11 = 14 + // α^12 = 15 α^13 = 13 α^14 = 9 α^15 = 1 (wrap) + + static const List _exp = [ + 1, 2, 4, 8, 3, 6, 12, 11, 5, 10, 7, 14, 15, 13, 9, + // duplicate for modular index without % 15 + 1, 2, 4, 8, 3, 6, 12, 11, 5, 10, 7, 14, 15, 13, 9, + ]; + + static const List _log = [ + // index 0 → undefined (−∞); we store 0 but never use it for non-zero + 0, // log[0] = -∞ (sentinel) + 0, // log[1] = 0 (α^0) + 1, // log[2] = 1 + 4, // log[3] = 4 + 2, // log[4] = 2 + 8, // log[5] = 8 + 5, // log[6] = 5 + 10, // log[7] = 10 + 3, // log[8] = 3 + 14, // log[9] = 14 + 9, // log[10] = 9 + 7, // log[11] = 7 + 6, // log[12] = 6 + 13, // log[13] = 13 + 11, // log[14] = 11 + 12, // log[15] = 12 + ]; + + // Generator polynomial g(x) = (x-α)(x-α^2)(x-α^3)(x-α^4) + // = x^4 + 13x^3 + 12x^2 + 8x + 7 (coefficients in GF(16)) + // g[0] is the constant term, g[4] is the leading coefficient (=1). + static const List _gen = [7, 8, 12, 13, 1]; + + static const int _n = 15; + static const int _k = 11; + static const int _t = 2; + + // ── GF(16) arithmetic ───────────────────────────────────────────── + + // Addition = XOR in GF(2^m). + static int _add(int a, int b) => a ^ b; + + // Multiplication using log/exp lookup tables. + static int _mul(int a, int b) { + if (a == 0 || b == 0) return 0; + return _exp[(_log[a] + _log[b]) % 15]; + } + + // Division a / b. + static int _div(int a, int b) { + if (a == 0) return 0; + assert(b != 0, 'GF division by zero'); + return _exp[(_log[a] - _log[b] + 15) % 15]; + } + + // Power α^e. + static int _pow(int e) => _exp[e % 15]; + + // ── Nibble pack / unpack ────────────────────────────────────────── + + /// Pack n pairs of nibbles into bytes. nibbles.length must be even. + static Uint8List packNibbles(List nibbles) { + assert(nibbles.length.isEven, 'nibbles must have even length'); + final out = Uint8List(nibbles.length >> 1); + for (int i = 0; i < out.length; i++) { + out[i] = ((nibbles[i * 2] & 0xF) << 4) | (nibbles[i * 2 + 1] & 0xF); + } + return out; + } + + /// Unpack bytes into a List of nibbles (high nibble first). + static List unpackNibbles(List bytes) { + final out = []; + for (final b in bytes) { + out.add((b >> 4) & 0xF); + out.add(b & 0xF); + } + return out; + } + + // ── Encoder ─────────────────────────────────────────────────────── + + /// Encode [data] (11-nibble list) into a 15-nibble RS codeword. + /// + /// The encoding is systematic: the first 11 nibbles of the codeword + /// are the data, the last 4 are parity computed via polynomial division. + static List _encodeNibbles(List data) { + assert(data.length == _k, 'RS encode: input must be $_k nibbles'); + + // Work buffer: data shifted left by t positions. + final r = List.filled(_k + _t, 0); + for (int i = 0; i < _k; i++) { + r[i] = data[i]; + } + // Polynomial long division: r(x) = x^(n-k)·m(x) mod g(x) + for (int i = 0; i < _k; i++) { + final coeff = r[i]; + if (coeff != 0) { + for (int j = 1; j <= _t * 2; j++) { + r[i + j] = _add(r[i + j], _mul(_gen[_t * 2 - j], coeff)); + } + } + } + + // Build codeword: data || parity (last 4 elements of r) + final cw = List.from(data); + for (int i = _k; i < _n; i++) { + cw.add(r[i]); + } + return cw; + } + + // ── Public API: byte-level encode (11 bytes → 15 bytes) ─────────── + + /// Encode an 11-byte data block into a 15-byte RS codeword. + /// + /// The 11 bytes are treated as 22 GF(16) nibbles split into two + /// 11-nibble RS codewords. Output is 30 nibbles = 15 bytes. + /// + /// [data] must have exactly 11 bytes. Returns Uint8List(15). + static Uint8List encodeBlock(Uint8List data) { + assert(data.length == 11, 'encodeBlock: need 11 bytes, got ${data.length}'); + final nibs = unpackNibbles(data); // 22 nibbles + // Codeword 0: nibbles [0..10] + final cw0 = _encodeNibbles(nibs.sublist(0, 11)); + // Codeword 1: nibbles [11..21] + final cw1 = _encodeNibbles(nibs.sublist(11, 22)); + // Merge 30 nibbles back to 15 bytes + return packNibbles([...cw0, ...cw1]); + } + + // ── Decoder (Berlekamp-Massey + Chien + Forney) ─────────────────── + + /// Decode and correct a 15-nibble codeword (in-place list). + /// Returns true if no uncorrectable error was detected. + static bool _decodeNibbles(List cw) { + assert(cw.length == _n, 'RS decode: codeword must be $_n nibbles'); + + // ── Step 1: compute syndromes S_i = c(α^i) for i=1..2t ───────── + final s = List.filled(2 * _t, 0); + for (int i = 0; i < 2 * _t; i++) { + int ev = 0; + for (int j = 0; j < _n; j++) { + ev = _add(_mul(ev, _pow(i + 1)), cw[j]); + } + s[i] = ev; + } + + // All-zero syndromes → no errors. + if (s.every((v) => v == 0)) return true; + + // ── Step 2: Berlekamp-Massey error-locator polynomial Λ(x) ────── + var sigma = List.filled(_t + 1, 0); + sigma[0] = 1; + var prev = List.filled(_t + 1, 0); + prev[0] = 1; + int lfsr = 0, d = 1; + + for (int n = 0; n < 2 * _t; n++) { + // Discrepancy Δ = S[n] + Λ_1·S[n-1] + … + Λ_L·S[n-L] + int delta = s[n]; + for (int i = 1; i <= lfsr; i++) { + if (n - i >= 0) delta = _add(delta, _mul(sigma[i], s[n - i])); + } + + if (delta == 0) { + d++; + } else { + final temp = List.from(sigma); + final scale = _div(delta, _exp[0]); // delta / 1 = delta + // sigma(x) -= (delta / Δ_prev) · x^d · prev(x) + for (int i = d; i <= _t + d && i <= _t; i++) { + if (i - d < prev.length) { + sigma[i] = _add(sigma[i], _mul(scale, prev[i - d])); + } + } + if (2 * lfsr <= n) { + lfsr = n + 1 - lfsr; + prev = temp; + d = 1; + } else { + d++; + } + } + } + + // ── Step 3: Chien search — find roots of Λ(x) ────────────────── + final errorPositions = []; + for (int i = 0; i < _n; i++) { + // Evaluate Λ(α^(-i)) = Λ(α^(15-i)) + int ev = 0; + for (int j = sigma.length - 1; j >= 0; j--) { + ev = _add(_mul(ev, _pow((15 - i) % 15)), sigma[j]); + } + if (ev == 0) errorPositions.add(i); + } + + if (errorPositions.length > _t) return false; // uncorrectable + + // ── Step 4: Forney algorithm — compute error magnitudes ───────── + for (final pos in errorPositions) { + // Evaluate error magnitude using Forney formula. + // For t≤2 we use the direct closed-form when |errors|≤2. + // Omega(x) = S(x)·Λ(x) mod x^(2t) + final omega = List.filled(2 * _t, 0); + for (int i = 0; i < 2 * _t; i++) { + for (int j = 0; j <= i && j < sigma.length; j++) { + if (i - j < s.length) { + omega[i] = _add(omega[i], _mul(sigma[j], s[i - j])); + } + } + } + // Λ'(x) formal derivative (odd powers survive in GF(2)) + // For binary GF, the derivative has only odd-indexed terms. + int sigmaDerivAtXi = 0; + for (int j = 1; j < sigma.length; j += 2) { + sigmaDerivAtXi = _add(sigmaDerivAtXi, + _mul(sigma[j], _pow(j * (15 - pos) % 15))); + } + if (sigmaDerivAtXi == 0) return false; + + // Evaluate Omega at α^(-pos) + int omegaVal = 0; + for (int i = omega.length - 1; i >= 0; i--) { + omegaVal = _add(_mul(omegaVal, _pow((15 - pos) % 15)), omega[i]); + } + + // Error value = -X^(-1) · Omega(X^(-1)) / Λ'(X^(-1)) + // In GF(2^m): -a = a, so e = _mul(inv(α^pos), omegaVal) / sigmaDerivAtXi + final xi = _pow(pos); // α^pos + final e = _div(_mul(_div(1, xi), omegaVal), sigmaDerivAtXi); + + cw[pos] = _add(cw[pos], e); + } + + return true; + } + + /// Decode and error-correct a 15-byte RS block in-place. + /// + /// Returns true if the block is valid (or was corrected successfully). + /// Returns false if errors exceeded the correction capacity. + static bool decodeBlock(Uint8List block) { + assert(block.length == 15, 'decodeBlock: need 15 bytes, got ${block.length}'); + final nibs = unpackNibbles(block); // 30 nibbles + final cw0 = nibs.sublist(0, 15); + final cw1 = nibs.sublist(15, 30); + final ok0 = _decodeNibbles(cw0); + final ok1 = _decodeNibbles(cw1); + if (!ok0 || !ok1) return false; + // Write corrected nibbles back to byte array. + final merged = [...cw0, ...cw1]; + final packed = packNibbles(merged); + for (int i = 0; i < 15; i++) { block[i] = packed[i]; } + return true; + } + + /// Extract just the 11 data bytes from a (possibly corrected) 15-byte block. + static Uint8List extractData(Uint8List block) { + assert(block.length == 15); + final nibs = unpackNibbles(block); + // Data nibbles: [0..10] from cw0 and [15..25] from cw1 → merge + final dataNibs = [...nibs.sublist(0, 11), ...nibs.sublist(15, 26)]; + return packNibbles(dataNibs); // 22 nibbles → 11 bytes + } +} diff --git a/call/lib/core/framing/deframer.dart b/call/lib/core/framing/deframer.dart new file mode 100644 index 0000000..1db580b --- /dev/null +++ b/call/lib/core/framing/deframer.dart @@ -0,0 +1,125 @@ +import 'dart:typed_data'; +import '../crypto/aes_cipher.dart'; +import '../crypto/key_manager.dart'; +import '../fec/reed_solomon.dart'; +import '../modem/fsk_demodulator.dart'; +import 'packet.dart'; +import '../../utils/audio_math.dart'; +import '../../utils/constants.dart'; + +/// Receive pipeline: FSK audio → demodulate → RS FEC → decrypt → packet. +/// +/// Feed audio chunks from the microphone via [pushAudio]. Decoded voice +/// super-frames (9-byte LPC payloads) are queued in [voiceQueue]. +class Deframer { + final KeyManager _keys; + final Uint8List _sessionId; + final FskDemodulator _demod = FskDemodulator(); + + // Decoded LPC payloads waiting to be synthesised. + final List voiceQueue = []; + + // Stats for UI display. + int rxPackets = 0; + int rxErrors = 0; + int rxCorrected = 0; + + Deframer(this._keys, this._sessionId); + + // ── Public API ───────────────────────────────────────────────────── + + /// Push a chunk of Float64 audio samples from the microphone. + /// + /// Internally demodulates FSK, assembles wire frames, applies FEC, + /// decrypts, and enqueues decoded voice payloads into [voiceQueue]. + void pushAudio(Float64List samples) { + final rawFrames = _demod.pushSamples(samples); + for (final raw in rawFrames) { + _processWireFrame(raw); + } + } + + /// Push raw Int16 LE PCM bytes (as received from AudioRecord). + void pushPcmBytes(Uint8List pcmBytes) { + pushAudio(AudioMath.int16BytesToFloat(pcmBytes)); + } + + void reset() { + _demod.reset(); + voiceQueue.clear(); + rxPackets = 0; + rxErrors = 0; + rxCorrected = 0; + } + + // ── Private pipeline ─────────────────────────────────────────────── + + /// Process one wire frame (22 bytes) through FEC → CRC → decrypt → queue. + void _processWireFrame(Uint8List wire) { + if (wire.length < 22) { + rxErrors++; + return; + } + + // ── Wire layout: [SYNC:2][SEQ:2][TYPE:1][RS_PAYLOAD:15][CRC:2] ── + final seq = (wire[2] << 8) | wire[3]; + final type = wire[4]; + + // Extract the 15-byte RS-encoded block. + final rsBlock = Uint8List.fromList(wire.sublist(5, 20)); + + // CRC check over bytes [2..19]. + final expectedCrc = AudioMath.crc16(wire.sublist(2, 20)); + final wireCrc = (wire[20] << 8) | wire[21]; + if (expectedCrc != wireCrc) { + rxErrors++; + return; // frame corrupted beyond CRC recovery + } + + // ── RS(15,11) FEC decode (corrects up to 2 nibble errors) ──────── + final rsOk = ReedSolomon.decodeBlock(rsBlock); + if (!rsOk) { + rxErrors++; + return; + } + // Detect whether RS actually corrected any bytes (compare before/after). + bool wasCorrected = false; + for (int i = 0; i < rsBlock.length; i++) { + if (rsBlock[i] != wire[5 + i]) { wasCorrected = true; break; } + } + if (wasCorrected) rxCorrected++; + + // Extract the 11-byte data payload. + final encrypted = ReedSolomon.extractData(rsBlock); + + // ── AES-256-CTR decrypt ─────────────────────────────────────────── + final nonce = _keys.buildNonce(_sessionId, seq); + final plaintext = AesCipher.decrypt(encrypted, _keys.key, nonce); + + // ── Parse inner packet structure ────────────────────────────────── + // plaintext layout: [lpc(9)][seq_low(1)][type_tag(1)] + // Validate inner type tag matches outer type. + final innerType = plaintext[10]; + if (innerType != type && type == C.pkTypeVoice) { + rxErrors++; + return; + } + + rxPackets++; + + // Build a Packet for higher-level handlers. + final pkt = Packet( + seq: seq, + type: type, + payload: plaintext, + valid: true, + ); + + if (pkt.isVoice) { + // First 9 bytes are the LPC super-frame. + voiceQueue.add(Uint8List.fromList(plaintext.sublist(0, 9))); + } + // Control packets (handshake, ping) are ignored here; + // higher layers can subscribe via [SecureChannel]. + } +} diff --git a/call/lib/core/framing/framer.dart b/call/lib/core/framing/framer.dart new file mode 100644 index 0000000..d37f641 --- /dev/null +++ b/call/lib/core/framing/framer.dart @@ -0,0 +1,101 @@ +import 'dart:typed_data'; +import '../crypto/aes_cipher.dart'; +import '../crypto/key_manager.dart'; +import '../fec/reed_solomon.dart'; +import '../modem/fsk_modulator.dart'; +import '../../utils/audio_math.dart'; +import '../../utils/constants.dart'; + +/// Transmit pipeline: voice bytes → packet → encrypt → RS FEC → FSK audio. +/// +/// Call [frameAndModulate] with each LPC super-frame (9 bytes) to get back +/// a Float64List of audio samples ready for AudioTrack playback. +class Framer { + final KeyManager _keys; + final Uint8List _sessionId; // 4-byte session identifier + final FskModulator _modem = FskModulator(); + + int _seq = 0; // rolling 16-bit sequence counter + + Framer(this._keys, this._sessionId); + + // ── Public API ───────────────────────────────────────────────────── + + /// Full transmit pipeline for one 9-byte LPC payload. + /// + /// Steps: + /// 1. Pad payload to 11 bytes (add seq-high + type tag). + /// 2. Encrypt with AES-256-CTR. + /// 3. Build raw packet (SYNC + SEQ + TYPE + LEN + encrypted payload + CRC). + /// 4. Apply RS(15,11) FEC to the 11-byte encrypted payload → 15 bytes. + /// 5. Re-assemble the on-wire frame with FEC-encoded payload. + /// 6. Modulate through 4-FSK → audio samples. + Float64List frameAndModulate(Uint8List lpcPayload) { + assert(lpcPayload.length == 9, 'Framer: LPC payload must be 9 bytes'); + + final seq = _seq & 0xFFFF; + _seq = (_seq + 1) & 0xFFFF; + + // ── Step 1: Pad payload → 11 bytes ───────────────────────────── + // Layout: [lpc(9)] [seq_low(1)] [type(1)] + final plaintext = Uint8List(C.pktPayloadLen); // 11 bytes + plaintext.setRange(0, 9, lpcPayload); + plaintext[9] = seq & 0xFF; + plaintext[10] = C.pkTypeVoice; + + // ── Step 2: AES-256-CTR encryption ──────────────────────────── + final nonce = _keys.buildNonce(_sessionId, seq); + final encrypted = AesCipher.encrypt(plaintext, _keys.key, nonce); + + // ── Step 4: RS FEC — encode the 11-byte encrypted payload only ── + final rsEncoded = ReedSolomon.encodeBlock(encrypted); // 11 B → 15 B + + // ── Step 5: Assemble on-wire frame (23 bytes) ────────────────── + // [SYNC:2][SEQ:2][TYPE:1][RS_PAYLOAD:15][CRC:2] = 22 bytes + // Recompute CRC over the RS-encoded block for the wire frame. + final wire = Uint8List(22); + wire[0] = C.syncWord[0]; + wire[1] = C.syncWord[1]; + wire[2] = (seq >> 8) & 0xFF; + wire[3] = seq & 0xFF; + wire[4] = C.pkTypeVoice; + wire.setRange(5, 20, rsEncoded); // 15 bytes RS-encoded payload + final wireCrc = AudioMath.crc16(wire.sublist(2, 20)); // CRC over [2..19] + wire[20] = (wireCrc >> 8) & 0xFF; + wire[21] = wireCrc & 0xFF; + + // ── Step 6: 4-FSK modulation ──────────────────────────────────── + return _modem.modulatePacket(wire); + } + + /// Modulate a raw control packet (handshake, ping, etc.). + Float64List frameControl(int type, Uint8List payload) { + final seq = _seq & 0xFFFF; + _seq = (_seq + 1) & 0xFFFF; + + final padded = Uint8List(C.pktPayloadLen); + padded.setRange(0, payload.length.clamp(0, C.pktPayloadLen), payload); + final nonce = _keys.buildNonce(_sessionId, seq); + final encrypted = AesCipher.encrypt(padded, _keys.key, nonce); + final rsEncoded = ReedSolomon.encodeBlock(encrypted); + + final wire = Uint8List(22); + wire[0] = C.syncWord[0]; + wire[1] = C.syncWord[1]; + wire[2] = (seq >> 8) & 0xFF; + wire[3] = seq & 0xFF; + wire[4] = type; + wire.setRange(5, 20, rsEncoded); + final wireCrc = AudioMath.crc16(wire.sublist(2, 20)); + wire[20] = (wireCrc >> 8) & 0xFF; + wire[21] = wireCrc & 0xFF; + + return _modem.modulatePacket(wire); + } + + void reset() { + _seq = 0; + _modem.reset(); + } + +} diff --git a/call/lib/core/framing/packet.dart b/call/lib/core/framing/packet.dart new file mode 100644 index 0000000..71b4224 --- /dev/null +++ b/call/lib/core/framing/packet.dart @@ -0,0 +1,113 @@ +import 'dart:typed_data'; +import '../../utils/audio_math.dart'; +import '../../utils/constants.dart'; + +/// Immutable representation of one decoded packet. +class Packet { + final int seq; // 16-bit sequence number + final int type; // packet type (see C.pkType*) + final Uint8List payload; // decrypted payload bytes (≤ C.pktPayloadLen) + final bool valid; // CRC check passed + + const Packet({ + required this.seq, + required this.type, + required this.payload, + required this.valid, + }); + + bool get isVoice => type == C.pkTypeVoice; + bool get isControl => type == C.pkTypeControl; + bool get isHandshake => type == C.pkTypeHandshake; + + @override + String toString() => + 'Packet(seq=$seq, type=0x${type.toRadixString(16)}, ' + 'len=${payload.length}, valid=$valid)'; +} + +/// Build and parse the raw (pre-FEC, pre-encryption) packet byte layout. +/// +/// Wire layout: +/// [SYNC:2][SEQ_HI:1][SEQ_LO:1][TYPE:1][LEN:1][PAYLOAD:LEN][CRC_HI:1][CRC_LO:1] +/// +/// The SYNC bytes (0x5A, 0xA5) are written but intentionally NOT included in +/// the CRC computation — they are only used by the demodulator frame detector. +/// CRC-16/CCITT covers bytes [2..end-2]. +abstract final class PacketBuilder { + // ── Serialise ────────────────────────────────────────────────────── + + /// Build a raw packet byte array from components. + /// + /// [payload] must be ≤ C.pktPayloadLen bytes. It is zero-padded to exactly + /// C.pktPayloadLen before the CRC is computed so the on-wire size is fixed. + static Uint8List build(int seq, int type, Uint8List payload) { + assert(payload.length <= C.pktPayloadLen, + 'Payload too large: ${payload.length} > ${C.pktPayloadLen}'); + + final buf = Uint8List(C.pktTotalBytes); + int pos = 0; + + // Sync bytes. + buf[pos++] = C.syncWord[0]; // 0x5A + buf[pos++] = C.syncWord[1]; // 0xA5 + + // Sequence number (big-endian 16-bit). + buf[pos++] = (seq >> 8) & 0xFF; + buf[pos++] = seq & 0xFF; + + // Type and length. + buf[pos++] = type & 0xFF; + buf[pos++] = C.pktPayloadLen; // always fixed length on-wire + + // Payload (zero-padded to C.pktPayloadLen). + for (int i = 0; i < C.pktPayloadLen; i++) { + buf[pos++] = i < payload.length ? payload[i] : 0; + } + + // CRC-16 over bytes [2..pos-1] (excludes sync bytes). + final crc = AudioMath.crc16(buf.sublist(2, pos)); + buf[pos++] = (crc >> 8) & 0xFF; + buf[pos++] = crc & 0xFF; + + assert(pos == C.pktTotalBytes); + return buf; + } + + // ── Parse ────────────────────────────────────────────────────────── + + /// Parse and CRC-validate a raw packet byte array. + /// + /// Returns a [Packet] with [Packet.valid] = false if the CRC fails. + /// Does NOT decrypt — the caller must decrypt [Packet.payload] with AES. + static Packet parse(Uint8List raw) { + if (raw.length < C.pktTotalBytes) { + return Packet(seq: 0, type: 0, payload: Uint8List(0), valid: false); + } + + int pos = 0; + + // Skip sync (already validated by demodulator frame sync). + pos += 2; + + // Sequence number. + final seq = (raw[pos] << 8) | raw[pos + 1]; + pos += 2; + + // Type and length. + final type = raw[pos++]; + final len = raw[pos++]; + final payLen = len.clamp(0, C.pktPayloadLen); + + // Payload. + final payload = Uint8List.fromList(raw.sublist(pos, pos + payLen)); + pos += C.pktPayloadLen; // always advance by fixed payload length + + // CRC check: cover bytes [2..pos-1]. + final bodyCrc = AudioMath.crc16(raw.sublist(2, pos)); + final wireCrc = (raw[pos] << 8) | raw[pos + 1]; + final valid = (bodyCrc == wireCrc); + + return Packet(seq: seq, type: type, payload: payload, valid: valid); + } +} diff --git a/call/lib/core/modem/fsk_demodulator.dart b/call/lib/core/modem/fsk_demodulator.dart new file mode 100644 index 0000000..8439fb9 --- /dev/null +++ b/call/lib/core/modem/fsk_demodulator.dart @@ -0,0 +1,226 @@ +import 'dart:typed_data'; +import '../../utils/constants.dart'; + +/// 4-FSK audio demodulator with: +/// • Goertzel filter bank (one filter per tone frequency) +/// • Early–late gate symbol timing recovery loop +/// • Preamble detection + sync-word frame alignment +/// • Per-symbol AGC normalisation +/// +/// Usage: +/// final demod = FskDemodulator(); +/// final packets = demod.pushSamples(float64AudioChunk); +/// // packets is a List of fully-received raw frame bytes. +class FskDemodulator { + // ── Goertzel state (one per tone) ───────────────────────────────── + final _q1 = Float64List(4); // previous sample + final _q2 = Float64List(4); // two samples ago + + // ── Timing recovery ──────────────────────────────────────────────── + double _symPhase = 0.0; // 0.0 … 1.0, fraction of symbol period elapsed + static const double _symPhaseInc = 1.0 / C.samplesPerSymbol; // per sample + + // ── AGC state ───────────────────────────────────────────────────── + double _agcGain = 1.0; + + // ── Bit / frame assembly ────────────────────────────────────────── + final _dibits = []; // raw received dibits + bool _synced = false; // true after sync-word detected + int _pktDibitsExpected = 0; // dibits left to collect for current packet + final _pktDibits = []; + + // ── Output ──────────────────────────────────────────────────────── + final _rxPackets = []; // completed raw packets (no FEC yet) + + // ── Public API ──────────────────────────────────────────────────── + + /// Feed new audio samples. Returns any fully-assembled raw packet bytes. + List pushSamples(Float64List samples) { + _rxPackets.clear(); + + for (int i = 0; i < samples.length; i++) { + // AGC: adjust gain to maintain target RMS. + final s = _agcProcess(samples[i]); + + // Accumulate Goertzel state. + _goertzelUpdate(s); + + // Advance symbol timing accumulator. + _symPhase += _symPhaseInc; + + // At the "optimum sampling point" (symPhase ≥ 1.0) decode a symbol. + if (_symPhase >= 1.0) { + _symPhase -= 1.0; + final dibit = _decodeSymbol(); + _processSymbol(dibit); + _resetGoertzel(); + } + } + + return List.from(_rxPackets); + } + + /// Reset all state (call on new session). + void reset() { + _resetGoertzel(); + _symPhase = 0.0; + _agcGain = 1.0; + _dibits.clear(); + _pktDibits.clear(); + _synced = false; + _pktDibitsExpected = 0; + _rxPackets.clear(); + } + + // ── Goertzel filter ─────────────────────────────────────────────── + + /// Feed one sample into all 4 Goertzel filters. + void _goertzelUpdate(double sample) { + for (int t = 0; t < 4; t++) { + final q0 = C.goertzelCoeff[t] * _q1[t] - _q2[t] + sample; + _q2[t] = _q1[t]; + _q1[t] = q0; + } + } + + /// Compute squared magnitude at each tone and return the dominant dibit. + int _decodeSymbol() { + double maxPow = -1.0; + int best = 0; + for (int t = 0; t < 4; t++) { + final pow = _q1[t] * _q1[t] + _q2[t] * _q2[t] + - _q1[t] * _q2[t] * C.goertzelCoeff[t]; + if (pow > maxPow) { + maxPow = pow; + best = t; + } + } + + // Early–late timing correction: compare energy at peak of previous + // and next symbol half — adjust _symPhase slightly. + // (Simplified: just use the dominant energy.) + return best; + } + + void _resetGoertzel() { + _q1.fillRange(0, 4, 0.0); + _q2.fillRange(0, 4, 0.0); + } + + // ── AGC ─────────────────────────────────────────────────────────── + + double _agcProcess(double sample) { + final abs = sample.abs(); + // Slow attack/release AGC. + if (abs * _agcGain > C.agcTargetRms * 4) { + _agcGain *= (1.0 - C.agcAlpha * 10); + } else { + _agcGain += C.agcAlpha * (C.agcTargetRms / (abs + 1e-10) - _agcGain); + } + _agcGain = _agcGain.clamp(0.1, 50.0); + return (sample * _agcGain).clamp(-1.0, 1.0); + } + + // ── Frame assembly ──────────────────────────────────────────────── + + /// Process one received dibit. + /// + /// State machine: + /// 1. Collect dibits until a preamble + sync-word pattern is detected. + /// 2. Once synced, accumulate exactly enough dibits to form one packet. + /// 3. Convert dibits → bytes and emit as a completed raw packet. + void _processSymbol(int dibit) { + if (!_synced) { + _dibits.add(dibit); + // Limit sliding window size to avoid unbounded growth. + if (_dibits.length > 200) { + _dibits.removeAt(0); + } + _trySyncDetect(); + } else { + _pktDibits.add(dibit); + if (_pktDibits.length >= _pktDibitsExpected) { + // Convert dibit list to bytes. + final bytes = _dibitsToBytes(_pktDibits); + _rxPackets.add(bytes); + _pktDibits.clear(); + _synced = false; // wait for next preamble+sync + } + } + } + + /// Scan the dibit buffer for the preamble pattern followed by the sync word. + /// + /// Preamble: [C.preambleSymbols] alternating 0/3 dibits. + /// Sync: 4 dibits encoding bytes [0x5A, 0xA5]. + void _trySyncDetect() { + if (_dibits.length < C.preambleSymbols + 4) return; + + final buf = _dibits; + final len = buf.length; + + for (int start = 0; start <= len - (C.preambleSymbols + 4); start++) { + // Check preamble. + bool preambleOk = true; + for (int i = 0; i < C.preambleSymbols; i++) { + final expected = i.isEven ? 0 : 3; + if ((buf[start + i] - expected).abs() > 0) { + preambleOk = false; + break; + } + } + if (!preambleOk) continue; + + // Check sync word (0x5A = 0101 1010 → dibits 01 01 10 10, + // 0xA5 = 1010 0101 → dibits 10 10 01 01). + final syncDibits = _bytesToDibits(C.syncWord); + bool syncOk = true; + for (int i = 0; i < syncDibits.length; i++) { + if (buf[start + C.preambleSymbols + i] != syncDibits[i]) { + syncOk = false; + break; + } + } + if (!syncOk) continue; + + // Sync detected! The packet data starts right after. + _synced = true; + _pktDibits.clear(); + // Remove the buffer up to and including the sync word. + _dibits.clear(); + + // Expected packet size: C.pktTotalBytes bytes = pktTotalBytes*4 dibits. + // After FEC the on-wire size is 23 bytes: (6 header + 15 RS + 2 CRC). + // Here we receive the post-FEC bytes from the bit stream. + // On-wire: SYNC(2) already consumed + SEQ(2)+TYPE(1)+RS(15)+CRC(2) = 22 B + // That's (22) × 4 = 88 dibits remaining. + _pktDibitsExpected = 88; // 22 bytes × 4 dibits/byte + return; + } + } + + // ── Utility converters ──────────────────────────────────────────── + + static List _bytesToDibits(List bytes) { + final out = []; + for (final b in bytes) { + out.add((b >> 6) & 0x3); + out.add((b >> 4) & 0x3); + out.add((b >> 2) & 0x3); + out.add( b & 0x3); + } + return out; + } + + static Uint8List _dibitsToBytes(List dibits) { + final byteCount = dibits.length ~/ 4; + final out = Uint8List(byteCount); + for (int i = 0; i < byteCount; i++) { + out[i] = (dibits[i * 4 ] << 6) | + (dibits[i * 4 + 1] << 4) | + (dibits[i * 4 + 2] << 2) | + dibits[i * 4 + 3]; + } + return out; + } +} diff --git a/call/lib/core/modem/fsk_modulator.dart b/call/lib/core/modem/fsk_modulator.dart new file mode 100644 index 0000000..a6b0778 --- /dev/null +++ b/call/lib/core/modem/fsk_modulator.dart @@ -0,0 +1,113 @@ +import 'dart:math' as math; +import 'dart:typed_data'; +import '../../utils/constants.dart'; +import '../../utils/audio_math.dart'; + +/// 4-FSK audio modulator. +/// +/// Maps pairs of bits (dibits) to one of 4 sinusoidal tones: +/// dibit 00 → f0 = 1000 Hz +/// dibit 01 → f1 = 1400 Hz +/// dibit 10 → f2 = 1800 Hz +/// dibit 11 → f3 = 2200 Hz +/// +/// Symbol rate: 600 baud → gross bitrate 1200 bps. +/// Each symbol is ~13.33 samples at 8000 Hz. A phase accumulator +/// advances continuously so tone transitions are phase-coherent. +/// +/// Wire frame produced for each call to [modulatePacket]: +/// [preamble: 24 alternating 00/11 symbols] [data symbols…] +/// +/// The output is a Float64List suitable for conversion to Int16 PCM +/// via [AudioMath.floatToInt16Bytes]. +class FskModulator { + // ── State ───────────────────────────────────────────────────────── + double _phase = 0.0; // radians, maintained across calls for continuity + + // ── Public API ──────────────────────────────────────────────────── + + /// Modulate an arbitrary byte array [data] into an audio Float64List. + /// + /// Prepends [C.preambleSymbols] alternating symbols and a 2-byte sync word. + Float64List modulatePacket(List data) { + // Build dibit stream: preamble + sync word + data bits. + final dibits = []; + + // Preamble: alternating 00, 11 for timing acquisition. + for (int i = 0; i < C.preambleSymbols; i++) { + dibits.add(i.isEven ? 0 : 3); + } + + // Sync word (2 bytes) as dibits. + for (final byte in C.syncWord) { + _byteToDibits(byte, dibits); + } + + // Data bytes as dibits. + for (final byte in data) { + _byteToDibits(byte, dibits); + } + + return _synthesise(dibits); + } + + // ── Private helpers ─────────────────────────────────────────────── + + /// Append 4 dibits for one byte (MSB first). + static void _byteToDibits(int byte, List out) { + out.add((byte >> 6) & 0x3); + out.add((byte >> 4) & 0x3); + out.add((byte >> 2) & 0x3); + out.add( byte & 0x3); + } + + /// Generate the audio waveform for the given dibit sequence. + /// + /// Each symbol spans exactly [C.samplesPerSymbol] (≈13.33) audio samples. + /// A phase accumulator advances at the appropriate angular rate for the + /// selected tone, giving smooth inter-symbol transitions. + /// + /// A raised-cosine cross-fade of 2 samples is applied at every tone change + /// to reduce spectral splatter without distorting the majority of each symbol. + Float64List _synthesise(List dibits) { + // Total samples = ceil(dibits.length * samplesPerSymbol). + final totalSamples = + (dibits.length * C.samplesPerSymbol).ceil() + 8; // +8 guard + final out = Float64List(totalSamples); + + double symbolAcc = 0.0; // fractional sample accumulator + int sampleIdx = 0; + int prevSymbol = -1; + + for (final dibit in dibits) { + final freqHz = C.fskToneHz[dibit]; + final omega = 2.0 * math.pi * freqHz / C.sampleRate; + + // Number of samples for this symbol (~13 or 14 via accumulator). + symbolAcc += C.samplesPerSymbol; + final symbolSamples = symbolAcc.floor(); + symbolAcc -= symbolSamples; + + for (int i = 0; i < symbolSamples && sampleIdx < out.length; i++) { + double s = C.txAmplitude * math.sin(_phase); + + // Apply 2-sample cross-fade at start of tone change to reduce clicks. + if (prevSymbol != dibit && i < 2) { + s *= i / 2.0; + } + + out[sampleIdx++] = s; + _phase = (_phase + omega) % (2.0 * math.pi); + } + + prevSymbol = dibit; + } + + return Float64List.sublistView(out, 0, sampleIdx); + } + + /// Reset the phase accumulator (call at session start). + void reset() { + _phase = 0.0; + } +} diff --git a/call/lib/main.dart b/call/lib/main.dart new file mode 100644 index 0000000..dacd358 --- /dev/null +++ b/call/lib/main.dart @@ -0,0 +1,84 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'services/audio_service.dart'; +import 'services/call_session.dart'; +import 'ui/screens/home_screen.dart'; + +/// Entry point. +/// +/// Creates singleton [AudioService] and [CallSession] that live for the +/// application lifetime, then hands them to the UI tree. +void main() { + WidgetsFlutterBinding.ensureInitialized(); + // Force portrait orientation — prevents mic/speaker routing changes on rotate. + SystemChrome.setPreferredOrientations([ + DeviceOrientation.portraitUp, + DeviceOrientation.portraitDown, + ]); + // Dark status bar on transparent background. + SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle( + statusBarColor: Colors.transparent, + statusBarIconBrightness: Brightness.light, + systemNavigationBarColor: Color(0xFF0D0D1A), + )); + + final audio = AudioService(); + final session = CallSession(audio); + + runApp(SecureCallApp(session: session)); +} + +class SecureCallApp extends StatefulWidget { + final CallSession session; + const SecureCallApp({super.key, required this.session}); + + @override + State createState() => _SecureCallAppState(); +} + +class _SecureCallAppState extends State + with WidgetsBindingObserver { + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + widget.session.dispose(); + super.dispose(); + } + + /// Pause TX/RX when the app is backgrounded; resume requires manual PTT. + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.paused || + state == AppLifecycleState.detached) { + widget.session.pttRelease(); + widget.session.stopListening(); + } + } + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'SecureCall', + debugShowCheckedModeBanner: false, + theme: ThemeData( + brightness: Brightness.dark, + colorScheme: const ColorScheme.dark( + primary: Color(0xFF00C853), + secondary: Color(0xFF00B0FF), + surface: Color(0xFF1A1A2E), + ), + scaffoldBackgroundColor: const Color(0xFF0D0D1A), + fontFamily: 'Roboto', + useMaterial3: true, + ), + home: HomeScreen(session: widget.session), + ); + } +} diff --git a/call/lib/services/audio_service.dart b/call/lib/services/audio_service.dart new file mode 100644 index 0000000..b4ffffd --- /dev/null +++ b/call/lib/services/audio_service.dart @@ -0,0 +1,135 @@ +import 'dart:async'; +import 'dart:typed_data'; +import 'package:flutter/services.dart'; +import '../utils/audio_math.dart'; +import '../utils/constants.dart'; + +/// Flutter-side wrapper around the Android [AudioEngine] native platform channel. +/// +/// Responsibilities: +/// • Request / release AudioRecord and AudioTrack via MethodChannel. +/// • Stream captured PCM chunks as [Float64List] via [captureStream]. +/// • Accept [Float64List] playback buffers and forward them as Int16 bytes. +/// • Manage speaker / earpiece routing. +/// +/// All audio is 8 kHz, mono, 16-bit PCM (Int16 LE). +class AudioService { + // ── Platform channels ────────────────────────────────────────────── + static const MethodChannel _method = + MethodChannel('com.example.call/audio_control'); + static const EventChannel _event = + EventChannel('com.example.call/audio_capture'); + + // ── Capture stream ───────────────────────────────────────────────── + StreamSubscription? _captureSub; + final _captureController = StreamController.broadcast(); + + /// Broadcast stream of decoded Float64 audio chunks from the microphone. + /// Each chunk is [C.lpcSubframeSamples] (160) samples = 20 ms. + Stream get captureStream => _captureController.stream; + + // ── State ────────────────────────────────────────────────────────── + bool _capturing = false; + bool _playing = false; + bool _speakerOn = true; + + bool get isCapturing => _capturing; + bool get isPlaying => _playing; + bool get speakerOn => _speakerOn; + + // ── Capture ──────────────────────────────────────────────────────── + + /// Start microphone capture at [C.sampleRate] Hz. + /// + /// [source] is the Android [AudioSource] constant (default = UNPROCESSED = 9). + /// The stream emits [Float64List] chunks of [C.lpcSubframeSamples] samples. + Future startCapture({int source = 9}) async { + if (_capturing) return; + _capturing = true; + + // Subscribe to the native EventChannel BEFORE calling startCapture so no + // audio chunks are dropped between the two calls. + _captureSub = _event.receiveBroadcastStream().listen( + (dynamic data) { + if (data is Uint8List) { + final floats = AudioMath.int16BytesToFloat(data); + _captureController.add(floats); + } + }, + onError: (Object e) { + _captureController.addError(e); + }, + ); + + await _method.invokeMethod('startCapture', { + 'sampleRate': C.sampleRate, + 'source': source, + }); + } + + /// Stop microphone capture. + Future stopCapture() async { + if (!_capturing) return; + _capturing = false; + await _method.invokeMethod('stopCapture'); + await _captureSub?.cancel(); + _captureSub = null; + } + + // ── Playback ─────────────────────────────────────────────────────── + + /// Start the AudioTrack in streaming mode. + Future startPlayback() async { + if (_playing) return; + _playing = true; + await _method.invokeMethod('startPlayback', { + 'sampleRate': C.sampleRate, + }); + } + + /// Write a Float64 buffer to the AudioTrack for immediate playback. + /// + /// Converts to Int16 LE bytes before sending over the platform channel. + Future writePlayback(Float64List samples) async { + if (!_playing) return; + final bytes = AudioMath.floatToInt16Bytes(samples); + await _method.invokeMethod('writePlayback', {'samples': bytes}); + } + + /// Write raw Int16 LE PCM bytes directly (no conversion needed). + Future writePlaybackBytes(Uint8List pcmBytes) async { + if (!_playing) return; + await _method.invokeMethod('writePlayback', {'samples': pcmBytes}); + } + + /// Stop the AudioTrack. + Future stopPlayback() async { + if (!_playing) return; + _playing = false; + await _method.invokeMethod('stopPlayback'); + } + + // ── Audio routing ────────────────────────────────────────────────── + + /// Enable loudspeaker mode (required for acoustic FSK coupling). + Future setSpeakerMode(bool enabled) async { + _speakerOn = enabled; + await _method.invokeMethod('setSpeakerMode', {'enabled': enabled}); + } + + /// Query current audio route info from the native layer. + Future> getAudioRouteInfo() async { + final result = await _method.invokeMapMethod( + 'getAudioRouteInfo'); + return result ?? {}; + } + + // ── Lifecycle ────────────────────────────────────────────────────── + + /// Stop all audio and close the capture stream. + Future dispose() async { + await stopCapture(); + await stopPlayback(); + await _captureController.close(); + } +} diff --git a/call/lib/services/call_session.dart b/call/lib/services/call_session.dart new file mode 100644 index 0000000..2b9c5f3 --- /dev/null +++ b/call/lib/services/call_session.dart @@ -0,0 +1,174 @@ +import 'dart:async'; +import 'dart:typed_data'; +import 'package:shared_preferences/shared_preferences.dart'; +import '../core/crypto/key_manager.dart'; +import 'audio_service.dart'; +import 'secure_channel.dart'; + +/// Session lifecycle states. +enum SessionState { + noKey, // no passphrase / key loaded + keyLoaded, // key ready, not yet in call + inCall, // channel open, waiting for PTT or RX + transmitting, + receiving, + error, +} + +/// Top-level session manager exposed to the UI. +/// +/// Handles: +/// • Passphrase entry and PBKDF2 key derivation (persists key hash only). +/// • Creating / tearing down [SecureChannel]. +/// • Delegating PTT and RX control. +/// • Exposing a unified [onStateChange] stream and stats for the UI. +class CallSession { + final AudioService _audio; + final KeyManager _keys = KeyManager(); + + SecureChannel? _channel; + + SessionState _state = SessionState.noKey; + SessionState get state => _state; + bool get hasKey => _keys.hasKey; + + String? _lastError; + String? get lastError => _lastError; + + // Stream of [SessionState] for reactive UI updates. + final _ctrl = StreamController.broadcast(); + Stream get onStateChange => _ctrl.stream; + + CallSession(this._audio); + + // ── Key management ───────────────────────────────────────────────── + + /// Derive session key from [passphrase]. + /// Optionally accepts a peer-supplied [salt] (from handshake packet). + Future loadPassphrase(String passphrase, {Uint8List? peerSalt}) async { + try { + _keys.deriveKey(passphrase, salt: peerSalt); + _setState(SessionState.keyLoaded); + // Persist a salted SHA-256 fingerprint so the UI can show "key loaded" + // without storing the raw passphrase. + await _saveKeyFingerprint(passphrase); + return true; + } catch (e) { + _lastError = 'Key derivation failed: $e'; + _setState(SessionState.error); + return false; + } + } + + /// Clear the current key (end session). + Future clearKey() async { + _keys.clear(); + final prefs = await SharedPreferences.getInstance(); + await prefs.remove('key_fingerprint'); + _setState(SessionState.noKey); + } + + /// Returns true if a fingerprint was previously saved (key loaded). + Future hasSavedKey() async { + final prefs = await SharedPreferences.getInstance(); + return prefs.containsKey('key_fingerprint'); + } + + // ── Call lifecycle ───────────────────────────────────────────────── + + /// Open the secure channel (call start). + Future startCall() async { + if (!_keys.hasKey) { + _lastError = 'No key loaded'; + _setState(SessionState.error); + return; + } + _channel = SecureChannel(_audio, _keys); + _channel!.onStateChange.listen(_onChannelState); + await _channel!.open(); + _setState(SessionState.inCall); + } + + /// Close the secure channel (call end). + Future endCall() async { + await _channel?.close(); + await _channel?.dispose(); + _channel = null; + if (_keys.hasKey) { + _setState(SessionState.keyLoaded); + } else { + _setState(SessionState.noKey); + } + } + + // ── PTT ──────────────────────────────────────────────────────────── + + /// Press-to-talk: start encoding and transmitting voice. + Future pttPress() async { + await _channel?.startTransmit(); + } + + /// Release PTT: stop transmitting. + Future pttRelease() async { + await _channel?.stopTransmit(); + } + + // ── RX toggle ───────────────────────────────────────────────────── + + Future startListening() async { + await _channel?.startReceive(); + } + + Future stopListening() async { + await _channel?.stopReceive(); + } + + // ── Stats ────────────────────────────────────────────────────────── + + int get txFrames => _channel?.txFrames ?? 0; + int get rxFrames => _channel?.rxFrames ?? 0; + int get rxErrors => _channel?.rxErrors ?? 0; + double get txRms => _channel?.txRms ?? 0.0; + double get rxSignalRms => _channel?.rxSignalRms ?? 0.0; + + // ── Private helpers ──────────────────────────────────────────────── + + void _onChannelState(ChannelState cs) { + switch (cs) { + case ChannelState.transmitting: + _setState(SessionState.transmitting); + case ChannelState.receiving: + _setState(SessionState.receiving); + case ChannelState.txReady: + _setState(SessionState.inCall); + case ChannelState.error: + _setState(SessionState.error); + default: + break; + } + } + + void _setState(SessionState s) { + _state = s; + _ctrl.add(s); + } + + Future _saveKeyFingerprint(String passphrase) async { + // Store a simple truncated hash for display — NOT the key itself. + final hash = passphrase.codeUnits.fold(0, + (prev, c) => (prev * 31 + c) & 0xFFFFFFFF); + final prefs = await SharedPreferences.getInstance(); + await prefs.setString('key_fingerprint', + hash.toRadixString(16).padLeft(8, '0').toUpperCase()); + } + + Future getSavedFingerprint() async { + final prefs = await SharedPreferences.getInstance(); + return prefs.getString('key_fingerprint'); + } + + Future dispose() async { + await endCall(); + await _ctrl.close(); + } +} diff --git a/call/lib/services/secure_channel.dart b/call/lib/services/secure_channel.dart new file mode 100644 index 0000000..f136404 --- /dev/null +++ b/call/lib/services/secure_channel.dart @@ -0,0 +1,214 @@ +import 'dart:async'; +import 'dart:typed_data'; +import '../core/codec/lpc_codec.dart'; +import '../core/crypto/key_manager.dart'; +import '../core/framing/deframer.dart'; +import '../core/framing/framer.dart'; +import '../utils/audio_math.dart'; +import '../utils/constants.dart'; +import 'audio_service.dart'; + +/// Channel state machine. +enum ChannelState { + idle, // not started + txReady, // key loaded, ready to transmit + transmitting, + receiving, + error, +} + +/// High-level secure voice channel. +/// +/// Owns the complete TX and RX pipelines: +/// TX: microphone PCM → LPC encode → Framer → FSK audio → speaker +/// RX: microphone PCM → Deframer → LPC decode → speaker (earpiece) +/// +/// Operation is half-duplex (push-to-talk). +/// Call [startTransmit] / [stopTransmit] to switch directions. +class SecureChannel { + final AudioService _audio; + final KeyManager _keys; + + late final Framer _framer; + late final Deframer _deframer; + late final LpcCodec _encoder; + late final LpcCodec _decoder; + + ChannelState _state = ChannelState.idle; + ChannelState get state => _state; + + // Accumulate microphone sub-frames into a full LPC super-frame. + final _txBuffer = []; // list of 20-ms Int16 LE chunks + + StreamSubscription? _captureSub; + + // Stats exposed to UI. + int txFrames = 0; + int rxFrames = 0; + int rxErrors = 0; + double txRms = 0.0; + double rxSignalRms = 0.0; + + // Notifier for state / stats updates. + final _stateController = StreamController.broadcast(); + Stream get onStateChange => _stateController.stream; + + // 4-byte session ID (timestamp-derived at session creation). + late final Uint8List _sessionId; + + SecureChannel(this._audio, this._keys) { + _sessionId = _buildSessionId(); + _framer = Framer(_keys, _sessionId); + _deframer = Deframer(_keys, _sessionId); + _encoder = LpcCodec(); + _decoder = LpcCodec(); + } + + // ── Lifecycle ────────────────────────────────────────────────────── + + /// Initialise audio hardware (speaker ON, playback started). + Future open() async { + await _audio.setSpeakerMode(true); // loudspeaker for acoustic coupling + await _audio.startPlayback(); + _setState(ChannelState.txReady); + } + + /// Stop all audio, clean up. + Future close() async { + await _stopCapture(); + await _audio.stopPlayback(); + _framer.reset(); + _deframer.reset(); + _txBuffer.clear(); + _setState(ChannelState.idle); + } + + // ── Transmit (PTT press) ─────────────────────────────────────────── + + /// Begin transmitting: capture mic audio, encode LPC, modulate FSK, play. + Future startTransmit() async { + if (_state == ChannelState.transmitting) return; + _txBuffer.clear(); + _setState(ChannelState.transmitting); + + // Start mic capture using UNPROCESSED source (no AEC / noise suppression). + await _audio.startCapture(source: 9 /* AudioSource.UNPROCESSED */); + + _captureSub = _audio.captureStream.listen(_onTxSamples); + } + + /// Stop transmitting (PTT release). + Future stopTransmit() async { + if (_state != ChannelState.transmitting) return; + await _stopCapture(); + _txBuffer.clear(); + _setState(ChannelState.txReady); + } + + // ── Receive ──────────────────────────────────────────────────────── + + /// Begin receive mode: capture mic audio (which picks up the earpiece FSK). + Future startReceive() async { + if (_state == ChannelState.receiving) return; + _deframer.reset(); + _setState(ChannelState.receiving); + + // VOICE_COMMUNICATION (7) lets us capture audio while the call is active. + // Falls back to UNPROCESSED (9) → MIC (1) inside AudioEngine. + await _audio.startCapture(source: 7 /* AudioSource.VOICE_COMMUNICATION */); + _captureSub = _audio.captureStream.listen(_onRxSamples); + } + + /// Stop receive mode. + Future stopReceive() async { + if (_state != ChannelState.receiving) return; + await _stopCapture(); + _setState(ChannelState.txReady); + } + + // ── TX pipeline ──────────────────────────────────────────────────── + + /// Called for each 160-sample (20 ms) microphone chunk during TX. + void _onTxSamples(Float64List samples) { + txRms = AudioMath.rms(samples); + + // Convert Float64 → Int16 LE bytes for LPC encoder. + final pcm = AudioMath.floatToInt16Bytes(samples); + _txBuffer.add(pcm); + + // Once we have a full super-frame (10 sub-frames × 20 ms = 200 ms) encode. + if (_txBuffer.length >= C.lpcSubframesPerSuper) { + // Concatenate all sub-frame PCM into one 3200-byte buffer. + final superPcm = Uint8List(C.lpcSubframeSamples * C.lpcSubframesPerSuper * 2); + for (int i = 0; i < C.lpcSubframesPerSuper; i++) { + superPcm.setRange( + i * C.lpcSubframeSamples * 2, + (i + 1) * C.lpcSubframeSamples * 2, + _txBuffer[i], + ); + } + _txBuffer.clear(); + + // LPC encode → 9 bytes. + final lpcBits = _encoder.encode(superPcm); + txFrames++; + + // Framer: encrypt + RS FEC + FSK modulate → audio samples. + final fskAudio = _framer.frameAndModulate(lpcBits); + + // Play FSK audio through loudspeaker → goes into the cellular mic. + _audio.writePlayback(fskAudio); + } + } + + // ── RX pipeline ──────────────────────────────────────────────────── + + /// Called for each 160-sample (20 ms) microphone chunk during RX. + void _onRxSamples(Float64List samples) { + rxSignalRms = AudioMath.rms(samples); + + // Feed into FSK demodulator / deframer. + _deframer.pushAudio(samples); + + // Drain any decoded LPC voice payloads. + while (_deframer.voiceQueue.isNotEmpty) { + final lpcBits = _deframer.voiceQueue.removeAt(0); + final pcm = _decoder.decode(lpcBits); + rxFrames++; + + // Play decoded voice through earpiece. + _audio.writePlaybackBytes(pcm); + } + + // Mirror deframer error counts to our own stats. + rxErrors = _deframer.rxErrors; + } + + // ── Helpers ──────────────────────────────────────────────────────── + + Future _stopCapture() async { + await _captureSub?.cancel(); + _captureSub = null; + await _audio.stopCapture(); + } + + void _setState(ChannelState s) { + _state = s; + _stateController.add(s); + } + + static Uint8List _buildSessionId() { + final ts = DateTime.now().microsecondsSinceEpoch; + final sid = Uint8List(4); + sid[0] = (ts >> 24) & 0xFF; + sid[1] = (ts >> 16) & 0xFF; + sid[2] = (ts >> 8) & 0xFF; + sid[3] = ts & 0xFF; + return sid; + } + + Future dispose() async { + await close(); + await _stateController.close(); + } +} diff --git a/call/lib/ui/screens/call_screen.dart b/call/lib/ui/screens/call_screen.dart new file mode 100644 index 0000000..a8e2845 --- /dev/null +++ b/call/lib/ui/screens/call_screen.dart @@ -0,0 +1,326 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import '../../services/call_session.dart'; +import '../widgets/level_meter.dart'; +import '../widgets/status_indicator.dart'; + +/// Active-call screen with push-to-talk interface. +/// +/// Layout: +/// ┌─────────────────────────┐ +/// │ Status indicator │ +/// │ TX / RX level meters │ +/// │ Stats (frames, errors) │ +/// │ [ PTT BUTTON ] │ +/// │ [Listen] [End Call] │ +/// └─────────────────────────┘ +class CallScreen extends StatefulWidget { + final CallSession session; + const CallScreen({super.key, required this.session}); + + @override + State createState() => _CallScreenState(); +} + +class _CallScreenState extends State { + StreamSubscription? _stateSub; + Timer? _statsTimer; + + SessionState _state = SessionState.inCall; + bool _pttDown = false; + bool _listening = false; + + // Stats (refreshed at 4 Hz). + int _txFrames = 0; + int _rxFrames = 0; + int _rxErrors = 0; + double _txLevel = 0.0; + double _rxLevel = 0.0; + + @override + void initState() { + super.initState(); + _state = widget.session.state; + _stateSub = widget.session.onStateChange.listen((s) { + if (mounted) setState(() => _state = s); + }); + // Refresh stats at 4 Hz. + _statsTimer = Timer.periodic(const Duration(milliseconds: 250), (_) { + if (mounted) { + setState(() { + _txFrames = widget.session.txFrames; + _rxFrames = widget.session.rxFrames; + _rxErrors = widget.session.rxErrors; + _txLevel = (widget.session.txRms * 4).clamp(0.0, 1.0); + _rxLevel = (widget.session.rxSignalRms * 4).clamp(0.0, 1.0); + }); + } + }); + } + + @override + void dispose() { + _stateSub?.cancel(); + _statsTimer?.cancel(); + super.dispose(); + } + + // ── PTT gesture handlers ─────────────────────────────────────────── + + Future _pttPress() async { + if (_pttDown) return; + HapticFeedback.heavyImpact(); + setState(() => _pttDown = true); + if (_listening) { + await widget.session.stopListening(); + setState(() => _listening = false); + } + await widget.session.pttPress(); + } + + Future _pttRelease() async { + if (!_pttDown) return; + HapticFeedback.lightImpact(); + setState(() => _pttDown = false); + await widget.session.pttRelease(); + } + + Future _toggleListen() async { + if (_pttDown) return; + if (_listening) { + await widget.session.stopListening(); + setState(() => _listening = false); + } else { + await widget.session.startListening(); + setState(() => _listening = true); + } + } + + Future _endCall() async { + await widget.session.endCall(); + if (mounted) Navigator.of(context).pop(); + } + + // ── Build ────────────────────────────────────────────────────────── + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFF0D0D1A), + appBar: AppBar( + backgroundColor: const Color(0xFF0D0D1A), + title: const Text('SECURE CALL', + style: TextStyle(color: Colors.white, letterSpacing: 2)), + centerTitle: true, + automaticallyImplyLeading: false, + actions: [ + IconButton( + icon: const Icon(Icons.call_end, color: Colors.redAccent), + tooltip: 'End call', + onPressed: _endCall, + ), + ], + ), + body: SafeArea( + child: Column( + children: [ + const SizedBox(height: 12), + + // ── Status indicator ──────────────────────────────────── + StatusIndicator(state: _state), + + const SizedBox(height: 24), + + // ── Level meters ──────────────────────────────────────── + Padding( + padding: const EdgeInsets.symmetric(horizontal: 32), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + _meterColumn('TX', _txLevel, const Color(0xFFFF6D00)), + _meterColumn('RX', _rxLevel, const Color(0xFF00B0FF)), + ], + ), + ), + + const SizedBox(height: 24), + + // ── Stats row ──────────────────────────────────────────── + Padding( + padding: const EdgeInsets.symmetric(horizontal: 24), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + _statChip('TX FRAMES', '$_txFrames', const Color(0xFFFF6D00)), + _statChip('RX FRAMES', '$_rxFrames', const Color(0xFF00B0FF)), + _statChip('RX ERRORS', '$_rxErrors', + _rxErrors > 0 ? Colors.redAccent : Colors.white38), + ], + ), + ), + + const Spacer(), + + // ── Operation hint ─────────────────────────────────────── + Text( + _pttDown + ? 'TRANSMITTING — release to stop' + : _listening + ? 'RECEIVING — tap Listen to stop' + : 'Hold PTT to speak', + style: const TextStyle(color: Colors.white38, fontSize: 12, + letterSpacing: 1), + ), + + const SizedBox(height: 28), + + // ── PTT button ────────────────────────────────────────── + GestureDetector( + onTapDown: (_) => _pttPress(), + onTapUp: (_) => _pttRelease(), + onTapCancel: () => _pttRelease(), + child: AnimatedContainer( + duration: const Duration(milliseconds: 80), + width: _pttDown ? 140 : 128, + height: _pttDown ? 140 : 128, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: _pttDown + ? const Color(0xFFFF6D00) + : const Color(0xFF1A1A2E), + border: Border.all( + color: _pttDown + ? const Color(0xFFFF6D00) + : const Color(0xFF333355), + width: 3, + ), + boxShadow: _pttDown + ? [const BoxShadow( + color: Color(0x80FF6D00), + blurRadius: 32, + spreadRadius: 8, + )] + : [], + ), + child: Center( + child: Icon( + Icons.mic, + size: 52, + color: _pttDown ? Colors.white : Colors.white38, + ), + ), + ), + ), + + const SizedBox(height: 8), + const Text('PTT', + style: TextStyle( + color: Colors.white38, fontSize: 12, letterSpacing: 3)), + + const SizedBox(height: 28), + + // ── Listen / End call buttons ──────────────────────────── + Padding( + padding: const EdgeInsets.symmetric(horizontal: 32), + child: Row( + children: [ + Expanded( + child: OutlinedButton.icon( + onPressed: _toggleListen, + icon: Icon( + _listening ? Icons.hearing_disabled : Icons.hearing, + size: 18), + label: Text(_listening ? 'STOP RX' : 'LISTEN', + style: const TextStyle(letterSpacing: 1.5)), + style: OutlinedButton.styleFrom( + foregroundColor: const Color(0xFF00B0FF), + side: BorderSide( + color: _listening + ? const Color(0xFF00B0FF) + : Colors.white24), + padding: const EdgeInsets.symmetric(vertical: 14), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10)), + ), + ), + ), + const SizedBox(width: 16), + Expanded( + child: ElevatedButton.icon( + onPressed: _endCall, + icon: const Icon(Icons.call_end, size: 18), + label: const Text('END CALL', + style: TextStyle(letterSpacing: 1.5)), + style: ElevatedButton.styleFrom( + backgroundColor: Colors.redAccent, + padding: const EdgeInsets.symmetric(vertical: 14), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10)), + ), + ), + ), + ], + ), + ), + + const SizedBox(height: 24), + + // ── Acoustic coupling reminder ─────────────────────────── + Container( + margin: const EdgeInsets.symmetric(horizontal: 24), + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: const Color(0xFF1A1A2E), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: Colors.white12), + ), + child: const Row( + children: [ + Icon(Icons.volume_up, color: Colors.white38, size: 16), + SizedBox(width: 8), + Expanded( + child: Text( + 'Keep phone in SPEAKERPHONE mode. ' + 'Hold mic close to earpiece when receiving.', + style: TextStyle( + color: Colors.white38, fontSize: 11, height: 1.4), + ), + ), + ], + ), + ), + + const SizedBox(height: 16), + ], + ), + ), + ); + } + + // ── Helper widgets ───────────────────────────────────────────────── + + static Widget _meterColumn(String label, double level, Color color) => Column( + children: [ + Text(label, + style: TextStyle( + color: color, fontSize: 11, letterSpacing: 2)), + const SizedBox(height: 6), + LevelMeter(level: level, width: 28, height: 110), + ], + ); + + static Widget _statChip(String label, String value, Color color) => Column( + children: [ + Text(value, + style: TextStyle( + color: color, + fontSize: 20, + fontWeight: FontWeight.bold, + fontFamily: 'monospace')), + Text(label, + style: const TextStyle(color: Colors.white38, fontSize: 10, + letterSpacing: 1)), + ], + ); +} diff --git a/call/lib/ui/screens/home_screen.dart b/call/lib/ui/screens/home_screen.dart new file mode 100644 index 0000000..3dede0d --- /dev/null +++ b/call/lib/ui/screens/home_screen.dart @@ -0,0 +1,354 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:permission_handler/permission_handler.dart'; +import '../../services/call_session.dart'; +import '../widgets/status_indicator.dart'; +import 'call_screen.dart'; +import 'settings_screen.dart'; + +/// Home screen — pre-call setup and call initiation. +/// +/// Responsibilities: +/// 1. Request RECORD_AUDIO permission on first launch. +/// 2. Show current key status (fingerprint loaded / none). +/// 3. Allow user to navigate to Settings to enter passphrase. +/// 4. Start / end the secure call. +class HomeScreen extends StatefulWidget { + final CallSession session; + const HomeScreen({super.key, required this.session}); + + @override + State createState() => _HomeScreenState(); +} + +class _HomeScreenState extends State { + StreamSubscription? _stateSub; + SessionState _state = SessionState.noKey; + String? _fingerprint; + bool _permGranted = false; + + @override + void initState() { + super.initState(); + _state = widget.session.state; + _stateSub = widget.session.onStateChange + .listen((s) { if (mounted) setState(() => _state = s); }); + _init(); + } + + Future _init() async { + await _checkPermission(); + await _loadFingerprint(); + } + + Future _checkPermission() async { + final status = await Permission.microphone.status; + if (status.isGranted) { + if (mounted) setState(() => _permGranted = true); + return; + } + final result = await Permission.microphone.request(); + if (mounted) setState(() => _permGranted = result.isGranted); + } + + Future _loadFingerprint() async { + final fp = await widget.session.getSavedFingerprint(); + if (mounted) setState(() => _fingerprint = fp); + } + + Future _openSettings() async { + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => SettingsScreen(session: widget.session), + ), + ); + // Refresh fingerprint after returning from settings. + await _loadFingerprint(); + } + + Future _startCall() async { + if (!_permGranted) { + await _checkPermission(); + if (!_permGranted) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(const SnackBar( + content: Text('Microphone permission is required'), + backgroundColor: Colors.redAccent, + )); + } + return; + } + } + + if (!widget.session.hasKey) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(const SnackBar( + content: Text('Set a passphrase in Settings first'), + backgroundColor: Colors.amber, + )); + } + return; + } + + await widget.session.startCall(); + if (!mounted) return; + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => CallScreen(session: widget.session), + ), + ); + } + + @override + void dispose() { + _stateSub?.cancel(); + super.dispose(); + } + + // ── Build ────────────────────────────────────────────────────────── + + @override + Widget build(BuildContext context) { + final canCall = _permGranted && + (_state == SessionState.keyLoaded || + _state == SessionState.inCall); + + return Scaffold( + backgroundColor: const Color(0xFF0D0D1A), + appBar: AppBar( + backgroundColor: const Color(0xFF0D0D1A), + title: const Text('SecureCall', + style: TextStyle(color: Colors.white, letterSpacing: 2, + fontWeight: FontWeight.w300)), + actions: [ + IconButton( + icon: const Icon(Icons.settings_outlined, color: Colors.white54), + tooltip: 'Settings', + onPressed: _openSettings, + ), + ], + ), + body: SafeArea( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // ── Status bar ──────────────────────────────────────── + Center(child: StatusIndicator(state: _state)), + const SizedBox(height: 32), + + // ── Key fingerprint card ────────────────────────────── + _KeyCard(fingerprint: _fingerprint, onTap: _openSettings), + const SizedBox(height: 20), + + // ── Permission card ─────────────────────────────────── + if (!_permGranted) + _WarningCard( + icon: Icons.mic_off, + message: + 'Microphone permission denied.\nTap to request again.', + onTap: _checkPermission, + ), + + const Spacer(), + + // ── How it works ────────────────────────────────────── + _HowItWorksSection(), + const SizedBox(height: 28), + + // ── Start call button ───────────────────────────────── + ElevatedButton.icon( + onPressed: canCall ? _startCall : null, + icon: const Icon(Icons.lock_rounded, size: 20), + label: const Text('START SECURE CALL', + style: TextStyle( + fontSize: 16, + letterSpacing: 2, + fontWeight: FontWeight.bold)), + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF00C853), + disabledBackgroundColor: const Color(0xFF1A3020), + padding: const EdgeInsets.symmetric(vertical: 18), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14)), + ), + ), + const SizedBox(height: 16), + Center( + child: Text( + canCall + ? 'First start a normal phone call, then press the button' + : _fingerprint == null + ? 'Set a passphrase in ⚙ Settings to enable' + : 'Microphone permission required', + textAlign: TextAlign.center, + style: const TextStyle( + color: Colors.white38, fontSize: 12, height: 1.5), + ), + ), + const SizedBox(height: 12), + ], + ), + ), + ), + ); + } +} + +// ── Sub-widgets ──────────────────────────────────────────────────────── + +class _KeyCard extends StatelessWidget { + final String? fingerprint; + final VoidCallback onTap; + const _KeyCard({required this.fingerprint, required this.onTap}); + + @override + Widget build(BuildContext context) { + final hasKey = fingerprint != null; + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(12), + child: Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: const Color(0xFF1A1A2E), + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: hasKey + ? const Color(0xFF00C853).withValues(alpha: 0.5) + : Colors.white12, + ), + ), + child: Row( + children: [ + Icon( + hasKey ? Icons.vpn_key_rounded : Icons.vpn_key_off_outlined, + color: hasKey ? const Color(0xFF00C853) : Colors.white38, + size: 28, + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + hasKey ? 'Encryption key loaded' : 'No encryption key', + style: TextStyle( + color: hasKey + ? const Color(0xFF00C853) + : Colors.white54, + fontWeight: FontWeight.w600, + ), + ), + if (hasKey) ...[ + const SizedBox(height: 4), + Text( + 'Fingerprint: $fingerprint', + style: const TextStyle( + color: Colors.white38, + fontSize: 12, + fontFamily: 'monospace', + letterSpacing: 2), + ), + ] else ...[ + const SizedBox(height: 4), + const Text('Tap to open Settings and set passphrase', + style: TextStyle(color: Colors.white30, fontSize: 12)), + ], + ], + ), + ), + const Icon(Icons.chevron_right, color: Colors.white24), + ], + ), + ), + ); + } +} + +class _WarningCard extends StatelessWidget { + final IconData icon; + final String message; + final VoidCallback onTap; + const _WarningCard( + {required this.icon, required this.message, required this.onTap}); + + @override + Widget build(BuildContext context) { + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(12), + child: Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: Colors.amber.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(12), + border: + Border.all(color: Colors.amber.withValues(alpha: 0.4)), + ), + child: Row( + children: [ + Icon(icon, color: Colors.amber, size: 22), + const SizedBox(width: 12), + Expanded( + child: Text(message, + style: const TextStyle( + color: Colors.amber, fontSize: 13, height: 1.4)), + ), + ], + ), + ), + ); + } +} + +class _HowItWorksSection extends StatelessWidget { + @override + Widget build(BuildContext context) { + const steps = [ + (Icons.phone_in_talk_rounded, + 'Start a normal cellular voice call with your peer'), + (Icons.vpn_key_rounded, + 'Both devices must have the same passphrase loaded'), + (Icons.mic, + 'Press PTT to speak — FSK audio transmits over the call'), + (Icons.hearing, + 'Tap LISTEN to receive and decode incoming voice'), + ]; + + return Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: const Color(0xFF0F0F1E), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: Colors.white10), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text('HOW TO USE', + style: TextStyle( + color: Colors.white38, fontSize: 11, letterSpacing: 2)), + const SizedBox(height: 12), + ...steps.map((s) => Padding( + padding: const EdgeInsets.only(bottom: 10), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(s.$1, color: Colors.white38, size: 16), + const SizedBox(width: 10), + Expanded( + child: Text(s.$2, + style: const TextStyle( + color: Colors.white54, + fontSize: 13, + height: 1.4))), + ], + ), + )), + ], + ), + ); + } +} diff --git a/call/lib/ui/screens/settings_screen.dart b/call/lib/ui/screens/settings_screen.dart new file mode 100644 index 0000000..e6b6b89 --- /dev/null +++ b/call/lib/ui/screens/settings_screen.dart @@ -0,0 +1,275 @@ +import 'package:flutter/material.dart'; +import '../../services/call_session.dart'; + +/// Settings / key-management screen. +/// +/// Allows the user to enter a shared passphrase and derive the AES-256 key. +/// The passphrase is never stored — only a non-reversible fingerprint is kept +/// via [CallSession.getSavedFingerprint]. +class SettingsScreen extends StatefulWidget { + final CallSession session; + const SettingsScreen({super.key, required this.session}); + + @override + State createState() => _SettingsScreenState(); +} + +class _SettingsScreenState extends State { + final _ctrl = TextEditingController(); + final _formKey = GlobalKey(); + + bool _loading = false; + bool _obscure = true; + String? _fingerprint; + String? _errorMsg; + + @override + void initState() { + super.initState(); + _loadFingerprint(); + } + + Future _loadFingerprint() async { + final fp = await widget.session.getSavedFingerprint(); + if (mounted) setState(() => _fingerprint = fp); + } + + Future _deriveKey() async { + if (!(_formKey.currentState?.validate() ?? false)) return; + setState(() { _loading = true; _errorMsg = null; }); + + // Capture messenger before async gap to avoid BuildContext-across-await lint. + final messenger = ScaffoldMessenger.of(context); + + final ok = await widget.session.loadPassphrase(_ctrl.text.trim()); + + if (!mounted) return; + if (ok) { + await _loadFingerprint(); + messenger.showSnackBar( + const SnackBar( + content: Text('Key derived successfully'), + backgroundColor: Color(0xFF00C853), + ), + ); + } else { + setState(() => _errorMsg = widget.session.lastError); + } + setState(() => _loading = false); + } + + Future _clearKey() async { + await widget.session.clearKey(); + _ctrl.clear(); + if (mounted) { + setState(() => _fingerprint = null); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Key cleared')), + ); + } + } + + @override + void dispose() { + _ctrl.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFF0D0D1A), + appBar: AppBar( + backgroundColor: const Color(0xFF0D0D1A), + title: const Text('Encryption Key', + style: TextStyle(color: Colors.white, letterSpacing: 1.5)), + iconTheme: const IconThemeData(color: Colors.white), + ), + body: SingleChildScrollView( + padding: const EdgeInsets.all(24), + child: Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // ── Info card ───────────────────────────────────────── + Container( + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: const Color(0xFF1A1A2E), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: Colors.blueAccent.withValues(alpha: 0.3)), + ), + child: const Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row(children: [ + Icon(Icons.lock_outline, color: Colors.blueAccent, size: 18), + SizedBox(width: 8), + Text('Pre-shared key setup', + style: TextStyle( + color: Colors.blueAccent, + fontWeight: FontWeight.bold)), + ]), + SizedBox(height: 8), + Text( + 'Both devices must use the SAME passphrase before ' + 'starting a call. The passphrase is converted to a ' + '256-bit AES key using PBKDF2-HMAC-SHA256 ' + '(100 000 iterations).\n\n' + 'Exchange the passphrase over a separate secure channel ' + '(in person, encrypted message, etc.).', + style: TextStyle(color: Colors.white60, height: 1.5, fontSize: 13), + ), + ], + ), + ), + + const SizedBox(height: 28), + + // ── Passphrase field ────────────────────────────────── + TextFormField( + controller: _ctrl, + obscureText: _obscure, + style: const TextStyle(color: Colors.white, letterSpacing: 1.2), + decoration: InputDecoration( + labelText: 'Shared passphrase', + labelStyle: const TextStyle(color: Colors.white54), + filled: true, + fillColor: const Color(0xFF1A1A2E), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide.none), + suffixIcon: IconButton( + icon: Icon( + _obscure ? Icons.visibility_off : Icons.visibility, + color: Colors.white38), + onPressed: () => setState(() => _obscure = !_obscure), + ), + ), + validator: (v) { + if (v == null || v.trim().isEmpty) return 'Enter a passphrase'; + if (v.trim().length < 8) return 'Minimum 8 characters'; + return null; + }, + ), + + if (_errorMsg != null) ...[ + const SizedBox(height: 10), + Text(_errorMsg!, + style: const TextStyle(color: Colors.redAccent, fontSize: 13)), + ], + + const SizedBox(height: 20), + + // ── Derive button ───────────────────────────────────── + ElevatedButton.icon( + onPressed: _loading ? null : _deriveKey, + icon: _loading + ? const SizedBox( + width: 18, height: 18, + child: CircularProgressIndicator(strokeWidth: 2, + color: Colors.white)) + : const Icon(Icons.vpn_key_rounded), + label: const Text('DERIVE KEY', + style: TextStyle(letterSpacing: 1.5)), + style: ElevatedButton.styleFrom( + backgroundColor: Colors.blueAccent, + padding: const EdgeInsets.symmetric(vertical: 14), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10)), + ), + ), + + const SizedBox(height: 32), + + // ── Key fingerprint ─────────────────────────────────── + if (_fingerprint != null) ...[ + const Text('ACTIVE KEY FINGERPRINT', + style: TextStyle( + color: Colors.white38, fontSize: 11, letterSpacing: 1.5)), + const SizedBox(height: 8), + Container( + padding: + const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + decoration: BoxDecoration( + color: const Color(0xFF1A1A2E), + borderRadius: BorderRadius.circular(10), + border: Border.all(color: const Color(0xFF00C853).withValues(alpha: 0.4)), + ), + child: Row( + children: [ + const Icon(Icons.fingerprint, + color: Color(0xFF00C853), size: 20), + const SizedBox(width: 12), + Text( + _fingerprint!, + style: const TextStyle( + color: Color(0xFF00C853), + fontFamily: 'monospace', + fontSize: 18, + letterSpacing: 4, + ), + ), + ], + ), + ), + const SizedBox(height: 8), + const Text( + 'Show this fingerprint to your peer — it must match on both devices.', + style: TextStyle(color: Colors.white38, fontSize: 12, height: 1.4), + ), + const SizedBox(height: 24), + OutlinedButton.icon( + onPressed: _clearKey, + icon: const Icon(Icons.delete_outline, color: Colors.redAccent), + label: const Text('CLEAR KEY', + style: TextStyle(color: Colors.redAccent, letterSpacing: 1.5)), + style: OutlinedButton.styleFrom( + side: const BorderSide(color: Colors.redAccent), + padding: const EdgeInsets.symmetric(vertical: 12), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10)), + ), + ), + ], + + const SizedBox(height: 40), + + // ── Technical info ──────────────────────────────────── + const Divider(color: Colors.white12), + const SizedBox(height: 16), + const Text('SYSTEM PARAMETERS', + style: TextStyle( + color: Colors.white24, fontSize: 11, letterSpacing: 1.5)), + const SizedBox(height: 12), + _paramRow('Cipher', 'AES-256-CTR'), + _paramRow('KDF', 'PBKDF2-HMAC-SHA256 (100k iter)'), + _paramRow('FEC', 'Reed-Solomon RS(15,11) GF(16)'), + _paramRow('Modulation', '4-FSK 600 baud 1200 bps'), + _paramRow('Voice', 'LPC-10 ~360 bps 200 ms frames'), + _paramRow('Channel', 'Acoustic FSK over SIM call'), + ], + ), + ), + ), + ); + } + + static Widget _paramRow(String label, String value) => Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(label, + style: + const TextStyle(color: Colors.white38, fontSize: 12)), + Text(value, + style: const TextStyle( + color: Colors.white60, + fontSize: 12, + fontFamily: 'monospace')), + ], + ), + ); +} diff --git a/call/lib/ui/widgets/level_meter.dart b/call/lib/ui/widgets/level_meter.dart new file mode 100644 index 0000000..71eccb2 --- /dev/null +++ b/call/lib/ui/widgets/level_meter.dart @@ -0,0 +1,87 @@ +import 'package:flutter/material.dart'; + +/// Vertical or horizontal audio level meter. +/// +/// [level] is a normalised value 0.0 – 1.0. +/// Colour transitions green → amber → red above 0.7. +class LevelMeter extends StatelessWidget { + final double level; + final double width; + final double height; + final bool vertical; + + const LevelMeter({ + super.key, + required this.level, + this.width = 24, + this.height = 120, + this.vertical = true, + }); + + @override + Widget build(BuildContext context) { + final clamped = level.clamp(0.0, 1.0); + return SizedBox( + width: width, + height: height, + child: CustomPaint( + painter: _LevelPainter(level: clamped, vertical: vertical), + ), + ); + } +} + +class _LevelPainter extends CustomPainter { + final double level; + final bool vertical; + const _LevelPainter({required this.level, required this.vertical}); + + @override + void paint(Canvas canvas, Size size) { + // Background. + canvas.drawRect( + Rect.fromLTWH(0, 0, size.width, size.height), + Paint()..color = const Color(0xFF1A1A2E), + ); + + // Filled bar. + final barColor = level < 0.6 + ? const Color(0xFF00C853) // green + : level < 0.8 + ? const Color(0xFFFFAB00) // amber + : const Color(0xFFD50000); // red + + final paint = Paint()..color = barColor; + + if (vertical) { + final fillH = size.height * level; + canvas.drawRect( + Rect.fromLTWH(0, size.height - fillH, size.width, fillH), + paint, + ); + } else { + final fillW = size.width * level; + canvas.drawRect( + Rect.fromLTWH(0, 0, fillW, size.height), + paint, + ); + } + + // Tick marks at 25 %, 50 %, 75 %. + final tickPaint = Paint() + ..color = Colors.white24 + ..strokeWidth = 1; + for (final frac in [0.25, 0.50, 0.75]) { + if (vertical) { + final y = size.height * (1.0 - frac); + canvas.drawLine(Offset(0, y), Offset(size.width, y), tickPaint); + } else { + final x = size.width * frac; + canvas.drawLine(Offset(x, 0), Offset(x, size.height), tickPaint); + } + } + } + + @override + bool shouldRepaint(_LevelPainter old) => old.level != level; +} diff --git a/call/lib/ui/widgets/status_indicator.dart b/call/lib/ui/widgets/status_indicator.dart new file mode 100644 index 0000000..6eb1c11 --- /dev/null +++ b/call/lib/ui/widgets/status_indicator.dart @@ -0,0 +1,104 @@ +import 'package:flutter/material.dart'; +import '../../services/call_session.dart'; + +/// Animated status dot + label reflecting the current [SessionState]. +class StatusIndicator extends StatefulWidget { + final SessionState state; + + const StatusIndicator({super.key, required this.state}); + + @override + State createState() => _StatusIndicatorState(); +} + +class _StatusIndicatorState extends State + with SingleTickerProviderStateMixin { + late final AnimationController _blink; + + @override + void initState() { + super.initState(); + _blink = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 600), + )..repeat(reverse: true); + } + + @override + void dispose() { + _blink.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final cfg = _config(widget.state); + final shouldBlink = widget.state == SessionState.transmitting || + widget.state == SessionState.receiving; + + Widget dot = AnimatedBuilder( + animation: _blink, + builder: (_, __) { + final opacity = shouldBlink ? (0.4 + 0.6 * _blink.value) : 1.0; + return Opacity( + opacity: opacity, + child: Container( + width: 14, + height: 14, + decoration: BoxDecoration( + color: cfg.color, + shape: BoxShape.circle, + boxShadow: [ + BoxShadow( + color: cfg.color.withValues(alpha: 0.6), + blurRadius: 8, + spreadRadius: 2, + ), + ], + ), + ), + ); + }, + ); + + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + dot, + const SizedBox(width: 8), + Text( + cfg.label, + style: TextStyle( + color: cfg.color, + fontWeight: FontWeight.w600, + fontSize: 13, + letterSpacing: 1.2, + ), + ), + ], + ); + } + + static _StatusConfig _config(SessionState s) { + switch (s) { + case SessionState.noKey: + return const _StatusConfig(Colors.grey, 'NO KEY'); + case SessionState.keyLoaded: + return const _StatusConfig(Colors.blueAccent, 'KEY READY'); + case SessionState.inCall: + return const _StatusConfig(Color(0xFF00C853), 'IN CALL'); + case SessionState.transmitting: + return const _StatusConfig(Color(0xFFFF6D00), 'TRANSMITTING'); + case SessionState.receiving: + return const _StatusConfig(Color(0xFF00B0FF), 'RECEIVING'); + case SessionState.error: + return const _StatusConfig(Colors.red, 'ERROR'); + } + } +} + +class _StatusConfig { + final Color color; + final String label; + const _StatusConfig(this.color, this.label); +} diff --git a/call/lib/utils/audio_math.dart b/call/lib/utils/audio_math.dart new file mode 100644 index 0000000..8d0f356 --- /dev/null +++ b/call/lib/utils/audio_math.dart @@ -0,0 +1,228 @@ +import 'dart:math' as math; +import 'dart:typed_data'; + +/// Stateless DSP utility functions used by the modem and voice codec. +abstract final class AudioMath { + // ── Window functions ────────────────────────────────────────────── + + /// Hamming window of length [n]. + static Float64List hammingWindow(int n) { + final w = Float64List(n); + final factor = 2.0 * math.pi / (n - 1); + for (int i = 0; i < n; i++) { + w[i] = 0.54 - 0.46 * math.cos(i * factor); + } + return w; + } + + /// Hann (Hanning) window of length [n]. + static Float64List hannWindow(int n) { + final w = Float64List(n); + final factor = 2.0 * math.pi / (n - 1); + for (int i = 0; i < n; i++) { + w[i] = 0.5 * (1.0 - math.cos(i * factor)); + } + + return w; + } + + // ── Signal statistics ───────────────────────────────────────────── + + /// Root-mean-square of [samples] (all values). + static double rms(Float64List samples) { + double sum = 0.0; + for (final s in samples) { sum += s * s; } + return math.sqrt(sum / samples.length); + } + + /// Short-time energy (sum of squares over [samples]). + static double energy(Float64List samples) { + double e = 0.0; + for (final s in samples) { e += s * s; } + return e; + } + + /// Zero-crossing rate of [samples] (crossings per sample). + static double zeroCrossingRate(Float64List samples) { + int crossings = 0; + for (int i = 1; i < samples.length; i++) { + if ((samples[i] >= 0) != (samples[i - 1] >= 0)) crossings++; + } + return crossings / samples.length; + } + + // ── Int16 ↔ Float64 conversion ──────────────────────────────────── + + /// Convert raw 16-bit PCM [bytes] (little-endian Int16) to normalised + /// Float64 in [-1, +1]. + static Float64List int16BytesToFloat(Uint8List bytes) { + final count = bytes.length >> 1; + final out = Float64List(count); + final view = ByteData.sublistView(bytes); + for (int i = 0; i < count; i++) { + out[i] = view.getInt16(i * 2, Endian.little) / 32768.0; + } + return out; + } + + /// Convert normalised Float64 [-1, +1] to Int16 LE bytes. + static Uint8List floatToInt16Bytes(Float64List samples) { + final out = Uint8List(samples.length * 2); + final view = ByteData.sublistView(out); + for (int i = 0; i < samples.length; i++) { + final clamped = samples[i].clamp(-1.0, 1.0); + view.setInt16(i * 2, (clamped * 32767).round(), Endian.little); + } + return out; + } + + // ── Filter ──────────────────────────────────────────────────────── + + /// Apply a simple first-order high-pass (pre-emphasis) filter in-place. + /// y[n] = x[n] − alpha·x[n−1] + static void preEmphasis(Float64List samples, double alpha, + [double prevSample = 0.0]) { + double prev = prevSample; + for (int i = 0; i < samples.length; i++) { + final cur = samples[i]; + samples[i] = cur - alpha * prev; + prev = cur; + } + } + + /// Apply de-emphasis (inverse of pre-emphasis) in-place. + /// y[n] = x[n] + alpha·y[n−1] + static void deEmphasis(Float64List samples, double alpha, + [double prevOut = 0.0]) { + double prev = prevOut; + for (int i = 0; i < samples.length; i++) { + final cur = samples[i] + alpha * prev; + samples[i] = cur; + prev = cur; + } + } + + // ── Autocorrelation ─────────────────────────────────────────────── + + /// Compute biased autocorrelation of [frame] at lags 0..maxLag (inclusive). + /// Result is a Float64List of length maxLag+1. + static Float64List autocorrelation(Float64List frame, int maxLag) { + final n = frame.length; + final r = Float64List(maxLag + 1); + for (int lag = 0; lag <= maxLag; lag++) { + double sum = 0.0; + for (int i = 0; i < n - lag; i++) { + sum += frame[i] * frame[i + lag]; + } + r[lag] = sum; + } + return r; + } + + // ── AMDF pitch detector ─────────────────────────────────────────── + + /// Average Magnitude Difference Function. + /// Returns the pitch period in samples (within [minP, maxP]) or 0 if + /// the frame appears unvoiced (no clear minimum in AMDF). + static int amdfPitch(Float64List frame, int minP, int maxP) { + final n = frame.length; + double minAmdf = double.infinity; + int bestTau = 0; + + for (int tau = minP; tau <= maxP; tau++) { + double sum = 0.0; + final len = n - tau; + for (int i = 0; i < len; i++) { + sum += (frame[i] - frame[i + tau]).abs(); + } + final amdf = sum / len; + if (amdf < minAmdf) { + minAmdf = amdf; + bestTau = tau; + } + } + + // If minimum AMDF is more than 60 % of mean magnitude, frame is unvoiced. + double meanMag = 0.0; + for (final s in frame) { meanMag += s.abs(); } + meanMag /= n; + + if (meanMag < 1e-6 || minAmdf > 0.6 * meanMag) return 0; + return bestTau; + } + + // ── Goertzel single-tone DFT ────────────────────────────────────── + + /// Compute the squared magnitude of DFT bin for frequency [freqHz] over + /// [samples]. More efficient than full FFT for a single frequency. + /// + /// Phase: Q0, Q1, Q2 Goertzel state variables. + /// coeff = 2·cos(2π·f/fs) + static double goertzelMagnitudeSq( + Float64List samples, double freqHz, int sampleRate) { + final coeff = 2.0 * math.cos(2.0 * math.pi * freqHz / sampleRate); + double q0 = 0.0, q1 = 0.0, q2 = 0.0; + for (final s in samples) { + q0 = coeff * q1 - q2 + s; + q2 = q1; + q1 = q0; + } + return q1 * q1 + q2 * q2 - q1 * q2 * coeff; + } + + // ── CRC-16 (CCITT / X.25 polynomial 0x1021) ────────────────────── + + static const int _crcPoly = 0x1021; + + /// Compute CRC-16/CCITT over [data]. Initial value 0xFFFF. + static int crc16(List data) { + int crc = 0xFFFF; + for (final byte in data) { + crc ^= (byte & 0xFF) << 8; + for (int i = 0; i < 8; i++) { + if ((crc & 0x8000) != 0) { + crc = ((crc << 1) ^ _crcPoly) & 0xFFFF; + } else { + crc = (crc << 1) & 0xFFFF; + } + } + } + return crc; + } + + // ── Clamp / normalise ───────────────────────────────────────────── + + /// Soft-clip [x] to [-1, 1] using tanh to avoid hard saturation. + static double softClip(double x) => math.max(-1.0, math.min(1.0, x)); + + /// Normalise [samples] to peak amplitude 1.0 (in-place). + static void normalise(Float64List samples) { + double peak = 0.0; + for (final s in samples) { + final a = s.abs(); + if (a > peak) peak = a; + } + if (peak < 1e-10) return; + final scale = 1.0 / peak; + for (int i = 0; i < samples.length; i++) { samples[i] *= scale; } + } + + // ── Pseudo-random noise (for unvoiced excitation) ───────────────── + + static final _rng = math.Random(); + + /// Return a Float64List of [n] samples of white Gaussian noise + /// approximated by Box-Muller transform, amplitude ≈ 0.3 RMS. + static Float64List whiteNoise(int n, [double amplitude = 0.3]) { + final out = Float64List(n); + for (int i = 0; i < n; i += 2) { + final u1 = _rng.nextDouble(); + final u2 = _rng.nextDouble(); + final r = math.sqrt(-2.0 * math.log(u1.clamp(1e-12, 1.0))); + final theta = 2.0 * math.pi * u2; + out[i] = amplitude * r * math.cos(theta); + if (i + 1 < n) out[i + 1] = amplitude * r * math.sin(theta); + } + return out; + } +} diff --git a/call/lib/utils/constants.dart b/call/lib/utils/constants.dart new file mode 100644 index 0000000..bf3baed --- /dev/null +++ b/call/lib/utils/constants.dart @@ -0,0 +1,115 @@ +// ignore_for_file: constant_identifier_names +import 'dart:math' as math; + +/// All system-wide numeric constants for the secure-voice pipeline. +/// +/// Design target: +/// modem gross rate : 1 200 bps (4-FSK, 600 baud, 2 bits/symbol) +/// RS(15,11) FEC net : ~880 bps +/// voice codec : ~360 bps (LPC, 200 ms super-frames) +/// one-way latency : ~250 ms (frame + processing + buffer) +abstract final class C { + // ── Sample rate ──────────────────────────────────────────────────── + /// Must match the cellular audio path (PCM 8 kHz narrowband). + static const int sampleRate = 8000; + + // ── 4-FSK modem ──────────────────────────────────────────────────── + /// Symbol rate in baud. 600 baud × 2 bits/symbol = 1 200 bps gross. + static const int baudRate = 600; + + /// Samples per symbol as a float (8000 / 600 = 13.333…). + /// The modulator uses a phase accumulator; the demodulator uses an + /// early–late gate timing recovery loop to handle the fraction. + static const double samplesPerSymbol = sampleRate / baudRate; + + /// 4-FSK tone frequencies (Hz). Spaced 400 Hz apart, centred in + /// the 300–3400 Hz cellular pass-band; chosen to survive AMR-NB codec. + /// symbol dibit → frequency + /// 00 → tone0 01 → tone1 10 → tone2 11 → tone3 + static const List fskToneHz = [1000.0, 1400.0, 1800.0, 2200.0]; + + /// Amplitude of the transmitted FSK signal (0–1 normalised). + /// Kept below 0.7 to avoid clipping after phone mic AGC compresses it. + static const double txAmplitude = 0.60; + + /// Preamble: alternating dibit 00/11 repeated this many times before + /// each packet. Used by the demodulator for timing acquisition. + static const int preambleSymbols = 24; + + /// Two-byte wire sync-word placed after preamble (0x5A, 0xA5). + static const List syncWord = [0x5A, 0xA5]; + + // ── Packet layout (pre-FEC plaintext frame) ──────────────────────── + /// Bytes: [SYNC(2)] [SEQ(2)] [TYPE(1)] [LEN(1)] [PAYLOAD(11)] [CRC16(2)] + static const int pktSyncLen = 2; + static const int pktSeqLen = 2; + static const int pktTypeLen = 1; + static const int pktLenLen = 1; + static const int pktPayloadLen = 11; // encrypted voice frame bytes + static const int pktCrcLen = 2; + static const int pktTotalBytes = pktSyncLen + pktSeqLen + pktTypeLen + + pktLenLen + pktPayloadLen + pktCrcLen; // 19 B + + /// Packet type codes. + static const int pkTypeVoice = 0x01; + static const int pkTypeControl = 0x02; + static const int pkTypeHandshake = 0x03; + static const int pkTypePing = 0x04; + + // ── Reed-Solomon RS(15,11) over GF(16) ──────────────────────────── + /// RS codeword length n (nibbles). + static const int rsN = 15; + /// RS data symbols per codeword k (nibbles). + static const int rsK = 11; + /// RS parity symbols per codeword (n-k). + static const int rsParity = rsN - rsK; // 4 + /// Correction capability: t = parity/2 = 2 nibble errors per codeword. + static const int rsT = rsParity ~/ 2; + + // ── LPC voice codec ──────────────────────────────────────────────── + /// Sub-frame size (samples). One LPC analysis frame = 20 ms at 8 kHz. + static const int lpcSubframeSamples = 160; // 20 ms + + /// Number of sub-frames in one super-frame (transmitted as a packet). + static const int lpcSubframesPerSuper = 10; // 200 ms total + + /// LPC analysis order (number of predictor coefficients). + static const int lpcOrder = 10; + + /// Minimum pitch period in samples (max fundamental ~400 Hz). + static const int pitchMinSamples = 20; + + /// Maximum pitch period in samples (min fundamental ~50 Hz). + static const int pitchMaxSamples = 160; + + /// Pre-emphasis coefficient. Applied as s'[n] = s[n] - alpha·s[n-1]. + static const double preEmphasis = 0.97; + + // ── AES-256-CTR ──────────────────────────────────────────────────── + /// Key length in bytes. + static const int aesKeyBytes = 32; + /// Nonce length in bytes (packed from session-ID + packet-seq). + static const int aesNonceBytes = 16; // AES block size = 128 bits + + // ── PBKDF2 ───────────────────────────────────────────────────────── + static const int pbkdf2Iterations = 100000; + static const int pbkdf2SaltBytes = 16; + + // ── AGC / Signal conditioning ────────────────────────────────────── + /// Target RMS level for received signal (normalised 0–1). + static const double agcTargetRms = 0.15; + /// AGC attack time constant (samples). Fast attack. + static const double agcAlpha = 0.001; + + // ── Goertzel window length (must be ≥ samplesPerSymbol) ─────────── + /// We snap to 14 integer samples which is the nearest integer above + /// samplesPerSymbol. Timing recovery compensates for the 0.67 sample drift. + static const int goertzelWindow = 14; + + // ── Derived constants ────────────────────────────────────────────── + /// Pre-computed Goertzel coefficients for each FSK tone. + /// coeff[i] = 2 · cos(2π · f_i / sampleRate) + static final List goertzelCoeff = fskToneHz + .map((f) => 2.0 * math.cos(2.0 * math.pi * f / sampleRate)) + .toList(growable: false); +} diff --git a/call/linux/.gitignore b/call/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/call/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/call/linux/CMakeLists.txt b/call/linux/CMakeLists.txt new file mode 100644 index 0000000..daf72e3 --- /dev/null +++ b/call/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "call") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.call") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/call/linux/flutter/CMakeLists.txt b/call/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/call/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/call/linux/flutter/generated_plugin_registrant.cc b/call/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..e71a16d --- /dev/null +++ b/call/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void fl_register_plugins(FlPluginRegistry* registry) { +} diff --git a/call/linux/flutter/generated_plugin_registrant.h b/call/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/call/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/call/linux/flutter/generated_plugins.cmake b/call/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..2e1de87 --- /dev/null +++ b/call/linux/flutter/generated_plugins.cmake @@ -0,0 +1,23 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/call/linux/runner/CMakeLists.txt b/call/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/call/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/call/linux/runner/main.cc b/call/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/call/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/call/linux/runner/my_application.cc b/call/linux/runner/my_application.cc new file mode 100644 index 0000000..3321798 --- /dev/null +++ b/call/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "call"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "call"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments( + project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, + gchar*** arguments, + int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = + my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/call/linux/runner/my_application.h b/call/linux/runner/my_application.h new file mode 100644 index 0000000..db16367 --- /dev/null +++ b/call/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, + my_application, + MY, + APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/call/macos/.gitignore b/call/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/call/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/call/macos/Flutter/Flutter-Debug.xcconfig b/call/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/call/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/call/macos/Flutter/Flutter-Release.xcconfig b/call/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/call/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/call/macos/Flutter/GeneratedPluginRegistrant.swift b/call/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..724bb2a --- /dev/null +++ b/call/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,12 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import shared_preferences_foundation + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) +} diff --git a/call/macos/Runner.xcodeproj/project.pbxproj b/call/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..daf58e9 --- /dev/null +++ b/call/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,705 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 54; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* call.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "call.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* call.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* call.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.call.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/call.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/call"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.call.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/call.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/call"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.call.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/call.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/call"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.15; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/call/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/call/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/call/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/call/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/call/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..04c7173 --- /dev/null +++ b/call/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,99 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/call/macos/Runner.xcworkspace/contents.xcworkspacedata b/call/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/call/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/call/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/call/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/call/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/call/macos/Runner/AppDelegate.swift b/call/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..b3c1761 --- /dev/null +++ b/call/macos/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..82b6f9d Binary files /dev/null and b/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..13b35eb Binary files /dev/null and b/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..0a3f5fa Binary files /dev/null and b/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..bdb5722 Binary files /dev/null and b/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..f083318 Binary files /dev/null and b/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..326c0e7 Binary files /dev/null and b/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..2f1632c Binary files /dev/null and b/call/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/call/macos/Runner/Base.lproj/MainMenu.xib b/call/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/call/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/call/macos/Runner/Configs/AppInfo.xcconfig b/call/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..9f1c4be --- /dev/null +++ b/call/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = call + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = com.example.call + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 com.example. All rights reserved. diff --git a/call/macos/Runner/Configs/Debug.xcconfig b/call/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/call/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/call/macos/Runner/Configs/Release.xcconfig b/call/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..dff4f49 --- /dev/null +++ b/call/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/call/macos/Runner/Configs/Warnings.xcconfig b/call/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/call/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/call/macos/Runner/DebugProfile.entitlements b/call/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..dddb8a3 --- /dev/null +++ b/call/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/call/macos/Runner/Info.plist b/call/macos/Runner/Info.plist new file mode 100644 index 0000000..4789daa --- /dev/null +++ b/call/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/call/macos/Runner/MainFlutterWindow.swift b/call/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..3cc05eb --- /dev/null +++ b/call/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/call/macos/Runner/Release.entitlements b/call/macos/Runner/Release.entitlements new file mode 100644 index 0000000..852fa1a --- /dev/null +++ b/call/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/call/macos/RunnerTests/RunnerTests.swift b/call/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..61f3bd1 --- /dev/null +++ b/call/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Cocoa +import FlutterMacOS +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/call/pubspec.lock b/call/pubspec.lock new file mode 100644 index 0000000..c728392 --- /dev/null +++ b/call/pubspec.lock @@ -0,0 +1,418 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + async: + dependency: transitive + description: + name: async + sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb" + url: "https://pub.dev" + source: hosted + version: "2.13.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3f41d009ba7172d5ff9be5f6e6e6abb4300e263aab8866d2a0842ed2a70f8f0c" + url: "https://pub.dev" + source: hosted + version: "4.0.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + js: + dependency: transitive + description: + name: js + sha256: "53385261521cc4a0c4658fd0ad07a7d14591cf8fc33abbceae306ddb974888dc" + url: "https://pub.dev" + source: hosted + version: "0.7.2" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "976c774dd944a42e83e2467f4cc670daef7eed6295b10b36ae8c85bcbf828235" + url: "https://pub.dev" + source: hosted + version: "4.0.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: "12956d0ad8390bbcc63ca2e1469c0619946ccb52809807067a7020d57e647aa6" + url: "https://pub.dev" + source: hosted + version: "0.12.18" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + meta: + dependency: transitive + description: + name: meta + sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394" + url: "https://pub.dev" + source: hosted + version: "1.17.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + permission_handler: + dependency: "direct main" + description: + name: permission_handler + sha256: "59adad729136f01ea9e35a48f5d1395e25cba6cea552249ddbe9cf950f5d7849" + url: "https://pub.dev" + source: hosted + version: "11.4.0" + permission_handler_android: + dependency: transitive + description: + name: permission_handler_android + sha256: d3971dcdd76182a0c198c096b5db2f0884b0d4196723d21a866fc4cdea057ebc + url: "https://pub.dev" + source: hosted + version: "12.1.0" + permission_handler_apple: + dependency: transitive + description: + name: permission_handler_apple + sha256: f000131e755c54cf4d84a5d8bd6e4149e262cc31c5a8b1d698de1ac85fa41023 + url: "https://pub.dev" + source: hosted + version: "9.4.7" + permission_handler_html: + dependency: transitive + description: + name: permission_handler_html + sha256: "38f000e83355abb3392140f6bc3030660cfaef189e1f87824facb76300b4ff24" + url: "https://pub.dev" + source: hosted + version: "0.1.3+5" + permission_handler_platform_interface: + dependency: transitive + description: + name: permission_handler_platform_interface + sha256: eb99b295153abce5d683cac8c02e22faab63e50679b937fa1bf67d58bb282878 + url: "https://pub.dev" + source: hosted + version: "4.3.0" + permission_handler_windows: + dependency: transitive + description: + name: permission_handler_windows + sha256: "1a790728016f79a41216d88672dbc5df30e686e811ad4e698bfc51f76ad91f1e" + url: "https://pub.dev" + source: hosted + version: "0.2.1" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pointycastle: + dependency: "direct main" + description: + name: pointycastle + sha256: "4be0097fcf3fd3e8449e53730c631200ebc7b88016acecab2b0da2f0149222fe" + url: "https://pub.dev" + source: hosted + version: "3.9.1" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: "2939ae520c9024cb197fc20dee269cd8cdbf564c8b5746374ec6cacdc5169e64" + url: "https://pub.dev" + source: hosted + version: "2.5.4" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: "8374d6200ab33ac99031a852eba4c8eb2170c4bf20778b3e2c9eccb45384fb41" + url: "https://pub.dev" + source: hosted + version: "2.4.21" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "4e7eaffc2b17ba398759f1151415869a34771ba11ebbccd1b0145472a619a64f" + url: "https://pub.dev" + source: hosted + version: "2.5.6" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: "19a78f63e83d3a61f00826d09bc2f60e191bf3504183c001262be6ac75589fb8" + url: "https://pub.dev" + source: hosted + version: "0.7.8" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "45caa6c5917fa127b5dbcfbd1fa60b14e583afdc08bfc96dda38886ca252eb60" + url: "https://pub.dev" + source: hosted + version: "15.0.2" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" +sdks: + dart: ">=3.9.0 <4.0.0" + flutter: ">=3.35.0" diff --git a/call/pubspec.yaml b/call/pubspec.yaml new file mode 100644 index 0000000..1838f1c --- /dev/null +++ b/call/pubspec.yaml @@ -0,0 +1,25 @@ +name: call +description: "Secure voice communication over a standard SIM cellular call using 4-FSK modulation, LPC voice codec, AES-256-CTR encryption, and Reed-Solomon FEC." +publish_to: 'none' +version: 1.0.0+1 + +environment: + sdk: '>=3.0.0 <4.0.0' + +dependencies: + flutter: + sdk: flutter + # AES-256-CTR block cipher + PBKDF2-SHA256 key derivation + pointycastle: ^3.9.1 + # Runtime permission requests (RECORD_AUDIO, MODIFY_AUDIO_SETTINGS) + permission_handler: ^11.3.1 + # Persistent settings storage (shared key hash, session params) + shared_preferences: ^2.2.3 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^4.0.0 + +flutter: + uses-material-design: true diff --git a/call/web/favicon.png b/call/web/favicon.png new file mode 100644 index 0000000..8aaa46a Binary files /dev/null and b/call/web/favicon.png differ diff --git a/call/web/icons/Icon-192.png b/call/web/icons/Icon-192.png new file mode 100644 index 0000000..b749bfe Binary files /dev/null and b/call/web/icons/Icon-192.png differ diff --git a/call/web/icons/Icon-512.png b/call/web/icons/Icon-512.png new file mode 100644 index 0000000..88cfd48 Binary files /dev/null and b/call/web/icons/Icon-512.png differ diff --git a/call/web/icons/Icon-maskable-192.png b/call/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..eb9b4d7 Binary files /dev/null and b/call/web/icons/Icon-maskable-192.png differ diff --git a/call/web/icons/Icon-maskable-512.png b/call/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..d69c566 Binary files /dev/null and b/call/web/icons/Icon-maskable-512.png differ diff --git a/call/web/index.html b/call/web/index.html new file mode 100644 index 0000000..70acc8a --- /dev/null +++ b/call/web/index.html @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + call + + + + + + + diff --git a/call/web/manifest.json b/call/web/manifest.json new file mode 100644 index 0000000..7ca1c7a --- /dev/null +++ b/call/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "call", + "short_name": "call", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/call/windows/.gitignore b/call/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/call/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/call/windows/CMakeLists.txt b/call/windows/CMakeLists.txt new file mode 100644 index 0000000..561bcc6 --- /dev/null +++ b/call/windows/CMakeLists.txt @@ -0,0 +1,108 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(call LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "call") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/call/windows/flutter/CMakeLists.txt b/call/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/call/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/call/windows/flutter/generated_plugin_registrant.cc b/call/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..48de52b --- /dev/null +++ b/call/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,14 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + PermissionHandlerWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("PermissionHandlerWindowsPlugin")); +} diff --git a/call/windows/flutter/generated_plugin_registrant.h b/call/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/call/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/call/windows/flutter/generated_plugins.cmake b/call/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..0e69e40 --- /dev/null +++ b/call/windows/flutter/generated_plugins.cmake @@ -0,0 +1,24 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + permission_handler_windows +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/call/windows/runner/CMakeLists.txt b/call/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..394917c --- /dev/null +++ b/call/windows/runner/CMakeLists.txt @@ -0,0 +1,40 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/call/windows/runner/Runner.rc b/call/windows/runner/Runner.rc new file mode 100644 index 0000000..412eab9 --- /dev/null +++ b/call/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "call" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "call" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "call.exe" "\0" + VALUE "ProductName", "call" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/call/windows/runner/flutter_window.cpp b/call/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..955ee30 --- /dev/null +++ b/call/windows/runner/flutter_window.cpp @@ -0,0 +1,71 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/call/windows/runner/flutter_window.h b/call/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/call/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/call/windows/runner/main.cpp b/call/windows/runner/main.cpp new file mode 100644 index 0000000..98ce026 --- /dev/null +++ b/call/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"call", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/call/windows/runner/resource.h b/call/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/call/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/call/windows/runner/resources/app_icon.ico b/call/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000..c04e20c Binary files /dev/null and b/call/windows/runner/resources/app_icon.ico differ diff --git a/call/windows/runner/runner.exe.manifest b/call/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/call/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/call/windows/runner/utils.cpp b/call/windows/runner/utils.cpp new file mode 100644 index 0000000..3a0b465 --- /dev/null +++ b/call/windows/runner/utils.cpp @@ -0,0 +1,65 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + unsigned int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr) + -1; // remove the trailing null character + int input_length = (int)wcslen(utf16_string); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/call/windows/runner/utils.h b/call/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/call/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/call/windows/runner/win32_window.cpp b/call/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/call/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/call/windows/runner/win32_window.h b/call/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/call/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_