diff --git a/Front/android/app/src/main/AndroidManifest.xml b/Front/android/app/src/main/AndroidManifest.xml index 2ab0a0a..e1b1743 100644 --- a/Front/android/app/src/main/AndroidManifest.xml +++ b/Front/android/app/src/main/AndroidManifest.xml @@ -7,6 +7,9 @@ + + + + + + + + + when (call.method) { + + // ── Launcher ────────────────────────────────────────── + "openHomeSettings" -> { + try { + startActivity( + Intent(Settings.ACTION_HOME_SETTINGS) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + ) + result.success(null) + } catch (e: Exception) { + result.error("UNAVAILABLE", e.message, null) + } + } + + // ── Battery ─────────────────────────────────────────── + "getBatteryInfo" -> { + try { + val bm = getSystemService(BATTERY_SERVICE) as BatteryManager + val level = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) + val isCharging = bm.isCharging + result.success(mapOf("level" to level, "isCharging" to isCharging)) + } catch (e: Exception) { + result.error("ERROR", e.message, null) + } + } + + // ── Internet (WiFi + mobile data panel) ─────────────── + "openInternetSettings" -> { + try { + val intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY) + } else { + Intent(Settings.ACTION_WIRELESS_SETTINGS) + } + startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + result.success(null) + } catch (e: Exception) { + result.error("UNAVAILABLE", e.message, null) + } + } + + // ── Mobile Data Toggle ─────────────────────────────── + "toggleMobileData" -> { + val enable = call.argument("enable") + if (enable != null) { + setMobileDataState(enable) + result.success(null) + } else { + result.error("INVALID_ARGUMENT", "Enable status not provided", null) + } + } + "getMobileDataStatus" -> { + val isEnabled = isMobileDataEnabled() + result.success(isEnabled) + } + + // ── Accessibility Settings ─────────────────────────────── + "openAccessibilitySettings" -> { + try { + val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS) + startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + result.success(null) + } catch (e: Exception) { + result.error("UNAVAILABLE", e.message, null) + } + } + + // ── SystemSettings ─────────────────────────────── + "openSystemSettings" -> { + try { + val intent = packageManager.getLaunchIntentForPackage("com.dw.setting") + startActivity(intent) + result.success(true) + } catch (e: Exception) { + result.error("UNAVAILABLE", "تنظیمات باز نشد", null) + } + } + + // ── EngineerMode ─────────────────────────────── + "openEngineerMode" -> { + try { + // ساخت اینتنت برای باز کردن اکتیویتی مهندسی + val intent = Intent().apply { + // تنظیم پکیج و کلاس دقیق که فرستادید + setClassName("com.sprd.engineermode", "com.sprd.engineermode.EngineerModeActivity") + // اضافه کردن فلگ برای شروع اکتیویتی جدید در صورت نیاز + // flags = Intent.FLAG_ACTIVITY_NEW_TASK + } + startActivity(intent) + result.success(true) + } catch (e: Exception) { + // اگر اپلیکیشن نصب نباشد یا خطایی رخ دهد + result.error("ERROR", "خطا در باز کردن EngineerMode: ${e.message}", null) + } + } + + // ── Dialer ─────────────────────────────── + "openDialer" -> { + try { + val intent = packageManager.getLaunchIntentForPackage("com.divo.phone") + startActivity(intent) + result.success(true) + } catch (e: Exception) { + result.error("UNAVAILABLE", "شماره‌گیر در دسترس نیست", null) + } + } + + // ── bluetooth ─────────────────────────────── + "openBluetoothSettings" -> { + try { + // استفاده از روش دقیق برای باز کردن تنظیمات بلوتوث + val intent = Intent().apply { + setClassName("com.android.settings", "com.android.settings.bluetooth.BluetoothSettings") + flags = Intent.FLAG_ACTIVITY_NEW_TASK + } + startActivity(intent) + result.success(true) + } catch (e: Exception) { + result.error("UNAVAILABLE", "تنظیمات بلوتوث باز نشد", null) + } + } + + // ── WiFi settings page ──────────────────────────────── + "openWifiSettings" -> { + try { + startActivity( + Intent(Settings.ACTION_WIFI_SETTINGS) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + ) + result.success(null) + } catch (e: Exception) { + result.error("UNAVAILABLE", e.message, null) + } + } + + // ── WiFi scan list ──────────────────────────────────── + "getWifiList" -> { + try { + val wm = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager + if (!wm.isWifiEnabled) { + result.success(emptyList()) + return@setMethodCallHandler + } + @Suppress("DEPRECATION") + wm.startScan() + @Suppress("DEPRECATION") + val list = wm.scanResults + .filter { it.SSID.isNotEmpty() } + .distinctBy { it.SSID } + .sortedByDescending { it.level } + .take(25) + .map { + mapOf( + "ssid" to it.SSID, + "level" to it.level, + "secured" to (it.capabilities.contains("WPA") + || it.capabilities.contains("WEP")) + ) + } + result.success(list) + } catch (e: Exception) { + result.error("ERROR", e.message, null) + } + } + + // ── WiFi connect ────────────────────────────────────── + "connectToWifi" -> { + try { + val ssid = call.argument("ssid") ?: "" + val password = call.argument("password") ?: "" + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + val wm = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager + val builder = WifiNetworkSuggestion.Builder().setSsid(ssid) + if (password.isNotEmpty()) builder.setWpa2Passphrase(password) + wm.removeNetworkSuggestions(wm.networkSuggestions) + val status = wm.addNetworkSuggestions(listOf(builder.build())) + result.success(status == WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) + } else { + @Suppress("DEPRECATION") + val wm = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager + @Suppress("DEPRECATION") + val conf = android.net.wifi.WifiConfiguration().apply { + SSID = "\"$ssid\"" + if (password.isNotEmpty()) preSharedKey = "\"$password\"" + else allowedKeyManagement.set( + android.net.wifi.WifiConfiguration.KeyMgmt.NONE + ) + } + @Suppress("DEPRECATION") + val netId = wm.addNetwork(conf) + @Suppress("DEPRECATION") + wm.disconnect() + @Suppress("DEPRECATION") + wm.enableNetwork(netId, true) + @Suppress("DEPRECATION") + wm.reconnect() + result.success(true) + } + } catch (e: Exception) { + result.error("ERROR", e.message, null) + } + } + + else -> result.notImplemented() + } + } + } + private fun setMobileDataState(enabled: Boolean) { + try { + val connectivityManagerClass = Class.forName(connectivityManager.javaClass.name) + val method = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean::class.javaPrimitiveType) + method.isAccessible = true + method.invoke(connectivityManager, enabled) + } catch (e: Exception) { + e.printStackTrace() + } + } + + private fun isMobileDataEnabled(): Boolean { + return try { + val connectivityManagerClass = Class.forName(connectivityManager.javaClass.name) + val method = connectivityManagerClass.getDeclaredMethod("getMobileDataEnabled") + method.isAccessible = true + method.invoke(connectivityManager) as Boolean + } catch (e: Exception) { + false + } + } +} diff --git a/Front/android/app/src/main/res/values/strings.xml b/Front/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..0c7c6b0 --- /dev/null +++ b/Front/android/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + خدمات دسترسی برای کنترل دکمه‌های ساعت + \ No newline at end of file diff --git a/Front/android/app/src/main/res/xml/accessibility_service_config.xml b/Front/android/app/src/main/res/xml/accessibility_service_config.xml new file mode 100644 index 0000000..9413582 --- /dev/null +++ b/Front/android/app/src/main/res/xml/accessibility_service_config.xml @@ -0,0 +1,8 @@ + + \ No newline at end of file diff --git a/Front/android/gradle.properties b/Front/android/gradle.properties index 809cb22..6429069 100644 --- a/Front/android/gradle.properties +++ b/Front/android/gradle.properties @@ -5,8 +5,10 @@ org.gradle.caching=true org.gradle.daemon=true org.gradle.parallel=true -systemProp.http.proxyHost=127.0.0.1 -systemProp.http.proxyPort=10809 -systemProp.https.proxyHost=127.0.0.1 -systemProp.https.proxyPort=10809 -systemProp.http.nonProxyHosts=localhost|127.*|[::1] \ No newline at end of file +org.gradle.offline=true + +# systemProp.http.proxyHost=127.0.0.1 +# systemProp.http.proxyPort=10809 +# systemProp.https.proxyHost=127.0.0.1 +# systemProp.https.proxyPort=10809 +# systemProp.http.nonProxyHosts=localhost|127.*|[::1] \ No newline at end of file diff --git a/Front/assets/images/logo.png b/Front/assets/images/logo.png new file mode 100644 index 0000000..4f6cb35 Binary files /dev/null and b/Front/assets/images/logo.png differ diff --git a/Front/lib/channel_list/channel_list_screen.dart b/Front/lib/channel_list/channel_list_screen.dart new file mode 100644 index 0000000..1dc93b9 --- /dev/null +++ b/Front/lib/channel_list/channel_list_screen.dart @@ -0,0 +1,186 @@ +import 'package:flutter/material.dart'; +import '../models/channel.dart'; +import '../services/api_service.dart'; +import '../services/auth_service.dart'; +import 'widgets/channel_circle_item.dart'; +import '../screens/channel_screen.dart'; + +class ChannelListScreen extends StatefulWidget { + const ChannelListScreen({super.key}); + + @override + State createState() => _ChannelListScreenState(); +} + +class _ChannelListScreenState extends State { + final _authService = AuthService(); + late final ApiService _api; + List _channels = []; + bool _loading = true; + String? _currentUserId; + PageController? _pageCtrl; + int _currentPage = 0; + bool _initialized = false; + + @override + void initState() { + super.initState(); + _api = ApiService(_authService); + _init(); + } + + Future _init() async { + _currentUserId = await _authService.getUserId(); + await _loadChannels(); + } + + Future _loadChannels() async { + setState(() => _loading = true); + final channels = await _api.getChannels(); + if (!mounted) return; + setState(() { + _channels = channels; + _loading = false; + if (!_initialized) { + // صفحه ۰ می‌شود خانه، صفحه ۱ اولین کانال + final startPage = channels.isNotEmpty ? 1 : 0; + _pageCtrl = PageController(initialPage: startPage); + _currentPage = startPage; + _initialized = true; + } + }); + } + + void _goHome() { + Navigator.pop(context); // بازگشت به صفحه HomeScreen + } + + void _enterChannel(Channel ch) { + Navigator.push( + context, + MaterialPageRoute( + builder: (_) => + ChannelScreen(channel: ch, currentUserId: _currentUserId), + ), + ); + } + + @override + void dispose() { + _pageCtrl?.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + if (_loading || _pageCtrl == null) { + return const Scaffold( + backgroundColor: Colors.black, + body: Center( + child: CircularProgressIndicator( + color: Color(0xFF00C853), + strokeWidth: 2, + ), + ), + ); + } + + final totalPages = _channels.length + 1; // +1 برای صفحه خانه + + return Scaffold( + backgroundColor: Colors.black, + body: SafeArea( + child: Column( + children: [ + Expanded( + child: PageView.builder( + controller: _pageCtrl!, + scrollDirection: Axis.vertical, + onPageChanged: (i) => setState(() => _currentPage = i), + itemCount: totalPages, + itemBuilder: (ctx, i) { + if (i == 0) return _buildHomeOption(); + return _buildChannelPage(_channels[i - 1]); + }, + ), + ), + _buildPageIndicator(totalPages), + ], + ), + ), + ); + } + + Widget _buildPageIndicator(int totalPages) { + return Padding( + padding: const EdgeInsets.only(bottom: 6, top: 2), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: List.generate(totalPages, (i) { + final isActive = i == _currentPage; + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 2), + child: Container( + width: isActive ? 6 : 4, + height: isActive ? 6 : 4, + decoration: BoxDecoration( + color: isActive ? const Color(0xFF00C853) : Colors.white24, + shape: BoxShape.circle, + ), + ), + ); + }), + ), + ); + } + + // صفحه اول: دکمه خانه + Widget _buildHomeOption() { + return Center( + child: GestureDetector( + onTap: _goHome, + child: Container( + width: 180, // کمی بزرگتر از کانال‌ها + height: 180, + decoration: BoxDecoration( + color: const Color(0xFF1C1C1E), + shape: BoxShape.circle, + border: Border.all(color: Colors.white24, width: 2), + boxShadow: [ + BoxShadow( + color: Colors.white.withOpacity(0.05), + blurRadius: 20, + spreadRadius: 2, + ), + ], + ), + child: const Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.home, color: Colors.white70, size: 40), + SizedBox(height: 10), + Text( + 'خانه', + style: TextStyle( + color: Colors.white, + fontSize: 16, + fontWeight: FontWeight.bold, + ), + ), + ], + ), + ), + ), + ); + } + + // صفحات کانال + Widget _buildChannelPage(Channel channel) { + return Center( + child: ChannelCircleItem( + channel: channel, + onTap: () => _enterChannel(channel), + ), + ); + } +} diff --git a/Front/lib/channel_list/widgets/channel_circle_item.dart b/Front/lib/channel_list/widgets/channel_circle_item.dart new file mode 100644 index 0000000..ba32535 --- /dev/null +++ b/Front/lib/channel_list/widgets/channel_circle_item.dart @@ -0,0 +1,74 @@ +import 'package:flutter/material.dart'; +import '../../models/channel.dart'; + +class ChannelCircleItem extends StatelessWidget { + final Channel channel; + final VoidCallback onTap; + + const ChannelCircleItem({ + super.key, + required this.channel, + required this.onTap, + }); + + @override + Widget build(BuildContext context) { + return GestureDetector( + onTap: onTap, + child: LayoutBuilder( + builder: (ctx, constraints) { + final size = constraints.maxWidth * 0.72; + return Container( + width: size, + height: size, + decoration: BoxDecoration( + color: const Color(0xFF1C1C1E), + shape: BoxShape.circle, + border: Border.all( + color: const Color(0xFF00C853).withOpacity(0.55), + width: 2, + ), + boxShadow: [ + BoxShadow( + color: const Color(0xFF00C853).withOpacity(0.12), + blurRadius: 22, + spreadRadius: 2, + ), + ], + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + channel.type == 'PUBLIC' ? Icons.radio : Icons.lock_outline, + color: const Color(0xFF00C853), + size: 22, + ), + const SizedBox(height: 8), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 20), + child: Text( + channel.name, + style: const TextStyle( + color: Colors.white, + fontSize: 13, + fontWeight: FontWeight.bold, + ), + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(height: 4), + Text( + channel.type == 'PUBLIC' ? 'عمومی' : 'خصوصی', + style: const TextStyle(color: Colors.white38, fontSize: 9), + ), + ], + ), + ); + }, + ), + ); + } +} diff --git a/Front/lib/config/app_config.dart b/Front/lib/config/app_config.dart index e891235..5a05864 100644 --- a/Front/lib/config/app_config.dart +++ b/Front/lib/config/app_config.dart @@ -6,18 +6,40 @@ class AppConfig { static const bool debug = false; // ── Server ─────────────────────────────────────────────────────────────── - static const String serverHost = '10.225.63.122'; + static const String serverHost = '94.183.170.121'; + static const String livekithost = '94.183.170.121'; static const int serverPort = 8000; - static const int livekitPort = 7880; + static const int livekitPort = 7780; static const bool useSecure = false; static String get baseUrl => '${useSecure ? 'https' : 'http'}://$serverHost:$serverPort'; - static String get wsBaseUrl => - '${useSecure ? 'wss' : 'ws'}://$serverHost:$serverPort'; + static String get wsBaseUrl => 'ws://$serverHost:$serverPort'; // آدرس سرور LiveKit (پورت جداگانه از بکند) - static String get livekitUrl => - '${useSecure ? 'wss' : 'ws'}://$serverHost:$livekitPort'; + static String get livekitUrl => 'ws://$livekithost:$livekitPort'; } + +// class AppConfig { +// // ── Debug mode ────────────────────────────────────────────────────────── +// // true → از داده‌های فیک استفاده می‌کند (بدون نیاز به سرور) +// // false → به سرور واقعی وصل می‌شود +// static const bool debug = true; + +// // ── Server ─────────────────────────────────────────────────────────────── +// static const String serverHost = 'neda.wikm.ir'; +// static const String livekithost = '94.183.170.121'; +// static const int serverPort = 8000; +// static const int livekitPort = 7780; +// static const bool useSecure = false; + +// static String get baseUrl => +// '${useSecure ? 'https' : 'http'}://$serverHost:$serverPort'; + +// static String get wsBaseUrl => +// '${useSecure ? 'wss' : 'ws'}://$serverHost:$serverPort'; + +// // آدرس سرور LiveKit (پورت جداگانه از بکند) +// static String get livekitUrl => '${useSecure ? 'wss' : 'ws'}://$livekithost:$livekitPort'; +// } diff --git a/Front/lib/home/home_screen.dart b/Front/lib/home/home_screen.dart new file mode 100644 index 0000000..f887bdc --- /dev/null +++ b/Front/lib/home/home_screen.dart @@ -0,0 +1,19 @@ +import 'package:flutter/material.dart'; +import 'widgets/watch_launcher.dart'; + +class HomeScreen extends StatefulWidget { + const HomeScreen({super.key}); + + @override + State createState() => _HomeScreenState(); +} + +class _HomeScreenState extends State { + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.black, + body: SafeArea(child: const WatchLauncher()), + ); + } +} diff --git a/Front/lib/home/widgets/create_group_page.dart b/Front/lib/home/widgets/create_group_page.dart new file mode 100644 index 0000000..f46b577 --- /dev/null +++ b/Front/lib/home/widgets/create_group_page.dart @@ -0,0 +1,155 @@ +import 'package:flutter/material.dart'; + +class CreateGroupPage extends StatefulWidget { + const CreateGroupPage({super.key}); + + @override + State createState() => _CreateGroupPageState(); +} + +class _CreateGroupPageState extends State { + final _controller = TextEditingController(); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + void _confirm() { + final name = _controller.text.trim(); + if (name.isNotEmpty) { + Navigator.of(context).pop(name); + } else { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('نام گروه نمی‌تواند خالی باشد'), + duration: Duration(seconds: 1), + ), + ); + } + } + + void _cancel() { + Navigator.of(context).pop(null); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.black, + body: SafeArea( + // استفاده از SingleChildScrollView برای حل مشکل اسکرول و دیده نشدن دکمه‌ها + child: SingleChildScrollView( + physics: const BouncingScrollPhysics(), + padding: const EdgeInsets.all(12.0), // کاهش پدینگ برای فضای بیشتر + child: Column( + // حذف MainAxisAlignment.center برای جلوگیری از بیرون زدن محتوا + mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox(height: 20), // فاصله از بالا + // آیکون گروه (کمی کوچکتر شده) + Container( + width: 60, + height: 60, + decoration: BoxDecoration( + color: const Color(0xFF00C853).withOpacity(0.15), + shape: BoxShape.circle, + border: Border.all( + color: const Color(0xFF00C853).withOpacity(0.5), + width: 2, + ), + ), + child: const Icon( + Icons.group_add, + color: Color(0xFF00C853), + size: 30, // کاهش سایز آیکون + ), + ), + const SizedBox(height: 16), + + // عنوان + const Text( + 'گروه جدید', + style: TextStyle( + color: Colors.white, + fontSize: 16, // کاهش سایز فونت + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 20), + + // ورودی متن + TextField( + controller: _controller, + autofocus: true, + textAlign: TextAlign.center, + textCapitalization: TextCapitalization.sentences, + style: const TextStyle( + color: Colors.white, + fontSize: 14, // کاهش سایز فونت متن + letterSpacing: 0.5, + ), + decoration: InputDecoration( + hintText: 'نام گروه را وارد کنید', + hintStyle: const TextStyle( + color: Colors.white38, + fontSize: 12, + ), + filled: true, + fillColor: Colors.white.withOpacity(0.08), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(12), + borderSide: BorderSide.none, + ), + contentPadding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 12, // کاهش ارتفاع فیلد + ), + ), + onSubmitted: (_) => _confirm(), + ), + const SizedBox(height: 24), + + // دکمه تایید + SizedBox( + width: double.infinity, + height: 40, // ارتفاع ثابت برای دکمه + child: ElevatedButton( + onPressed: _confirm, + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF00C853), + foregroundColor: Colors.black, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20), + ), + elevation: 0, + ), + child: const Text( + 'ساخت گروه', + style: TextStyle(fontSize: 13, fontWeight: FontWeight.bold), + ), + ), + ), + const SizedBox(height: 8), + + // دکمه لغو + SizedBox( + width: double.infinity, + height: 40, // ارتفاع ثابت برای دکمه + child: TextButton( + onPressed: _cancel, + style: TextButton.styleFrom(foregroundColor: Colors.white54), + child: const Text('لغو', style: TextStyle(fontSize: 13)), + ), + ), + + // فضای خالی در پایین برای اسکرول راحت‌تر + const SizedBox(height: 20), + ], + ), + ), + ), + ); + } +} diff --git a/Front/lib/home/widgets/watch_launcher.dart b/Front/lib/home/widgets/watch_launcher.dart new file mode 100644 index 0000000..96a5b9e --- /dev/null +++ b/Front/lib/home/widgets/watch_launcher.dart @@ -0,0 +1,443 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import '../../services/api_service.dart'; + +// ایمپورت صفحات دیگر برای ناوبری +import '../../channel_list/channel_list_screen.dart'; +import '../../screens/notifications_screen.dart'; +import 'create_group_page.dart'; +import '../../screens/about.dart'; + +// مدل داده‌ای برای آیکون‌های منو +class LauncherItem { + final String label; + final IconData? icon; + final String? imagePath; + final Color color; + final VoidCallback onTap; + + LauncherItem({ + required this.label, + this.icon, + this.imagePath, + required this.color, + required this.onTap, + }); +} + +class WatchLauncher extends StatefulWidget { + const WatchLauncher({super.key}); + + @override + State createState() => _WatchLauncherState(); +} + +class _WatchLauncherState extends State { + // کنترلر اسکرول + final ScrollController _scrollController = ScrollController(); + + // ارتفاع هر آیکون + final double _itemHeight = 100.0; + + // کانال ارتباطی با کد نیتیو + static final _nativeChannel = const MethodChannel( + 'com.example.watch/launcher', + ); + + late final ApiService _api; + + // لیست آیکون‌های برنامه + late final List _items; + + // متغیرهای برای ساعت و تاریخ داینامیک + String _currentTime = ''; + String _currentDate = ''; + late StreamSubscription _timeSubscription; + + @override + void initState() { + super.initState(); + _items = _generateItems(); + + // استفاده از Stream برای بهینه‌سازی ساعت + _timeSubscription = + Stream.periodic( + const Duration(seconds: 1), + (count) => DateTime.now(), + ).listen((dateTime) { + if (!mounted) return; + final timeString = + '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}'; + final dateString = + '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')}'; + + setState(() { + _currentTime = timeString; + _currentDate = dateString; + }); + }); + } + + @override + void dispose() { + _scrollController.dispose(); + _timeSubscription.cancel(); + super.dispose(); + } + + // تولید لیست آیکون‌ها + List _generateItems() { + return [ + LauncherItem( + label: 'اعلان‌ها', + icon: Icons.notifications_outlined, + color: const Color(0xFFFF1744), + onTap: () => _navigateTo(const NotificationsScreen()), + ), + LauncherItem( + label: 'بی‌سیم', + icon: Icons.radio, + color: const Color(0xFF00C853), + onTap: () => _navigateTo(const ChannelListScreen()), + ), + LauncherItem( + label: 'گروه جدید', + icon: Icons.add_circle_outline, + color: const Color(0xFF00C853), + onTap: _showCreateGroupDialog, + ), + LauncherItem( + label: 'تلفن', + icon: Icons.phone, + color: const Color(0xFF2979FF), + onTap: _openDialer, + ), + LauncherItem( + label: 'اینترنت', + icon: Icons.cell_tower, + color: const Color(0xFF00BCD4), + onTap: _openInternetSettings, + ), + LauncherItem( + label: 'بلوتوث', + icon: Icons.bluetooth, + color: const Color(0xFF304FFE), + onTap: _openBluetoothSettings, + ), + LauncherItem( + label: 'درباره ما', + imagePath: 'assets/images/logo.png', + color: const Color(0xFF9C27B0), + onTap: () => _navigateTo(const AboutScreen()), + ), + LauncherItem( + label: 'خروج', + icon: Icons.logout, + color: Colors.redAccent, + onTap: _logout, + ), + ]; + } + + // --- متدهای کمکی --- + + void _navigateTo(Widget page) { + Navigator.push(context, MaterialPageRoute(builder: (_) => page)); + } + + void _showSnack(String msg) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + msg, + style: const TextStyle(fontSize: 10, color: Colors.white), + ), + backgroundColor: const Color(0xFF2C2C2E), + duration: const Duration(seconds: 2), + behavior: SnackBarBehavior.floating, + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 40), + ), + ); + } + + Future _openDialer() async { + try { + await _nativeChannel.invokeMethod('openDialer'); + } catch (_) { + _showSnack('خطا در باز کردن شماره‌گیر'); + } + } + + Future _openInternetSettings() async { + try { + await _nativeChannel.invokeMethod('openInternetSettings'); + } catch (_) { + _showSnack('تنظیمات اینترنت در دسترس نیست'); + } + } + + Future _openBluetoothSettings() async { + try { + await _nativeChannel.invokeMethod('openBluetoothSettings'); + } catch (_) { + _showSnack('خطا در باز کردن بلوتوث'); + } + } + + Future _logout() async { + try { + if (!mounted) return; + Navigator.pushReplacementNamed(context, '/login'); + } catch (e) { + _showSnack('خطا در خروج'); + } + } + + Future _showCreateGroupDialog() async { + final groupName = await Navigator.push( + context, + MaterialPageRoute( + builder: (ctx) => const CreateGroupPage(), + fullscreenDialog: true, + ), + ); + + if (groupName != null && groupName.trim().isNotEmpty && mounted) { + try { + final newChannel = await _api.createGroup(groupName.trim()); + + if (!mounted) return; + + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + newChannel != null ? 'گروه ساخته شد' : 'خطا در ساخت گروه', + style: const TextStyle(fontSize: 11, color: Colors.white), + textAlign: TextAlign.center, + ), + backgroundColor: const Color(0xFF2C2C2E), + behavior: SnackBarBehavior.floating, + duration: const Duration(seconds: 2), + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 40), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20), + ), + ), + ); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('خطا در ارتباط با سرور'), + backgroundColor: Colors.red, + ), + ); + } + } + } + + @override + Widget build(BuildContext context) { + final double screenHeight = MediaQuery.of(context).size.height; + final double verticalPadding = (screenHeight / 2) - (_itemHeight / 2); + + return Scaffold( + backgroundColor: Colors.black, + body: Stack( + children: [ + // لایه اسکرول آیکون‌ها + Positioned.fill( + child: NotificationListener( + onNotification: (scrollNotification) { + // فقط برای Snapping نیاز به setState نیست، AnimatedBuilder کار را انجام می‌دهد + if (scrollNotification is ScrollEndNotification) { + _snapToItem(); + } + return false; + }, + child: ListView.builder( + controller: _scrollController, + physics: const BouncingScrollPhysics(), + padding: EdgeInsets.symmetric(vertical: verticalPadding), + itemCount: _items.length, + itemBuilder: (context, index) { + return _buildAnimatedItem(index); + }, + ), + ), + ), + + // ساعت در سمت چپ + Positioned( + left: 8, + top: 0, + bottom: 0, + child: Center( + child: RotatedBox( + quarterTurns: 3, + child: Text( + _currentTime, + style: const TextStyle( + color: Colors.white, + fontSize: 15, + fontWeight: FontWeight.bold, + letterSpacing: 1, + ), + ), + ), + ), + ), + + // تاریخ در سمت راست + Positioned( + right: 8, + top: 0, + bottom: 0, + child: Center( + child: RotatedBox( + quarterTurns: 1, + child: Text( + _currentDate, + style: const TextStyle(color: Colors.white70, fontSize: 13), + ), + ), + ), + ), + ], + ), + ); + } + + // متد ساخت آیکون با انیمیشن بهینه + Widget _buildAnimatedItem(int index) { + return AnimatedBuilder( + animation: _scrollController, + builder: (context, child) { + double scrollOffset = _scrollController.hasClients + ? _scrollController.offset + : 0.0; + + double itemPosition = index * _itemHeight; + double screenHeight = MediaQuery.of(context).size.height; + double centerOffset = scrollOffset + (screenHeight / 2); + double distanceFromCenter = (itemPosition - centerOffset).abs(); + + // محاسبات انیمیشن + double scale = (1.6 - (distanceFromCenter / 180)).clamp(0.4, 1.6); + double opacity = (1.2 - (distanceFromCenter / 250)).clamp(0.1, 1.0); + + // چرخش آیکون‌های دورتر برای افکت سه بعدی + double rotation = (distanceFromCenter / 1000).clamp(-0.2, 0.2); + + // شدت سایه بر اساس فاصله از مرکز + double blurRadius = (20 - (distanceFromCenter / 20)).clamp(0, 20); + double shadowOpacity = (0.6 - (distanceFromCenter / 400)).clamp( + 0.0, + 0.6, + ); + + return SizedBox( + height: _itemHeight, + child: Center( + child: Transform.scale( + scale: scale, + child: Transform.rotate( + angle: rotation, + child: Opacity( + opacity: opacity, + child: Container( + // حلقه درخشان دور آیکون وقتی وسط است + decoration: BoxDecoration( + shape: BoxShape.circle, + boxShadow: [ + BoxShadow( + color: _items[index].color.withOpacity(shadowOpacity), + blurRadius: blurRadius, + spreadRadius: 2, + ), + ], + ), + child: _buildIconButton(_items[index]), + ), + ), + ), + ), + ), + ); + }, + ); + } + + // متد قفل و زنجیر (Snapping) + void _snapToItem() { + if (!_scrollController.hasClients) return; + + double screenHeight = MediaQuery.of(context).size.height; + double currentScroll = _scrollController.offset; + double centerOffset = currentScroll + (screenHeight / 2); + int targetIndex = (centerOffset / _itemHeight).round(); + + if (targetIndex < 0) targetIndex = 0; + if (targetIndex >= _items.length) targetIndex = _items.length - 1; + + double targetScroll = + (targetIndex * _itemHeight) - ((screenHeight / 2) - (_itemHeight / 2)); + + _scrollController.animateTo( + targetScroll, + duration: const Duration(milliseconds: 300), + curve: Curves.easeOutCubic, + ); + } + + // ویجت دایره‌ای آیکون + Widget _buildIconButton(LauncherItem item) { + return InkWell( + onTap: item.onTap, + borderRadius: BorderRadius.circular(50), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 60, + height: 60, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: item.color, + border: Border.all(color: item.color.withOpacity(0.5), width: 2), + ), + child: item.imagePath != null && item.imagePath!.isNotEmpty + ? Padding( + padding: const EdgeInsets.all(12.0), + child: Image.asset( + item.imagePath!, + errorBuilder: (context, error, stackTrace) { + return Icon( + item.icon ?? Icons.error_outline, + color: Colors.white, + size: 30, + ); + }, + ), + ) + : Icon( + item.icon ?? Icons.error_outline, + color: Colors.white, + size: 30, + ), + ), + const SizedBox(height: 4), + Text( + item.label, + style: const TextStyle( + color: Colors.white, + fontSize: 10, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ); + } +} diff --git a/Front/lib/main.dart b/Front/lib/main.dart index 652ec20..b047f74 100644 --- a/Front/lib/main.dart +++ b/Front/lib/main.dart @@ -1,7 +1,9 @@ import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:permission_handler/permission_handler.dart'; -import 'screens/channel_list_screen.dart'; +import 'home/home_screen.dart'; +import 'channel_list/channel_list_screen.dart'; import 'screens/login_screen.dart'; import 'services/auth_service.dart'; @@ -29,7 +31,23 @@ class WalkieTalkieApp extends StatelessWidget { scaffoldBackgroundColor: Colors.black, useMaterial3: true, ), - home: const _Splash(), + // استفاده از onGenerateRoute برای مدیریت مسیرها + onGenerateRoute: (settings) { + switch (settings.name) { + case '/': + return MaterialPageRoute(builder: (_) => const _Splash()); + case '/home': + return MaterialPageRoute(builder: (_) => const HomeScreen()); + case '/channel_list': + return MaterialPageRoute(builder: (_) => const ChannelListScreen()); + case '/login': + return MaterialPageRoute(builder: (_) => const LoginScreen()); + default: + return MaterialPageRoute(builder: (_) => const _Splash()); + } + }, + // صفحه پیش‌فرض برنامه (اسپلش) + initialRoute: '/', ); } } @@ -42,32 +60,139 @@ class _Splash extends StatefulWidget { } class _SplashState extends State<_Splash> { + bool _loading = false; + + // متغیرهای مربوط به باتری + static const _nativeChannel = MethodChannel('com.example.watch/launcher'); + int _batteryLevel = 0; + bool _isCharging = false; + @override void initState() { super.initState(); - _route(); + _loadBattery(); } - Future _route() async { + Future _loadBattery() async { + try { + final info = await _nativeChannel.invokeMapMethod( + 'getBatteryInfo', + ); + if (!mounted || info == null) return; + setState(() { + _batteryLevel = (info['level'] as int?) ?? 0; + _isCharging = (info['isCharging'] as bool?) ?? false; + }); + } catch (_) {} + } + + Future _onTap() async { + if (_loading) return; + setState(() => _loading = true); + final loggedIn = await AuthService().isLoggedIn(); + if (!mounted) return; - Navigator.pushReplacement( - context, - MaterialPageRoute( - builder: (_) => - loggedIn ? const ChannelListScreen() : const LoginScreen(), - ), - ); + + // هدایت کاربر بر اساس وضعیت لاگین + Navigator.pushReplacementNamed(context, loggedIn ? '/home' : '/login'); } @override Widget build(BuildContext context) { - return const Scaffold( - backgroundColor: Colors.black, - body: Center( - child: CircularProgressIndicator( - color: Color(0xFF00C853), - strokeWidth: 2, + return GestureDetector( + onTap: _onTap, + child: Scaffold( + backgroundColor: Colors.black, + body: Center( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 64, + height: 64, + decoration: const BoxDecoration( + color: Colors.white, + shape: BoxShape.circle, + ), + padding: const EdgeInsets.all(1), + child: Image.asset( + 'assets/images/logo.png', + fit: BoxFit.contain, + ), + ), + const SizedBox(height: 14), + const Text( + 'مرکز هوش مصنوعی', + style: TextStyle( + color: Colors.green, + fontSize: 15, + fontWeight: FontWeight.bold, + letterSpacing: 0.4, + ), + textAlign: TextAlign.center, + ), + const SizedBox(height: 3), + const Text( + 'و فناوری‌های نو ظهور', + style: TextStyle( + color: Colors.white, + fontSize: 14, + letterSpacing: 0.3, + ), + textAlign: TextAlign.center, + ), + const Text( + 'سپاه ثارلله استان کرمان', + style: TextStyle( + color: Colors.red, + fontSize: 14, + letterSpacing: 0.3, + ), + textAlign: TextAlign.center, + ), + const SizedBox(height: 16), + if (_loading) + const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator( + color: Color(0xFF00C853), + strokeWidth: 2, + ), + ) + else + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + _isCharging ? Icons.bolt : Icons.battery_std, + color: _isCharging + ? const Color(0xFF00C853) + : (_batteryLevel <= 15 + ? const Color(0xFFFF1744) + : Colors.white24), + size: 10, + ), + const SizedBox(width: 4), + Text( + '$_batteryLevel%', + style: TextStyle( + color: _isCharging + ? const Color(0xFF00C853) + : (_batteryLevel <= 15 + ? const Color(0xFFFF1744) + : Colors.white24), + fontSize: 9, + ), + ), + ], + ), + ], + ), + ), ), ), ); diff --git a/Front/lib/models/app_notification.dart b/Front/lib/models/app_notification.dart index b80daee..47927eb 100644 --- a/Front/lib/models/app_notification.dart +++ b/Front/lib/models/app_notification.dart @@ -20,11 +20,13 @@ class AppNotification { }); factory AppNotification.fromJson(Map json) { + final rawType = (json['type'] as String?) ?? 'PUBLIC'; + final normalizedType = _normalizeType(rawType); return AppNotification( id: json['id'].toString(), title: json['title'] as String, description: json['description'] as String?, - type: (json['type'] as String?) ?? 'PUBLIC', + type: normalizedType, groupId: json['group_id']?.toString(), isAccepted: json['is_accepted'] as bool?, receiverId: json['receiver_id'].toString(), @@ -32,6 +34,17 @@ class AppNotification { ); } + static String _normalizeType(String rawType) { + final upper = rawType.trim().toUpperCase(); + if (upper == 'GROUP_INVITATION' || + upper == 'GROUP_INVITE' || + upper == 'INVITE' || + upper == 'JOIN_REQUEST') { + return 'JOIN_REQUEST'; + } + return upper; + } + bool get isJoinRequest => type == 'JOIN_REQUEST'; bool get isPending => isAccepted == null; } diff --git a/Front/lib/screens/about.dart b/Front/lib/screens/about.dart new file mode 100644 index 0000000..95fb06d --- /dev/null +++ b/Front/lib/screens/about.dart @@ -0,0 +1,216 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +class AboutScreen extends StatefulWidget { + const AboutScreen({super.key}); + + @override + State createState() => _AboutScreenState(); +} + +class _AboutScreenState extends State { + static const _nativeChannel = MethodChannel('com.example.watch/launcher'); + + // --- متغیرهای مربوط به بخش توضیحات (برای تنظیمات) --- + int _descTapCount = 0; + DateTime? _descLastTapTime; + bool _descIsHolding = false; + + // --- متغیرهای مربوط به بخش نسخه (برای EngineerMode) --- + int _verTapCount = 0; + DateTime? _verLastTapTime; + bool _verIsHolding = false; + + // تابع باز کردن تنظیمات ساعت + Future _openWatchSettings() async { + try { + await _nativeChannel.invokeMethod('openWatchSettings'); + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('خطا در باز کردن تنظیمات')), + ); + } + } + } + + // تابع باز کردن EngineerMode + Future _openEngineerMode() async { + try { + await _nativeChannel.invokeMethod('openEngineerMode'); + } catch (e) { + if (mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('خطا در باز کردن مهندسی'))); + } + } + } + + // --- هندلرهای بخش توضیحات --- + void _handleDescTap() { + if (_descIsHolding) return; + final now = DateTime.now(); + if (_descLastTapTime != null && + now.difference(_descLastTapTime!) > const Duration(seconds: 1)) { + _descTapCount = 0; + } + _descTapCount++; + _descLastTapTime = now; + if (_descTapCount == 5) HapticFeedback.lightImpact(); + } + + void _handleDescLongPressStart(LongPressStartDetails details) { + setState(() => _descIsHolding = true); + if (_descTapCount >= 5) { + HapticFeedback.heavyImpact(); + _openWatchSettings(); + } else { + _descTapCount = 0; + } + } + + void _handleDescLongPressEnd(LongPressEndDetails details) { + setState(() => _descIsHolding = false); + } + + // --- هندلرهای بخش نسخه --- + void _handleVerTap() { + if (_verIsHolding) return; + final now = DateTime.now(); + if (_verLastTapTime != null && + now.difference(_verLastTapTime!) > const Duration(seconds: 1)) { + _verTapCount = 0; + } + _verTapCount++; + _verLastTapTime = now; + if (_verTapCount == 5) HapticFeedback.lightImpact(); + } + + void _handleVerLongPressStart(LongPressStartDetails details) { + setState(() => _verIsHolding = true); + if (_verTapCount >= 5) { + HapticFeedback.heavyImpact(); + _openEngineerMode(); + } else { + _verTapCount = 0; + } + } + + void _handleVerLongPressEnd(LongPressEndDetails details) { + setState(() => _verIsHolding = false); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFF000000), + body: SafeArea( + child: Center( + child: SingleChildScrollView( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + // --- لوگو --- + Container( + width: 100, + height: 100, + decoration: const BoxDecoration( + color: Colors.white, + shape: BoxShape.circle, + ), + child: Padding( + padding: const EdgeInsets.all(15.0), + child: Image.asset( + 'assets/images/logo.png', + errorBuilder: (context, error, stackTrace) { + return const Icon( + Icons.error_outline, + color: Colors.grey, + size: 50, + ); + }, + ), + ), + ), + const SizedBox(height: 30), + + // --- بخش توضیحات سازنده (قابل کلیک برای تنظیمات) --- + GestureDetector( + onTap: _handleDescTap, + onLongPressStart: _handleDescLongPressStart, + onLongPressEnd: _handleDescLongPressEnd, + behavior: HitTestBehavior.opaque, + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 20), + padding: const EdgeInsets.all(15), + decoration: BoxDecoration( + color: const Color(0xFF1C1C1E), + borderRadius: BorderRadius.circular(15), + border: Border.all(color: Colors.white.withOpacity(0.1)), + ), + child: const Text( + 'توسعه یافته توسط تیم هوش مصنوعی و فناوری های نو ظهور سپاه ثارلله استان کرمان', + textAlign: TextAlign.center, + style: TextStyle( + color: Colors.white, + fontSize: 14, + height: 1.5, + ), + ), + ), + ), + const SizedBox(height: 20), + + // --- بخش نسخه (قابل کلیک برای EngineerMode) --- + GestureDetector( + onTap: _handleVerTap, + onLongPressStart: _handleVerLongPressStart, + onLongPressEnd: _handleVerLongPressEnd, + behavior: HitTestBehavior.opaque, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 20, + vertical: 10, + ), + decoration: BoxDecoration( + color: Colors.white.withOpacity(0.05), + borderRadius: BorderRadius.circular(20), + border: Border.all(color: Colors.white.withOpacity(0.1)), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: const [ + Icon( + Icons.info_outline, + color: Colors.blueAccent, + size: 18, + ), + SizedBox(width: 8), + Text( + 'نسخه ۱.۰.۰', + style: TextStyle( + color: Colors.white, + fontSize: 16, + fontWeight: FontWeight.bold, + ), + ), + ], + ), + ), + ), + + const SizedBox(height: 40), + + IconButton( + onPressed: () => Navigator.pop(context), + icon: const Icon(Icons.arrow_back_ios, color: Colors.white), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/Front/lib/screens/channel_list_screen.dart b/Front/lib/screens/channel_list_screen.dart deleted file mode 100644 index 9e9c2f9..0000000 --- a/Front/lib/screens/channel_list_screen.dart +++ /dev/null @@ -1,390 +0,0 @@ -import 'package:flutter/material.dart'; -import '../models/channel.dart'; -import '../services/api_service.dart'; -import '../services/auth_service.dart'; -import 'channel_screen.dart'; -import 'login_screen.dart'; -import 'notifications_screen.dart'; - -class ChannelListScreen extends StatefulWidget { - const ChannelListScreen({super.key}); - - @override - State createState() => _ChannelListScreenState(); -} - -class _ChannelListScreenState extends State { - final _authService = AuthService(); - late final ApiService _api; - - List _channels = []; - bool _loading = true; - String? _error; - int _pendingNotifCount = 0; - String? _currentUserId; - - @override - void initState() { - super.initState(); - _api = ApiService(_authService); - _init(); - } - - Future _init() async { - _currentUserId = await _authService.getUserId(); - await _loadChannels(); - await _loadNotifCount(); - } - - Future _loadChannels() async { - setState(() { - _loading = true; - _error = null; - }); - final channels = await _api.getChannels(); - if (!mounted) return; - if (channels.isEmpty && _channels.isEmpty) { - setState(() { - _loading = false; - _error = 'کانالی یافت نشد'; - }); - } else { - setState(() { - _channels = channels; - _loading = false; - }); - } - } - - Future _loadNotifCount() async { - final notifs = await _api.getNotifications(); - if (!mounted) return; - setState(() { - _pendingNotifCount = notifs.where((n) => n.isPending).length; - }); - } - - Future _refresh() async { - await _loadChannels(); - await _loadNotifCount(); - } - - Future _logout() async { - await _authService.logout(); - if (!mounted) return; - Navigator.pushReplacement( - context, - MaterialPageRoute(builder: (_) => const LoginScreen()), - ); - } - - void _enterChannel(Channel ch) { - Navigator.push( - context, - MaterialPageRoute( - builder: (_) => ChannelScreen(channel: ch, currentUserId: _currentUserId), - ), - ); - } - - void _openNotifications() async { - await Navigator.push( - context, - MaterialPageRoute(builder: (_) => const NotificationsScreen()), - ); - // refresh notif count + reload channels after returning (user may have accepted invite) - _refresh(); - } - - Future _showCreateGroupDialog() async { - String groupName = ''; - final confirmed = await showDialog( - context: context, - builder: (ctx) => _CreateGroupDialog( - onNameChanged: (v) => groupName = v, - ), - ); - - if (confirmed == true && groupName.trim().isNotEmpty) { - final newChannel = await _api.createGroup(groupName.trim()); - if (!mounted) return; - if (newChannel != null) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: const Text('گروه ساخته شد', style: TextStyle(fontSize: 11), textAlign: TextAlign.center), - backgroundColor: const Color(0xFF1C1C1E), - behavior: SnackBarBehavior.floating, - duration: const Duration(seconds: 2), - margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 40), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), - ), - ); - _loadChannels(); - } else { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: const Text('خطا در ساخت گروه', style: TextStyle(fontSize: 11), textAlign: TextAlign.center), - backgroundColor: const Color(0xFF333333), - behavior: SnackBarBehavior.floating, - duration: const Duration(seconds: 2), - margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 40), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), - ), - ); - } - } - } - - @override - Widget build(BuildContext context) { - return Scaffold( - backgroundColor: Colors.black, - body: SafeArea( - child: Column( - children: [ - // Header - Padding( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), - child: Row( - children: [ - const SizedBox(width: 4), - const Icon(Icons.settings_input_antenna, - color: Color(0xFF00C853), size: 16), - const SizedBox(width: 4), - const Expanded( - child: Text( - 'کانال‌ها', - style: TextStyle( - color: Colors.white, - fontSize: 13, - fontWeight: FontWeight.bold), - ), - ), - // Notifications icon with badge - Stack( - clipBehavior: Clip.none, - children: [ - IconButton( - onPressed: _openNotifications, - padding: EdgeInsets.zero, - constraints: const BoxConstraints(minWidth: 32, minHeight: 32), - icon: const Icon(Icons.notifications_outlined, - color: Colors.white54, size: 18), - ), - if (_pendingNotifCount > 0) - Positioned( - top: 4, - right: 4, - child: Container( - width: 8, - height: 8, - decoration: const BoxDecoration( - color: Color(0xFFFF1744), - shape: BoxShape.circle, - ), - ), - ), - ], - ), - // Create group - IconButton( - onPressed: _showCreateGroupDialog, - padding: EdgeInsets.zero, - constraints: const BoxConstraints(minWidth: 32, minHeight: 32), - icon: const Icon(Icons.add_circle_outline, - color: Color(0xFF00C853), size: 18), - ), - // Refresh - IconButton( - onPressed: _loading ? null : _refresh, - padding: EdgeInsets.zero, - constraints: - const BoxConstraints(minWidth: 32, minHeight: 32), - icon: const Icon(Icons.refresh, - color: Colors.white54, size: 18), - ), - // Logout - IconButton( - onPressed: _logout, - padding: EdgeInsets.zero, - constraints: - const BoxConstraints(minWidth: 32, minHeight: 32), - icon: const Icon(Icons.logout, - color: Colors.white38, size: 16), - ), - ], - ), - ), - - // Content - Expanded( - child: _loading - ? const Center( - child: CircularProgressIndicator( - color: Color(0xFF00C853), strokeWidth: 2), - ) - : _error != null && _channels.isEmpty - ? Center( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(Icons.wifi_off, - color: Colors.white38, size: 24), - const SizedBox(height: 6), - Text(_error!, - style: const TextStyle( - color: Colors.white38, fontSize: 11)), - const SizedBox(height: 8), - TextButton( - onPressed: _refresh, - child: const Text('تلاش مجدد', - style: TextStyle( - color: Color(0xFF00C853), - fontSize: 11)), - ), - ], - ), - ) - : ListView.builder( - padding: const EdgeInsets.only(bottom: 4), - itemCount: _channels.length, - itemBuilder: (ctx, i) { - return _ChannelTile( - channel: _channels[i], - onTap: () => _enterChannel(_channels[i]), - ); - }, - ), - ), - ], - ), - ), - ); - } -} - -class _ChannelTile extends StatelessWidget { - final Channel channel; - final VoidCallback onTap; - - const _ChannelTile({required this.channel, required this.onTap}); - - @override - Widget build(BuildContext context) { - return GestureDetector( - onTap: onTap, - child: Container( - margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), - height: 44, - decoration: BoxDecoration( - color: const Color(0xFF1C1C1E), - borderRadius: BorderRadius.circular(14), - ), - padding: const EdgeInsets.symmetric(horizontal: 12), - child: Row( - children: [ - Icon( - channel.type == 'PUBLIC' ? Icons.radio : Icons.lock_outline, - color: const Color(0xFF00C853), - size: 16, - ), - const SizedBox(width: 8), - Expanded( - child: Text( - channel.name, - style: const TextStyle( - color: Colors.white, - fontSize: 12, - fontWeight: FontWeight.w500), - overflow: TextOverflow.ellipsis, - ), - ), - const SizedBox(width: 4), - const Icon(Icons.chevron_right, color: Colors.white24, size: 16), - ], - ), - ), - ); - } -} - -// ── Create Group Dialog ──────────────────────────────────────────────────── - -class _CreateGroupDialog extends StatefulWidget { - final ValueChanged onNameChanged; - - const _CreateGroupDialog({required this.onNameChanged}); - - @override - State<_CreateGroupDialog> createState() => _CreateGroupDialogState(); -} - -class _CreateGroupDialogState extends State<_CreateGroupDialog> { - final _ctrl = TextEditingController(); - - @override - void dispose() { - _ctrl.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { - return AlertDialog( - backgroundColor: const Color(0xFF1C1C1E), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), - contentPadding: const EdgeInsets.all(16), - content: Column( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(Icons.add_circle_outline, color: Color(0xFF00C853), size: 26), - const SizedBox(height: 8), - const Text( - 'گروه جدید', - style: TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.bold), - ), - const SizedBox(height: 10), - TextField( - controller: _ctrl, - autofocus: true, - textAlign: TextAlign.center, - style: const TextStyle(color: Colors.white, fontSize: 12), - decoration: InputDecoration( - hintText: 'نام گروه', - hintStyle: const TextStyle(color: Colors.white38, fontSize: 11), - filled: true, - fillColor: Colors.white.withValues(alpha: 0.05), - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(10), - borderSide: BorderSide.none, - ), - contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), - ), - onChanged: widget.onNameChanged, - ), - const SizedBox(height: 12), - Row( - children: [ - Expanded( - child: TextButton( - onPressed: () => Navigator.pop(context, false), - child: const Text('انصراف', style: TextStyle(color: Colors.white54, fontSize: 11)), - ), - ), - Expanded( - child: TextButton( - onPressed: () => Navigator.pop(context, true), - child: const Text('ساخت', style: TextStyle( - color: Color(0xFF00C853), - fontSize: 11, - fontWeight: FontWeight.bold, - )), - ), - ), - ], - ), - ], - ), - ); - } -} diff --git a/Front/lib/screens/channel_list_screen_old.dart b/Front/lib/screens/channel_list_screen_old.dart new file mode 100644 index 0000000..c300c71 --- /dev/null +++ b/Front/lib/screens/channel_list_screen_old.dart @@ -0,0 +1,594 @@ +// import 'package:flutter/material.dart'; +// import 'package:flutter/services.dart'; +// import '../models/channel.dart'; +// import '../services/api_service.dart'; +// import '../services/auth_service.dart'; +// import 'channel_screen.dart'; +// import 'login_screen.dart'; +// import 'notifications_screen.dart'; +// import 'wifi_screen.dart'; + +// class ChannelListScreen extends StatefulWidget { +// const ChannelListScreen({super.key}); + +// @override +// State createState() => _ChannelListScreenState(); +// } + +// class _ChannelListScreenState extends State { +// static final _nativeChannel = const MethodChannel( +// 'com.example.watch/launcher', +// ); + +// final _authService = AuthService(); +// late final ApiService _api; + +// List _channels = []; +// bool _loading = true; +// int _pendingNotifCount = 0; +// String? _currentUserId; +// PageController? _pageCtrl; +// int _currentPage = 0; +// bool _initialized = false; + +// // Battery +// int _batteryLevel = 0; +// bool _isCharging = false; + +// @override +// void initState() { +// super.initState(); +// _api = ApiService(_authService); +// _init(); +// } + +// Future _init() async { +// _currentUserId = await _authService.getUserId(); +// await Future.wait([_loadChannels(), _loadNotifCount(), _loadBattery()]); +// } + +// Future _loadBattery() async { +// try { +// final info = await _nativeChannel.invokeMapMethod( +// 'getBatteryInfo', +// ); +// if (!mounted || info == null) return; +// setState(() { +// _batteryLevel = (info['level'] as int?) ?? 0; +// _isCharging = (info['isCharging'] as bool?) ?? false; +// }); +// } catch (_) {} +// } + +// Future _loadChannels() async { +// setState(() => _loading = true); +// final channels = await _api.getChannels(); +// if (!mounted) return; +// setState(() { +// _channels = channels; +// _loading = false; +// if (!_initialized) { +// final startPage = channels.isNotEmpty ? 1 : 0; +// _pageCtrl = PageController(initialPage: startPage); +// _currentPage = startPage; +// _initialized = true; +// } +// }); +// } + +// Future _loadNotifCount() async { +// final notifs = await _api.getNotifications(); +// if (!mounted) return; +// setState(() { +// _pendingNotifCount = notifs.where((n) => n.isPending).length; +// }); +// } + +// Future _refresh() async { +// await _loadChannels(); +// await _loadNotifCount(); +// } + +// Future _openInternetSettings() async { +// try { +// await _nativeChannel.invokeMethod('openInternetSettings'); +// } catch (_) { +// if (!mounted) return; +// _showSnack('تنظیمات اینترنت در دسترس نیست'); +// } +// } + +// void _openWifi() { +// Navigator.push( +// context, +// MaterialPageRoute(builder: (_) => const WifiScreen()), +// ); +// } + +// Future _openAccessibilitySettings() async { +// try { +// await _nativeChannel.invokeMethod('openAccessibilitySettings'); +// } catch (e) { +// _showSnack('خطا در باز کردن تنظیمات'); +// } +// } + +// void _showSnack(String msg) { +// ScaffoldMessenger.of(context).showSnackBar( +// SnackBar( +// content: Text( +// msg, +// style: const TextStyle(fontSize: 10, color: Colors.white), +// textAlign: TextAlign.center, +// ), +// backgroundColor: const Color(0xFF2C2C2E), +// behavior: SnackBarBehavior.floating, +// duration: const Duration(seconds: 2), +// margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 40), +// ), +// ); +// } + +// Future _openHomeSettings() async { +// try { +// await _nativeChannel.invokeMethod('openHomeSettings'); +// } catch (_) { +// if (!mounted) return; +// ScaffoldMessenger.of(context).showSnackBar( +// const SnackBar( +// content: Text( +// 'این قابلیت روی دستگاه شما پشتیبانی نمی‌شود', +// style: TextStyle(fontSize: 10, color: Colors.white), +// textAlign: TextAlign.center, +// ), +// backgroundColor: Color(0xFF2C2C2E), +// behavior: SnackBarBehavior.floating, +// duration: Duration(seconds: 2), +// margin: EdgeInsets.symmetric(horizontal: 16, vertical: 40), +// ), +// ); +// } +// } + +// Future _logout() async { +// await _authService.logout(); +// if (!mounted) return; +// Navigator.pushReplacement( +// context, +// MaterialPageRoute(builder: (_) => const LoginScreen()), +// ); +// } + +// void _enterChannel(Channel ch) { +// Navigator.push( +// context, +// MaterialPageRoute( +// builder: (_) => +// ChannelScreen(channel: ch, currentUserId: _currentUserId), +// ), +// ); +// } + +// void _openNotifications() async { +// await Navigator.push( +// context, +// MaterialPageRoute(builder: (_) => const NotificationsScreen()), +// ); +// _refresh(); +// } + +// Future _showCreateGroupDialog() async { +// String groupName = ''; +// final confirmed = await showDialog( +// context: context, +// builder: (ctx) => _CreateGroupDialog(onNameChanged: (v) => groupName = v), +// ); +// if (confirmed == true && groupName.trim().isNotEmpty) { +// final newChannel = await _api.createGroup(groupName.trim()); +// if (!mounted) return; +// ScaffoldMessenger.of(context).showSnackBar( +// SnackBar( +// content: Text( +// newChannel != null ? 'گروه ساخته شد' : 'خطا در ساخت گروه', +// style: const TextStyle(fontSize: 11, color: Colors.white), +// textAlign: TextAlign.center, +// ), +// backgroundColor: const Color(0xFF2C2C2E), +// behavior: SnackBarBehavior.floating, +// duration: const Duration(seconds: 2), +// margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 40), +// shape: RoundedRectangleBorder( +// borderRadius: BorderRadius.circular(20), +// ), +// ), +// ); +// if (newChannel != null) _loadChannels(); +// } +// } + +// @override +// void dispose() { +// _pageCtrl?.dispose(); +// super.dispose(); +// } + +// @override +// Widget build(BuildContext context) { +// if (_loading || _pageCtrl == null) { +// return const Scaffold( +// backgroundColor: Colors.black, +// body: Center( +// child: CircularProgressIndicator( +// color: Color(0xFF00C853), +// strokeWidth: 2, +// ), +// ), +// ); +// } + +// final totalPages = _channels.length + 1; // +1 for menu page + +// return Scaffold( +// backgroundColor: Colors.black, +// body: SafeArea( +// child: Column( +// children: [ +// Expanded( +// child: PageView.builder( +// controller: _pageCtrl!, +// scrollDirection: Axis.vertical, +// onPageChanged: (i) => setState(() => _currentPage = i), +// itemCount: totalPages, +// itemBuilder: (ctx, i) { +// if (i == 0) return _buildMenuPage(); +// return _buildChannelPage(_channels[i - 1]); +// }, +// ), +// ), +// _buildPageIndicator(totalPages), +// ], +// ), +// ), +// ); +// } + +// Widget _buildPageIndicator(int totalPages) { +// return Padding( +// padding: const EdgeInsets.only(bottom: 6, top: 2), +// child: Row( +// mainAxisAlignment: MainAxisAlignment.center, +// children: List.generate(totalPages, (i) { +// final isActive = i == _currentPage; +// if (i == 0) { +// return Padding( +// padding: const EdgeInsets.symmetric(horizontal: 2), +// child: Icon( +// Icons.menu, +// size: isActive ? 9 : 6, +// color: isActive ? Colors.white70 : Colors.white24, +// ), +// ); +// } +// return Padding( +// padding: const EdgeInsets.symmetric(horizontal: 2), +// child: Container( +// width: isActive ? 6 : 4, +// height: isActive ? 6 : 4, +// decoration: BoxDecoration( +// color: isActive ? const Color(0xFF00C853) : Colors.white24, +// shape: BoxShape.circle, +// ), +// ), +// ); +// }), +// ), +// ); +// } + +// Widget _buildMenuPage() { +// final batteryColor = _isCharging +// ? const Color(0xFF00C853) +// : _batteryLevel <= 15 +// ? const Color(0xFFFF1744) +// : _batteryLevel <= 30 +// ? const Color(0xFFFFAB00) +// : Colors.white60; + +// // تغییر ListView به SingleChildScrollView و Column +// return Column( +// mainAxisSize: MainAxisSize.min, // ستون فقط به اندازه محتوا فضا می‌گیرد +// children: [ +// // _// Battery display_ +// Container( +// height: 32, +// margin: const EdgeInsets.only(bottom: 6), +// padding: const EdgeInsets.symmetric(horizontal: 12), +// decoration: BoxDecoration( +// color: batteryColor.withValues(alpha: 0.1), +// borderRadius: BorderRadius.circular(12), +// border: Border.all( +// color: batteryColor.withValues(alpha: 0.3), +// width: 1, +// ), +// ), +// child: Row( +// children: [ +// Icon( +// _isCharging ? Icons.bolt : Icons.battery_std, +// color: batteryColor, +// size: 14, +// ), +// const SizedBox(width: 6), +// Text( +// _isCharging +// ? 'در حال شارژ — $_batteryLevel%' +// : 'باتری: $_batteryLevel%', +// style: TextStyle(color: batteryColor, fontSize: 10), +// ), +// ], +// ), +// ), +// const SizedBox(height: 6), +// _MenuItem( +// icon: Icons.notifications_outlined, +// label: _pendingNotifCount > 0 +// ? 'اعلان‌ها ($_pendingNotifCount)' +// : 'اعلان‌ها', +// color: _pendingNotifCount > 0 +// ? const Color(0xFFFF1744) +// : Colors.white70, +// onTap: _openNotifications, +// ), +// const SizedBox(height: 6), +// _MenuItem( +// icon: Icons.wifi, +// label: 'وای‌فای', +// color: const Color(0xFF2979FF), +// onTap: _openWifi, +// ), +// const SizedBox(height: 6), +// _MenuItem( +// icon: Icons.cell_tower, +// label: 'اینترنت / سیم‌کارت', +// color: const Color(0xFF00BCD4), +// onTap: _openInternetSettings, +// ), +// const SizedBox(height: 6), +// _MenuItem( +// icon: Icons.accessibility_new, +// label: 'تنظیمات دکمه‌ها', +// color: Colors.orangeAccent, +// onTap: _openAccessibilitySettings, +// ), +// const SizedBox(height: 6), +// _MenuItem( +// icon: Icons.add_circle_outline, +// label: 'گروه جدید', +// color: const Color(0xFF00C853), +// onTap: _showCreateGroupDialog, +// ), +// const SizedBox(height: 6), +// _MenuItem( +// icon: Icons.refresh, +// label: 'بروزرسانی', +// color: Colors.white70, +// onTap: _loading ? null : _refresh, +// ), +// const SizedBox(height: 6), +// _MenuItem( +// icon: Icons.launch, +// label: 'تغییر لانچر', +// color: Colors.white54, +// onTap: _openHomeSettings, +// ), +// const SizedBox(height: 6), +// _MenuItem( +// icon: Icons.logout, +// label: 'خروج', +// color: Colors.redAccent, +// onTap: _logout, +// ), +// ], +// ); +// } + +// Widget _buildChannelPage(Channel channel) { +// return Center( +// child: GestureDetector( +// onTap: () => _enterChannel(channel), +// child: LayoutBuilder( +// builder: (ctx, constraints) { +// final size = constraints.maxWidth * 0.72; +// return Container( +// width: size, +// height: size, +// decoration: BoxDecoration( +// color: const Color(0xFF1C1C1E), +// shape: BoxShape.circle, +// border: Border.all( +// color: const Color(0xFF00C853).withValues(alpha: 0.55), +// width: 2, +// ), +// boxShadow: [ +// BoxShadow( +// color: const Color(0xFF00C853).withValues(alpha: 0.12), +// blurRadius: 22, +// spreadRadius: 2, +// ), +// ], +// ), +// child: Column( +// mainAxisAlignment: MainAxisAlignment.center, +// children: [ +// Icon( +// channel.type == 'PUBLIC' ? Icons.radio : Icons.lock_outline, +// color: const Color(0xFF00C853), +// size: 22, +// ), +// const SizedBox(height: 8), +// Padding( +// padding: const EdgeInsets.symmetric(horizontal: 20), +// child: Text( +// channel.name, +// style: const TextStyle( +// color: Colors.white, +// fontSize: 13, +// fontWeight: FontWeight.bold, +// ), +// textAlign: TextAlign.center, +// maxLines: 2, +// overflow: TextOverflow.ellipsis, +// ), +// ), +// const SizedBox(height: 4), +// Text( +// channel.type == 'PUBLIC' ? 'عمومی' : 'خصوصی', +// style: const TextStyle(color: Colors.white38, fontSize: 9), +// ), +// ], +// ), +// ); +// }, +// ), +// ), +// ); +// } +// } + +// // ── Menu Item ────────────────────────────────────────────────────────────── + +// class _MenuItem extends StatelessWidget { +// final IconData icon; +// final String label; +// final Color color; +// final VoidCallback? onTap; + +// const _MenuItem({ +// required this.icon, +// required this.label, +// required this.color, +// this.onTap, +// }); + +// @override +// Widget build(BuildContext context) { +// return GestureDetector( +// onTap: onTap, +// child: Container( +// height: 38, +// padding: const EdgeInsets.symmetric(horizontal: 12), +// decoration: BoxDecoration( +// color: const Color(0xFF1C1C1E), +// borderRadius: BorderRadius.circular(12), +// ), +// child: Row( +// children: [ +// Icon(icon, color: color, size: 16), +// const SizedBox(width: 8), +// Expanded( +// child: Text(label, style: TextStyle(color: color, fontSize: 11)), +// ), +// ], +// ), +// ), +// ); +// } +// } + +// // ── Create Group Dialog ──────────────────────────────────────────────────── + +// class _CreateGroupDialog extends StatefulWidget { +// final ValueChanged onNameChanged; + +// const _CreateGroupDialog({required this.onNameChanged}); + +// @override +// State<_CreateGroupDialog> createState() => _CreateGroupDialogState(); +// } + +// class _CreateGroupDialogState extends State<_CreateGroupDialog> { +// final _ctrl = TextEditingController(); + +// @override +// void dispose() { +// _ctrl.dispose(); +// super.dispose(); +// } + +// @override +// Widget build(BuildContext context) { +// return AlertDialog( +// backgroundColor: const Color(0xFF1C1C1E), +// shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), +// contentPadding: const EdgeInsets.all(16), +// content: Column( +// mainAxisSize: MainAxisSize.min, +// children: [ +// const Icon( +// Icons.add_circle_outline, +// color: Color(0xFF00C853), +// size: 26, +// ), +// const SizedBox(height: 8), +// const Text( +// 'گروه جدید', +// style: TextStyle( +// color: Colors.white, +// fontSize: 12, +// fontWeight: FontWeight.bold, +// ), +// ), +// const SizedBox(height: 10), +// TextField( +// controller: _ctrl, +// autofocus: true, +// textAlign: TextAlign.center, +// style: const TextStyle(color: Colors.white, fontSize: 12), +// decoration: InputDecoration( +// hintText: 'نام گروه', +// hintStyle: const TextStyle(color: Colors.white38, fontSize: 11), +// filled: true, +// fillColor: Colors.white.withValues(alpha: 0.05), +// border: OutlineInputBorder( +// borderRadius: BorderRadius.circular(10), +// borderSide: BorderSide.none, +// ), +// contentPadding: const EdgeInsets.symmetric( +// horizontal: 12, +// vertical: 8, +// ), +// ), +// onChanged: widget.onNameChanged, +// ), +// const SizedBox(height: 12), +// Row( +// children: [ +// Expanded( +// child: TextButton( +// onPressed: () => Navigator.pop(context, false), +// child: const Text( +// 'انصراف', +// style: TextStyle(color: Colors.white54, fontSize: 11), +// ), +// ), +// ), +// Expanded( +// child: TextButton( +// onPressed: () => Navigator.pop(context, true), +// child: const Text( +// 'ساخت', +// style: TextStyle( +// color: Color(0xFF00C853), +// fontSize: 11, +// fontWeight: FontWeight.bold, +// ), +// ), +// ), +// ), +// ], +// ), +// ], +// ), +// ); +// } +// } diff --git a/Front/lib/screens/group_members_screen.dart b/Front/lib/screens/group_members_screen.dart index b046f21..2e5af38 100644 --- a/Front/lib/screens/group_members_screen.dart +++ b/Front/lib/screens/group_members_screen.dart @@ -49,9 +49,7 @@ class _GroupMembersScreenState extends State { String username = ''; final confirmed = await showDialog( context: context, - builder: (ctx) => _InviteDialog( - onUsernameChanged: (v) => username = v, - ), + builder: (ctx) => _InviteDialog(onUsernameChanged: (v) => username = v), ); if (confirmed == true && username.trim().isNotEmpty) { final err = await _api.inviteMember(widget.channel.id, username.trim()); @@ -63,11 +61,15 @@ class _GroupMembersScreenState extends State { style: const TextStyle(fontSize: 11), textAlign: TextAlign.center, ), - backgroundColor: err == null ? const Color(0xFF1C1C1E) : const Color(0xFF333333), + backgroundColor: err == null + ? const Color(0xFF1C1C1E) + : const Color(0xFF333333), behavior: SnackBarBehavior.floating, duration: const Duration(seconds: 2), margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 40), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20), + ), ), ); } @@ -83,11 +85,19 @@ class _GroupMembersScreenState extends State { content: Column( mainAxisSize: MainAxisSize.min, children: [ - const Icon(Icons.person_remove_outlined, color: Colors.red, size: 28), + const Icon( + Icons.person_remove_outlined, + color: Colors.red, + size: 28, + ), const SizedBox(height: 8), Text( 'حذف ${member.username}؟', - style: const TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.bold), + style: const TextStyle( + color: Colors.white, + fontSize: 12, + fontWeight: FontWeight.bold, + ), textAlign: TextAlign.center, ), const SizedBox(height: 12), @@ -96,13 +106,19 @@ class _GroupMembersScreenState extends State { Expanded( child: TextButton( onPressed: () => Navigator.pop(ctx, false), - child: const Text('انصراف', style: TextStyle(color: Colors.white54, fontSize: 11)), + child: const Text( + 'انصراف', + style: TextStyle(color: Colors.white54, fontSize: 11), + ), ), ), Expanded( child: TextButton( onPressed: () => Navigator.pop(ctx, true), - child: const Text('حذف', style: TextStyle(color: Colors.red, fontSize: 11)), + child: const Text( + 'حذف', + style: TextStyle(color: Colors.red, fontSize: 11), + ), ), ), ], @@ -118,12 +134,18 @@ class _GroupMembersScreenState extends State { if (err != null) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( - content: Text(err, style: const TextStyle(fontSize: 11), textAlign: TextAlign.center), + content: Text( + err, + style: const TextStyle(fontSize: 11), + textAlign: TextAlign.center, + ), backgroundColor: const Color(0xFF333333), behavior: SnackBarBehavior.floating, duration: const Duration(seconds: 2), margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 40), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20), + ), ), ); } else { @@ -136,100 +158,81 @@ class _GroupMembersScreenState extends State { Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.black, - body: SafeArea( - child: Column( - children: [ - // Header - Padding( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), - child: Row( - children: [ - IconButton( - onPressed: () => Navigator.pop(context), - padding: EdgeInsets.zero, - constraints: const BoxConstraints(minWidth: 28, minHeight: 28), - icon: const Icon(Icons.arrow_back_ios_new, color: Colors.white70, size: 14), + // استفاده از Stack برای قرار دادن دکمه شناور روی محتوا + body: Stack( + children: [ + SafeArea( + child: Column( + children: [ + // هدر ساده شده (فقط نمایش اطلاعات، بدون دکمه‌های کناری) + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 8, ), - const SizedBox(width: 4), - const Icon(Icons.group_outlined, color: Color(0xFF00C853), size: 14), - const SizedBox(width: 4), - const Expanded( - child: Text( - 'اعضا', - style: TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.bold), - ), - ), - // Invite button - IconButton( - onPressed: _showInviteDialog, - padding: EdgeInsets.zero, - constraints: const BoxConstraints(minWidth: 28, minHeight: 28), - icon: const Icon(Icons.person_add_outlined, color: Color(0xFF00C853), size: 16), - ), - IconButton( - onPressed: _loading ? null : _load, - padding: EdgeInsets.zero, - constraints: const BoxConstraints(minWidth: 28, minHeight: 28), - icon: const Icon(Icons.refresh, color: Colors.white54, size: 16), - ), - ], - ), - ), - - // Group name chip - Padding( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2), - child: Row( - children: [ - Container( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), - decoration: BoxDecoration( - color: const Color(0xFF00C853).withValues(alpha: 0.12), - borderRadius: BorderRadius.circular(20), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Icon( - widget.channel.type == 'PUBLIC' - ? Icons.public - : Icons.lock_outline, - color: const Color(0xFF00C853), - size: 10, - ), - const SizedBox(width: 4), + child: Column( + children: [ + // نام گروه و تعداد اعضا وسط‌چین + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + widget.channel.type == 'PUBLIC' + ? Icons.public + : Icons.lock_outline, + color: const Color(0xFF00C853), + size: 12, + ), + const SizedBox(width: 4), + Flexible( + child: Text( + widget.channel.name, + style: const TextStyle( + color: Color(0xFF00C853), + fontSize: 12, + fontWeight: FontWeight.bold, + ), + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + if (!_loading) Text( - widget.channel.name, - style: const TextStyle(color: Color(0xFF00C853), fontSize: 10), + '${_members.length} عضو', + style: const TextStyle( + color: Colors.white38, + fontSize: 10, + ), ), - ], - ), + ], ), - if (!_loading) ...[ - const SizedBox(width: 6), - Text( - '${_members.length} عضو', - style: const TextStyle(color: Colors.white38, fontSize: 10), - ), - ], - ], - ), - ), - const SizedBox(height: 4), + ), + const Divider(height: 1, color: Color(0xFF333333)), - // Content - Expanded( - child: _loading - ? const Center( - child: CircularProgressIndicator(color: Color(0xFF00C853), strokeWidth: 2), - ) - : _members.isEmpty + // لیست اعضا + Expanded( + child: _loading ? const Center( - child: Text('عضوی یافت نشد', - style: TextStyle(color: Colors.white38, fontSize: 11)), + child: CircularProgressIndicator( + color: Color(0xFF00C853), + strokeWidth: 2, + ), + ) + : _members.isEmpty + ? const Center( + child: Text( + 'عضوی یافت نشد', + style: TextStyle( + color: Colors.white38, + fontSize: 11, + ), + ), ) : ListView.builder( - padding: const EdgeInsets.only(bottom: 4), + padding: const EdgeInsets.only( + bottom: 60, + ), // فضای خالی برای دکمه شناور پایین itemCount: _members.length, itemBuilder: (ctx, i) { final m = _members[i]; @@ -242,9 +245,32 @@ class _GroupMembersScreenState extends State { ); }, ), + ), + ], ), - ], - ), + ), + + // دکمه شناور افزودن عضو (فقط برای مدیر) در پایین صفحه وسط + if (_isManager) + Positioned( + bottom: 10, + left: 0, + right: 0, + child: Center( + child: FloatingActionButton( + heroTag: "invite_btn", // جلوگیری از تداخل HeroTag + mini: true, // سایز کوچکتر مناسب ساعت + onPressed: _showInviteDialog, + backgroundColor: const Color(0xFF00C853), + child: const Icon( + Icons.person_add, + color: Colors.black, + size: 20, + ), + ), + ), + ), + ], ), ); } @@ -267,18 +293,18 @@ class _MemberTile extends StatelessWidget { Widget build(BuildContext context) { return Container( margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), - height: 40, + height: 36, // کاهش ارتفاع آیتم decoration: BoxDecoration( color: const Color(0xFF1C1C1E), - borderRadius: BorderRadius.circular(12), + borderRadius: BorderRadius.circular(10), ), - padding: const EdgeInsets.symmetric(horizontal: 10), + padding: const EdgeInsets.symmetric(horizontal: 8), child: Row( children: [ // Online indicator Container( - width: 7, - height: 7, + width: 6, + height: 6, decoration: BoxDecoration( shape: BoxShape.circle, color: member.isOnline ? const Color(0xFF00C853) : Colors.white24, @@ -292,7 +318,9 @@ class _MemberTile extends StatelessWidget { style: TextStyle( color: isMe ? const Color(0xFF00C853) : Colors.white, fontSize: 11, - fontWeight: member.isManager ? FontWeight.bold : FontWeight.normal, + fontWeight: member.isManager + ? FontWeight.bold + : FontWeight.normal, ), overflow: TextOverflow.ellipsis, ), @@ -300,14 +328,14 @@ class _MemberTile extends StatelessWidget { // Role badge if (member.isManager) Container( - padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2), + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1), decoration: BoxDecoration( - color: const Color(0xFF00C853).withValues(alpha: 0.15), - borderRadius: BorderRadius.circular(8), + color: const Color(0xFF00C853).withOpacity(0.15), + borderRadius: BorderRadius.circular(6), ), child: const Text( 'مدیر', - style: TextStyle(color: Color(0xFF00C853), fontSize: 9), + style: TextStyle(color: Color(0xFF00C853), fontSize: 8), ), ), // Remove button @@ -315,7 +343,11 @@ class _MemberTile extends StatelessWidget { const SizedBox(width: 4), GestureDetector( onTap: onRemove, - child: const Icon(Icons.remove_circle_outline, color: Colors.red, size: 16), + child: const Icon( + Icons.remove_circle_outline, + color: Colors.red, + size: 16, + ), ), ], ], @@ -353,11 +385,19 @@ class _InviteDialogState extends State<_InviteDialog> { content: Column( mainAxisSize: MainAxisSize.min, children: [ - const Icon(Icons.person_add_outlined, color: Color(0xFF00C853), size: 26), + const Icon( + Icons.person_add_outlined, + color: Color(0xFF00C853), + size: 26, + ), const SizedBox(height: 8), const Text( 'دعوت عضو', - style: TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.bold), + style: TextStyle( + color: Colors.white, + fontSize: 12, + fontWeight: FontWeight.bold, + ), ), const SizedBox(height: 10), TextField( @@ -369,12 +409,15 @@ class _InviteDialogState extends State<_InviteDialog> { hintText: 'نام کاربری', hintStyle: const TextStyle(color: Colors.white38, fontSize: 11), filled: true, - fillColor: Colors.white.withValues(alpha: 0.05), + fillColor: Colors.white.withOpacity(0.05), border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none, ), - contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + contentPadding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 8, + ), ), onChanged: widget.onUsernameChanged, ), @@ -384,13 +427,23 @@ class _InviteDialogState extends State<_InviteDialog> { Expanded( child: TextButton( onPressed: () => Navigator.pop(context, false), - child: const Text('انصراف', style: TextStyle(color: Colors.white54, fontSize: 11)), + child: const Text( + 'انصراف', + style: TextStyle(color: Colors.white54, fontSize: 11), + ), ), ), Expanded( child: TextButton( onPressed: () => Navigator.pop(context, true), - child: const Text('ارسال', style: TextStyle(color: Color(0xFF00C853), fontSize: 11, fontWeight: FontWeight.bold)), + child: const Text( + 'ارسال', + style: TextStyle( + color: Color(0xFF00C853), + fontSize: 11, + fontWeight: FontWeight.bold, + ), + ), ), ), ], diff --git a/Front/lib/screens/home_screen_old.dart b/Front/lib/screens/home_screen_old.dart new file mode 100644 index 0000000..6c6dbe4 --- /dev/null +++ b/Front/lib/screens/home_screen_old.dart @@ -0,0 +1,247 @@ +// import 'dart:async'; +// import 'package:flutter/material.dart'; +// import 'package:flutter/services.dart'; +// import 'channel_list_screen.dart'; + +// class HomeScreen extends StatefulWidget { +// const HomeScreen({super.key}); + +// @override +// State createState() => _HomeScreenState(); +// } + +// class _HomeScreenState extends State { +// static final _channel = const MethodChannel('com.example.watch/launcher'); + +// int _batteryLevel = 0; +// bool _isCharging = false; +// Timer? _batteryTimer; + +// @override +// void initState() { +// super.initState(); +// _loadBattery(); +// _batteryTimer = Timer.periodic( +// const Duration(seconds: 30), +// (_) => _loadBattery(), +// ); +// } + +// Future _loadBattery() async { +// try { +// final info = await _channel.invokeMapMethod( +// 'getBatteryInfo', +// ); +// if (!mounted || info == null) return; +// setState(() { +// _batteryLevel = (info['level'] as int?) ?? 0; +// _isCharging = (info['isCharging'] as bool?) ?? false; +// }); +// } catch (_) {} +// } + +// @override +// void dispose() { +// _batteryTimer?.cancel(); +// super.dispose(); +// } + +// Color get _batteryColor { +// if (_isCharging) return const Color(0xFF00C853); +// if (_batteryLevel <= 15) return const Color(0xFFFF1744); +// if (_batteryLevel <= 30) return const Color(0xFFFFAB00); +// return Colors.white54; +// } + +// @override +// Widget build(BuildContext context) { +// return Scaffold( +// backgroundColor: Colors.black, +// body: SafeArea( +// child: Stack( +// children: [ +// // ── Battery indicator (top right) ────────────────────────── +// Positioned( +// top: 4, +// right: 8, +// child: Row( +// mainAxisSize: MainAxisSize.min, +// children: [ +// if (_isCharging) +// const Icon(Icons.bolt, color: Color(0xFF00C853), size: 11), +// Text( +// '$_batteryLevel%', +// style: TextStyle(color: _batteryColor, fontSize: 9), +// ), +// ], +// ), +// ), + +// // ── Charging banner ──────────────────────────────────────── +// if (_isCharging) +// Positioned( +// bottom: 10, +// left: 0, +// right: 0, +// child: Row( +// mainAxisAlignment: MainAxisAlignment.center, +// children: [ +// Container( +// padding: const EdgeInsets.symmetric( +// horizontal: 10, +// vertical: 3, +// ), +// decoration: BoxDecoration( +// color: const Color(0xFF00C853).withValues(alpha: 0.15), +// borderRadius: BorderRadius.circular(20), +// border: Border.all( +// color: const Color(0xFF00C853).withValues(alpha: 0.4), +// width: 1, +// ), +// ), +// child: Row( +// mainAxisSize: MainAxisSize.min, +// children: [ +// const Icon( +// Icons.bolt, +// color: Color(0xFF00C853), +// size: 11, +// ), +// const SizedBox(width: 3), +// Text( +// 'در حال شارژ — $_batteryLevel%', +// style: const TextStyle( +// color: Color(0xFF00C853), +// fontSize: 9, +// ), +// ), +// ], +// ), +// ), +// ], +// ), +// ), + +// // ── App grid ─────────────────────────────────────────────── +// Center( +// child: Column( +// mainAxisAlignment: MainAxisAlignment.center, +// children: [ +// const Text( +// 'برنامه‌ها', +// style: TextStyle( +// color: Colors.white38, +// fontSize: 9, +// letterSpacing: 0.5, +// ), +// ), +// const SizedBox(height: 16), +// Row( +// mainAxisAlignment: MainAxisAlignment.center, +// children: [ +// _AppIcon( +// icon: Icons.radio, +// label: 'بی‌سیم', +// color: const Color(0xFF00C853), +// onTap: () { +// Navigator.push( +// context, +// MaterialPageRoute( +// builder: (_) => const ChannelListScreen(), +// ), +// ); +// }, +// ), +// const SizedBox(width: 20), +// _AppIcon( +// icon: Icons.phone, +// label: 'تلفن', +// color: const Color(0xFF2979FF), +// onTap: () { +// ScaffoldMessenger.of(context).showSnackBar( +// const SnackBar( +// content: Text( +// 'به زودی', +// textAlign: TextAlign.center, +// style: TextStyle( +// fontSize: 11, +// color: Colors.white, +// ), +// ), +// duration: Duration(seconds: 1), +// backgroundColor: Color(0xFF2C2C2E), +// behavior: SnackBarBehavior.floating, +// margin: EdgeInsets.symmetric( +// horizontal: 24, +// vertical: 40, +// ), +// ), +// ); +// }, +// ), +// ], +// ), +// ], +// ), +// ), +// ], +// ), +// ), +// ); +// } +// } + +// class _AppIcon extends StatelessWidget { +// final IconData icon; +// final String label; +// final Color color; +// final VoidCallback onTap; + +// const _AppIcon({ +// required this.icon, +// required this.label, +// required this.color, +// required this.onTap, +// }); + +// @override +// Widget build(BuildContext context) { +// return GestureDetector( +// onTap: onTap, +// child: Column( +// mainAxisSize: MainAxisSize.min, +// children: [ +// Container( +// width: 58, +// height: 58, +// decoration: BoxDecoration( +// color: color.withValues(alpha: 0.13), +// shape: BoxShape.circle, +// border: Border.all( +// color: color.withValues(alpha: 0.45), +// width: 1.5, +// ), +// boxShadow: [ +// BoxShadow( +// color: color.withValues(alpha: 0.18), +// blurRadius: 12, +// spreadRadius: 1, +// ), +// ], +// ), +// child: Icon(icon, color: color, size: 28), +// ), +// const SizedBox(height: 7), +// Text( +// label, +// style: const TextStyle( +// color: Colors.white, +// fontSize: 11, +// fontWeight: FontWeight.w500, +// ), +// ), +// ], +// ), +// ); +// } +// } diff --git a/Front/lib/screens/login_screen.dart b/Front/lib/screens/login_screen.dart index aab5f6b..8337fbe 100644 --- a/Front/lib/screens/login_screen.dart +++ b/Front/lib/screens/login_screen.dart @@ -1,7 +1,8 @@ import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import '../services/auth_service.dart'; import '../services/api_service.dart'; -import 'channel_list_screen.dart'; +import '../home/home_screen.dart'; class LoginScreen extends StatefulWidget { const LoginScreen({super.key}); @@ -18,6 +19,11 @@ class _LoginScreenState extends State { bool _loading = false; String? _error; + // کانال ارتباطی با کد نیتیو برای تنظیمات اینترنت + static final _nativeChannel = const MethodChannel( + 'com.example.watch/launcher', + ); + @override void initState() { super.initState(); @@ -31,6 +37,31 @@ class _LoginScreenState extends State { super.dispose(); } + // متد باز کردن تنظیمات اینترنت + Future _openInternetSettings() async { + try { + await _nativeChannel.invokeMethod('openInternetSettings'); + } catch (_) { + _showSnack('تنظیمات اینترنت در دسترس نیست'); + } + } + + // متد نمایش پیام (SnackBar) + void _showSnack(String msg) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + msg, + style: const TextStyle(fontSize: 10, color: Colors.white), + ), + backgroundColor: const Color(0xFF2C2C2E), + duration: const Duration(seconds: 2), + behavior: SnackBarBehavior.floating, + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 40), + ), + ); + } + Future _login() async { final username = _usernameCtrl.text.trim(); final secret = _secretCtrl.text.trim(); @@ -49,7 +80,7 @@ class _LoginScreenState extends State { if (ok) { Navigator.pushReplacement( context, - MaterialPageRoute(builder: (_) => const ChannelListScreen()), + MaterialPageRoute(builder: (_) => const HomeScreen()), ); } else { setState(() { @@ -67,150 +98,203 @@ class _LoginScreenState extends State { child: SingleChildScrollView( child: ConstrainedBox( constraints: BoxConstraints( - minHeight: MediaQuery.of(context).size.height - + minHeight: + MediaQuery.of(context).size.height - MediaQuery.of(context).padding.top - MediaQuery.of(context).padding.bottom, ), - child: Center( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8), - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - mainAxisSize: MainAxisSize.min, - children: [ - // Icon - Container( - width: 36, - height: 36, - decoration: BoxDecoration( - color: const Color(0xFF00C853).withValues(alpha: 0.15), - shape: BoxShape.circle, - ), - child: const Icon( - Icons.settings_input_antenna, - color: Color(0xFF00C853), - size: 18, - ), - ), - const SizedBox(height: 4), - const Text( - 'WalkieTalkie', - style: TextStyle( - color: Colors.white, - fontSize: 12, - fontWeight: FontWeight.bold, - letterSpacing: 1, - ), - ), - const SizedBox(height: 10), - - // Username input - SizedBox( - height: 32, - child: TextField( - controller: _usernameCtrl, - style: const TextStyle(color: Colors.white, fontSize: 11), - textAlign: TextAlign.center, - decoration: InputDecoration( - hintText: 'نام کاربری', - hintStyle: - const TextStyle(color: Colors.white38, fontSize: 10), - filled: true, - fillColor: const Color(0xFF1C1C1E), - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(16), - borderSide: BorderSide.none, - ), - contentPadding: const EdgeInsets.symmetric( - horizontal: 10, vertical: 0), - ), - onSubmitted: (_) => - FocusScope.of(context).nextFocus(), - ), - ), - const SizedBox(height: 6), - - // Secret input - SizedBox( - height: 32, - child: TextField( - controller: _secretCtrl, - style: const TextStyle(color: Colors.white, fontSize: 11), - textAlign: TextAlign.center, - obscureText: true, - decoration: InputDecoration( - hintText: 'کلید ورود', - hintStyle: - const TextStyle(color: Colors.white38, fontSize: 10), - filled: true, - fillColor: const Color(0xFF1C1C1E), - border: OutlineInputBorder( - borderRadius: BorderRadius.circular(16), - borderSide: BorderSide.none, - ), - contentPadding: const EdgeInsets.symmetric( - horizontal: 10, vertical: 0), - ), - onSubmitted: (_) => _login(), - ), - ), - - // Error - SizedBox( - height: 16, - child: _error != null - ? Text( - _error!, - style: const TextStyle( - color: Color(0xFFFF1744), fontSize: 9), - ) - : null, - ), - - // Login button - GestureDetector( - onTap: _loading ? null : _login, - child: AnimatedContainer( - duration: const Duration(milliseconds: 200), - width: 50, - height: 50, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + // محتوای اصلی فرم + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 20, + vertical: 8, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + // Icon + Container( + width: 36, + height: 36, decoration: BoxDecoration( - color: _loading - ? const Color(0xFF424242) - : const Color(0xFF00C853), + color: const Color(0xFF00C853).withOpacity(0.15), shape: BoxShape.circle, - boxShadow: _loading - ? null - : [ - BoxShadow( - color: const Color(0xFF00C853).withValues(alpha: 0.4), - blurRadius: 10, - spreadRadius: 1, - ), - ], ), - child: _loading - ? const Center( - child: SizedBox( - width: 18, - height: 18, - child: CircularProgressIndicator( - color: Colors.white, - strokeWidth: 2, - ), + child: const Icon( + Icons.settings_input_antenna, + color: Color(0xFF00C853), + size: 18, + ), + ), + const SizedBox(height: 4), + const Text( + 'WalkieTalkie', + style: TextStyle( + color: Colors.white, + fontSize: 12, + fontWeight: FontWeight.bold, + letterSpacing: 1, + ), + ), + const SizedBox(height: 10), + + // Username input + SizedBox( + height: 32, + child: TextField( + controller: _usernameCtrl, + style: const TextStyle( + color: Colors.white, + fontSize: 11, + ), + textAlign: TextAlign.center, + decoration: InputDecoration( + hintText: 'نام کاربری', + hintStyle: const TextStyle( + color: Colors.white38, + fontSize: 10, + ), + filled: true, + fillColor: const Color(0xFF1C1C1E), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(16), + borderSide: BorderSide.none, + ), + contentPadding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 0, + ), + ), + onSubmitted: (_) => + FocusScope.of(context).nextFocus(), + ), + ), + const SizedBox(height: 6), + + // Secret input + SizedBox( + height: 32, + child: TextField( + controller: _secretCtrl, + style: const TextStyle( + color: Colors.white, + fontSize: 11, + ), + textAlign: TextAlign.center, + obscureText: true, + decoration: InputDecoration( + hintText: 'کلید ورود', + hintStyle: const TextStyle( + color: Colors.white38, + fontSize: 10, + ), + filled: true, + fillColor: const Color(0xFF1C1C1E), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(16), + borderSide: BorderSide.none, + ), + contentPadding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: 0, + ), + ), + onSubmitted: (_) => _login(), + ), + ), + + // Error + SizedBox( + height: 16, + child: _error != null + ? Text( + _error!, + style: const TextStyle( + color: Color(0xFFFF1744), + fontSize: 9, ), ) - : const Icon(Icons.login, color: Colors.white, size: 22), + : null, + ), + + // Login button + GestureDetector( + onTap: _loading ? null : _login, + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), + width: 50, + height: 50, + decoration: BoxDecoration( + color: _loading + ? const Color(0xFF424242) + : const Color(0xFF00C853), + shape: BoxShape.circle, + boxShadow: _loading + ? null + : [ + BoxShadow( + color: const Color( + 0xFF00C853, + ).withOpacity(0.4), + blurRadius: 10, + spreadRadius: 1, + ), + ], + ), + child: _loading + ? const Center( + child: SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator( + color: Colors.white, + strokeWidth: 2, + ), + ), + ) + : const Icon( + Icons.login, + color: Colors.white, + size: 22, + ), + ), + ), + const SizedBox(height: 4), + const Text( + 'ورود', + style: TextStyle(color: Colors.white38, fontSize: 9), + ), + ], + ), + ), + + const SizedBox(height: 20), + + // دکمه تنظیمات اینترنت (پایین صفحه وسط) + GestureDetector( + onTap: _openInternetSettings, + child: Container( + width: 40, + height: 40, + decoration: BoxDecoration( + color: const Color(0xFF1C1C1E), + shape: BoxShape.circle, + border: Border.all( + color: const Color(0xFF00BCD4).withOpacity(0.3), + width: 1, ), ), - const SizedBox(height: 4), - const Text( - 'ورود', - style: TextStyle(color: Colors.white38, fontSize: 9), + child: const Icon( + Icons.wifi, + color: Color(0xFF00BCD4), + size: 20, ), - ], + ), ), - ), + ], ), ), ), diff --git a/Front/lib/screens/notifications_screen.dart b/Front/lib/screens/notifications_screen.dart index 1a34914..b825a66 100644 --- a/Front/lib/screens/notifications_screen.dart +++ b/Front/lib/screens/notifications_screen.dart @@ -42,12 +42,18 @@ class _NotificationsScreenState extends State { if (err != null) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( - content: Text(err, style: const TextStyle(fontSize: 11), textAlign: TextAlign.center), + content: Text( + err, + style: const TextStyle(fontSize: 11), + textAlign: TextAlign.center, + ), backgroundColor: const Color(0xFF333333), behavior: SnackBarBehavior.floating, duration: const Duration(seconds: 2), margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 40), - shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20), + ), ), ); } else { @@ -63,64 +69,76 @@ class _NotificationsScreenState extends State { body: SafeArea( child: Column( children: [ - // Header + // Header ساده و وسط‌چین (بدون دکمه‌های کناری) Padding( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), child: Row( + mainAxisAlignment: MainAxisAlignment.center, children: [ - IconButton( - onPressed: () => Navigator.pop(context), - padding: EdgeInsets.zero, - constraints: const BoxConstraints(minWidth: 28, minHeight: 28), - icon: const Icon(Icons.arrow_back_ios_new, color: Colors.white70, size: 14), + const Icon( + Icons.notifications_outlined, + color: Color(0xFF00C853), + size: 16, ), - const SizedBox(width: 4), - const Icon(Icons.notifications_outlined, color: Color(0xFF00C853), size: 14), - const SizedBox(width: 4), - const Expanded( - child: Text( - 'اعلان‌ها', - style: TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.bold), + const SizedBox(width: 6), + const Text( + 'اعلان‌ها', + style: TextStyle( + color: Colors.white, + fontSize: 14, + fontWeight: FontWeight.bold, ), ), - IconButton( - onPressed: _loading ? null : _load, - padding: EdgeInsets.zero, - constraints: const BoxConstraints(minWidth: 28, minHeight: 28), - icon: const Icon(Icons.refresh, color: Colors.white54, size: 16), - ), ], ), ), + const Divider(height: 1, color: Color(0xFF333333)), // Content Expanded( child: _loading ? const Center( - child: CircularProgressIndicator(color: Color(0xFF00C853), strokeWidth: 2), + child: CircularProgressIndicator( + color: Color(0xFF00C853), + strokeWidth: 2, + ), ) : _notifications.isEmpty - ? const Center( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - Icon(Icons.notifications_off_outlined, color: Colors.white24, size: 28), - SizedBox(height: 6), - Text('اعلانی وجود ندارد', - style: TextStyle(color: Colors.white38, fontSize: 11)), - ], + ? const Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.notifications_off_outlined, + color: Colors.white24, + size: 32, ), - ) - : ListView.builder( - padding: const EdgeInsets.only(bottom: 4), - itemCount: _notifications.length, - itemBuilder: (ctx, i) => _NotifTile( - notif: _notifications[i], - isProcessing: _processing.contains(_notifications[i].id), - onAccept: () => _respond(_notifications[i], true), - onReject: () => _respond(_notifications[i], false), + SizedBox(height: 8), + Text( + 'اعلانی وجود ندارد', + style: TextStyle( + color: Colors.white38, + fontSize: 12, + ), ), + ], + ), + ) + : ListView.builder( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 8, + ), + itemCount: _notifications.length, + itemBuilder: (ctx, i) => _NotifTile( + notif: _notifications[i], + isProcessing: _processing.contains( + _notifications[i].id, ), + onAccept: () => _respond(_notifications[i], true), + onReject: () => _respond(_notifications[i], false), + ), + ), ), ], ), @@ -157,16 +175,16 @@ class _NotifTile extends StatelessWidget { } return Container( - margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + margin: const EdgeInsets.only(bottom: 8), // فاصله عمودی بین آیتم‌ها decoration: BoxDecoration( color: const Color(0xFF1C1C1E), borderRadius: BorderRadius.circular(12), border: Border.all( - color: isPending ? statusColor.withValues(alpha: 0.4) : Colors.transparent, + color: isPending ? statusColor.withOpacity(0.4) : Colors.transparent, width: 1, ), ), - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8), + padding: const EdgeInsets.all(10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -175,15 +193,15 @@ class _NotifTile extends StatelessWidget { Icon( isJoin ? Icons.group_add_outlined : Icons.campaign_outlined, color: statusColor, - size: 13, + size: 14, ), - const SizedBox(width: 5), + const SizedBox(width: 6), Expanded( child: Text( notif.title, style: const TextStyle( color: Colors.white, - fontSize: 11, + fontSize: 12, fontWeight: FontWeight.w600, ), overflow: TextOverflow.ellipsis, @@ -195,37 +213,47 @@ class _NotifTile extends StatelessWidget { const SizedBox(height: 4), Text( notif.description!, - style: const TextStyle(color: Colors.white60, fontSize: 10), - maxLines: 2, + style: const TextStyle(color: Colors.white70, fontSize: 11), + maxLines: 3, overflow: TextOverflow.ellipsis, ), ], if (isJoin && isPending) ...[ - const SizedBox(height: 6), + const SizedBox(height: 8), if (isProcessing) const Center( child: SizedBox( - width: 14, - height: 14, - child: CircularProgressIndicator(color: Color(0xFF00C853), strokeWidth: 1.5), + width: 16, + height: 16, + child: CircularProgressIndicator( + color: Color(0xFF00C853), + strokeWidth: 2, + ), ), ) else Row( - mainAxisAlignment: MainAxisAlignment.end, + mainAxisAlignment: MainAxisAlignment.end, // دکمه‌ها سمت راست children: [ // Reject GestureDetector( onTap: onReject, child: Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 6, + ), decoration: BoxDecoration( - color: Colors.red.withValues(alpha: 0.15), + color: Colors.red.withOpacity(0.15), borderRadius: BorderRadius.circular(20), ), child: const Text( 'رد', - style: TextStyle(color: Colors.red, fontSize: 10, fontWeight: FontWeight.bold), + style: TextStyle( + color: Colors.red, + fontSize: 11, + fontWeight: FontWeight.bold, + ), ), ), ), @@ -234,14 +262,21 @@ class _NotifTile extends StatelessWidget { GestureDetector( onTap: onAccept, child: Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 6, + ), decoration: BoxDecoration( - color: const Color(0xFF00C853).withValues(alpha: 0.15), + color: const Color(0xFF00C853).withOpacity(0.15), borderRadius: BorderRadius.circular(20), ), child: const Text( 'قبول', - style: TextStyle(color: Color(0xFF00C853), fontSize: 10, fontWeight: FontWeight.bold), + style: TextStyle( + color: Color(0xFF00C853), + fontSize: 11, + fontWeight: FontWeight.bold, + ), ), ), ), @@ -251,10 +286,10 @@ class _NotifTile extends StatelessWidget { if (!isPending) ...[ const SizedBox(height: 4), Align( - alignment: Alignment.centerLeft, + alignment: Alignment.centerRight, child: Text( notif.isAccepted == true ? 'پذیرفته شد' : 'رد شد', - style: TextStyle(color: statusColor, fontSize: 9), + style: TextStyle(color: statusColor, fontSize: 10), ), ), ], diff --git a/Front/lib/screens/wifi_screen.dart b/Front/lib/screens/wifi_screen.dart new file mode 100644 index 0000000..8a93bf2 --- /dev/null +++ b/Front/lib/screens/wifi_screen.dart @@ -0,0 +1,334 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +class WifiScreen extends StatefulWidget { + const WifiScreen({super.key}); + + @override + State createState() => _WifiScreenState(); +} + +class _WifiScreenState extends State { + static final _channel = const MethodChannel('com.example.watch/launcher'); + + List> _networks = []; + bool _loading = true; + String? _error; + + @override + void initState() { + super.initState(); + _scan(); + } + + Future _scan() async { + setState(() { + _loading = true; + _error = null; + }); + try { + final raw = await _channel.invokeListMethod('getWifiList'); + if (!mounted) return; + setState(() { + _networks = (raw ?? []) + .map((e) => Map.from(e as Map)) + .toList(); + _loading = false; + if (_networks.isEmpty) _error = 'شبکه‌ای یافت نشد'; + }); + } catch (e) { + if (!mounted) return; + setState(() { + _loading = false; + _error = 'خطا در اسکن وای‌فای'; + }); + } + } + + Future _openWifiSettings() async { + try { + await _channel.invokeMethod('openWifiSettings'); + } catch (_) {} + } + + Future _connectOrSuggest(String ssid, String password) async { + try { + final ok = await _channel.invokeMethod( + 'connectToWifi', + {'ssid': ssid, 'password': password}, + ); + if (!mounted) return; + if (ok == true) { + _showSnack('درخواست اتصال به "$ssid" ارسال شد'); + } else { + _openWifiSettings(); + } + } catch (_) { + _openWifiSettings(); + } + } + + void _showSnack(String msg) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text(msg, + style: const TextStyle(fontSize: 10, color: Colors.white), + textAlign: TextAlign.center), + backgroundColor: const Color(0xFF2C2C2E), + behavior: SnackBarBehavior.floating, + duration: const Duration(seconds: 2), + margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 40), + )); + } + + int _bars(int level) { + if (level >= -50) return 3; + if (level >= -70) return 2; + return 1; + } + + IconData _wifiIcon(int bars) { + if (bars >= 3) return Icons.wifi; + if (bars == 2) return Icons.wifi_2_bar; + return Icons.wifi_1_bar; + } + + void _onNetworkTap(String ssid, bool secured) { + if (secured) { + _showPasswordDialog(ssid); + } else { + _connectOrSuggest(ssid, ''); + } + } + + void _showPasswordDialog(String ssid) async { + String password = ''; + final confirmed = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + backgroundColor: const Color(0xFF1C1C1E), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)), + contentPadding: const EdgeInsets.all(14), + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.wifi_password, color: Color(0xFF00C853), size: 22), + const SizedBox(height: 6), + Text(ssid, + style: const TextStyle( + color: Colors.white, + fontSize: 11, + fontWeight: FontWeight.bold), + textAlign: TextAlign.center), + const SizedBox(height: 10), + TextField( + autofocus: true, + obscureText: true, + textAlign: TextAlign.center, + style: const TextStyle(color: Colors.white, fontSize: 11), + decoration: InputDecoration( + hintText: 'رمز عبور', + hintStyle: + const TextStyle(color: Colors.white38, fontSize: 10), + filled: true, + fillColor: Colors.white.withValues(alpha: 0.05), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + borderSide: BorderSide.none), + contentPadding: + const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + ), + onChanged: (v) => password = v, + ), + const SizedBox(height: 10), + Row( + children: [ + Expanded( + child: TextButton( + onPressed: () => Navigator.pop(ctx, false), + child: const Text('انصراف', + style: + TextStyle(color: Colors.white54, fontSize: 11)), + ), + ), + Expanded( + child: TextButton( + onPressed: () => Navigator.pop(ctx, true), + child: const Text('اتصال', + style: TextStyle( + color: Color(0xFF00C853), + fontSize: 11, + fontWeight: FontWeight.bold)), + ), + ), + ], + ), + ], + ), + ), + ); + if (confirmed == true && password.isNotEmpty) { + _connectOrSuggest(ssid, password); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: Colors.black, + body: SafeArea( + child: Column( + children: [ + // Header + Padding( + padding: + const EdgeInsets.symmetric(horizontal: 8, vertical: 6), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + GestureDetector( + onTap: () => Navigator.pop(context), + child: const Icon(Icons.arrow_back_ios_new, + color: Colors.white54, size: 14), + ), + const SizedBox(width: 6), + const Icon(Icons.wifi, color: Color(0xFF00C853), size: 14), + const SizedBox(width: 6), + const Text('وای‌فای', + style: TextStyle( + color: Colors.white, + fontSize: 13, + fontWeight: FontWeight.bold)), + const SizedBox(width: 8), + GestureDetector( + onTap: _loading ? null : _scan, + child: Icon(Icons.refresh, + color: _loading ? Colors.white24 : Colors.white54, + size: 14), + ), + ], + ), + ), + + // Content + Expanded( + child: _loading + ? const Center( + child: CircularProgressIndicator( + color: Color(0xFF00C853), strokeWidth: 2)) + : _error != null && _networks.isEmpty + ? Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.wifi_off, + color: Colors.white38, size: 24), + const SizedBox(height: 6), + Text(_error!, + style: const TextStyle( + color: Colors.white38, fontSize: 11)), + const SizedBox(height: 10), + GestureDetector( + onTap: _openWifiSettings, + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 14, vertical: 6), + decoration: BoxDecoration( + color: const Color(0xFF1C1C1E), + borderRadius: BorderRadius.circular(12), + ), + child: const Text('تنظیمات وای‌فای', + style: TextStyle( + color: Color(0xFF00C853), + fontSize: 10)), + ), + ), + ], + ), + ) + : ListView.builder( + padding: const EdgeInsets.only(bottom: 4), + itemCount: _networks.length + 1, + itemBuilder: (ctx, i) { + // Last item: settings link + if (i == _networks.length) { + return Padding( + padding: const EdgeInsets.symmetric( + horizontal: 8, vertical: 3), + child: GestureDetector( + onTap: _openWifiSettings, + child: Container( + height: 34, + decoration: BoxDecoration( + color: const Color(0xFF1C1C1E), + borderRadius: + BorderRadius.circular(12), + ), + child: const Row( + mainAxisAlignment: + MainAxisAlignment.center, + children: [ + Icon(Icons.settings, + size: 12, + color: Colors.white38), + SizedBox(width: 4), + Text('تنظیمات وای‌فای', + style: TextStyle( + color: Colors.white38, + fontSize: 10)), + ], + ), + ), + ), + ); + } + + final net = _networks[i]; + final ssid = (net['ssid'] as String?) ?? ''; + final level = (net['level'] as int?) ?? -100; + final secured = + (net['secured'] as bool?) ?? false; + final bars = _bars(level); + + return GestureDetector( + onTap: () => _onNetworkTap(ssid, secured), + child: Container( + margin: const EdgeInsets.symmetric( + horizontal: 8, vertical: 2), + height: 40, + decoration: BoxDecoration( + color: const Color(0xFF1C1C1E), + borderRadius: BorderRadius.circular(12), + ), + padding: const EdgeInsets.symmetric( + horizontal: 10), + child: Row( + children: [ + Icon(_wifiIcon(bars), + color: const Color(0xFF00C853), + size: 14), + const SizedBox(width: 8), + Expanded( + child: Text( + ssid, + style: const TextStyle( + color: Colors.white, + fontSize: 11), + overflow: TextOverflow.ellipsis, + ), + ), + if (secured) + const Icon(Icons.lock_outline, + color: Colors.white38, size: 10), + ], + ), + ), + ); + }, + ), + ), + ], + ), + ), + ); + } +} diff --git a/Front/lib/services/api_service.dart b/Front/lib/services/api_service.dart index 6ed9494..6e9f47f 100644 --- a/Front/lib/services/api_service.dart +++ b/Front/lib/services/api_service.dart @@ -128,7 +128,10 @@ class ApiService { Future createGroup(String name) async { if (AppConfig.debug) { await Future.delayed(const Duration(milliseconds: 400)); - return Channel(id: 'fake_${DateTime.now().millisecondsSinceEpoch}', name: name); + return Channel( + id: 'fake_${DateTime.now().millisecondsSinceEpoch}', + name: name, + ); } try { @@ -154,9 +157,24 @@ class ApiService { if (AppConfig.debug) { await Future.delayed(const Duration(milliseconds: 400)); return [ - const GroupMember(userId: 'u1', username: 'علی', role: 'MANAGER', isOnline: true), - const GroupMember(userId: 'u2', username: 'رضا', role: 'MEMBER', isOnline: false), - const GroupMember(userId: 'u3', username: 'مریم', role: 'MEMBER', isOnline: true), + const GroupMember( + userId: 'u1', + username: 'علی', + role: 'MANAGER', + isOnline: true, + ), + const GroupMember( + userId: 'u2', + username: 'رضا', + role: 'MEMBER', + isOnline: false, + ), + const GroupMember( + userId: 'u3', + username: 'مریم', + role: 'MEMBER', + isOnline: true, + ), ]; } @@ -273,6 +291,7 @@ class ApiService { if (res.statusCode == 200) { final list = jsonDecode(res.body) as List; + print(list); return list .map((e) => AppNotification.fromJson(e as Map)) .toList(); @@ -283,7 +302,10 @@ class ApiService { } } - Future respondToNotification(String notificationId, bool isAccepted) async { + Future respondToNotification( + String notificationId, + bool isAccepted, + ) async { if (AppConfig.debug) { await Future.delayed(const Duration(milliseconds: 400)); return null; @@ -292,7 +314,9 @@ class ApiService { try { final res = await http .post( - Uri.parse('${AppConfig.baseUrl}/notifications/$notificationId/respond'), + Uri.parse( + '${AppConfig.baseUrl}/notifications/$notificationId/respond', + ), headers: await _headers(), body: jsonEncode({'is_accepted': isAccepted}), ) diff --git a/Front/lib/services/ptt_service.dart b/Front/lib/services/ptt_service.dart index 067025d..9a705a5 100644 --- a/Front/lib/services/ptt_service.dart +++ b/Front/lib/services/ptt_service.dart @@ -73,8 +73,7 @@ class PttService { _livekitUrl = livekitUrl; try { - final wsUrl = - '${AppConfig.wsBaseUrl}/ws/groups/$groupId?token=$jwtToken'; + final wsUrl = '${AppConfig.wsBaseUrl}/ws/groups/$groupId?token=$jwtToken'; _ws = await WebSocket.connect(wsUrl); _listenerTokenCompleter = Completer(); @@ -135,13 +134,15 @@ class PttService { case 'speaker_granted': // درخواست صحبت تایید شد - if (_speakGrantCompleter != null && !_speakGrantCompleter!.isCompleted) { + if (_speakGrantCompleter != null && + !_speakGrantCompleter!.isCompleted) { _speakGrantCompleter!.complete(msg['token'] as String?); } case 'speaker_busy': // خط اشغاله - if (_speakGrantCompleter != null && !_speakGrantCompleter!.isCompleted) { + if (_speakGrantCompleter != null && + !_speakGrantCompleter!.isCompleted) { _speakGrantCompleter!.complete(null); } _errorCtrl.add('خط اشغال است'); @@ -172,21 +173,23 @@ class PttService { bool setConnectedState = true, }) async { try { - await _listener?.dispose(); - await _room?.disconnect(); + try { + await _listener?.dispose(); + } catch (_) {} + try { + await _room?.disconnect().timeout( + const Duration(seconds: 2), + onTimeout: () => null, + ); + } catch (_) {} _room = Room( - roomOptions: const RoomOptions( - adaptiveStream: false, - dynacast: false, - ), + roomOptions: const RoomOptions(adaptiveStream: false, dynacast: false), ); _listener = _room!.createListener(); _listener! - ..on( - (e) => _onSpeakersChanged(e.speakers), - ) + ..on((e) => _onSpeakersChanged(e.speakers)) ..on((_) { if (_state != PttState.speaking) _setState(PttState.idle); }); @@ -301,12 +304,29 @@ class PttService { await _room?.localParticipant?.setMicrophoneEnabled(false); } catch (_) {} - await _listener?.dispose(); - await _room?.disconnect(); - _room = null; - _listener = null; + try { + await _listener?.dispose(); + } catch (_) {} - await _ws?.close(); + try { + if (_room != null) { + // LiveKit's disconnect can sometimes timeout or throw, + // we wrap it to ensure cleanup proceeds. + await _room!.disconnect().timeout( + const Duration(seconds: 3), + onTimeout: () => null, + ); + } + } catch (e) { + // Ignore disconnect errors as we are shutting down + } finally { + _room = null; + _listener = null; + } + + try { + await _ws?.close(); + } catch (_) {} _ws = null; _setState(PttState.idle); diff --git a/Front/pubspec.yaml b/Front/pubspec.yaml index 8316d56..3ff8bc1 100644 --- a/Front/pubspec.yaml +++ b/Front/pubspec.yaml @@ -24,3 +24,5 @@ dev_dependencies: flutter: uses-material-design: true + assets: + - assets/images/ diff --git a/Security_disable.txt b/Security_disable.txt new file mode 100644 index 0000000..18388bf --- /dev/null +++ b/Security_disable.txt @@ -0,0 +1,41 @@ +#غیرفعال کردن لانچر اصلی +adb shell pm disable-user com.dw.launcher + +#غیرفعال کردن ui سیستمی و توپ کویک +adb shell pm disable-user plugin.sprd.systemuidynanavigationbar +adb shell pm disable-user com.android.systemui +adb shell reboot + +# غیرفعال کردن فروشگاه‌ها و سرویس‌های گوگل (جلوگیری از دانلود برنامه ناخواسته) +adb shell pm disable-user com.android.vending +adb shell pm disable-user com.google.android.gms +adb shell pm disable-user com.google.android.gsf + +# غیرفعال کردن برنامه‌های پرخطر (مرورگر، مدیریت فایل، انتقال فایل) +adb shell pm disable-user com.android.browser +adb shell pm disable-user com.sprd.fileexplorer +adb shell pm disable-user com.lenovo.anyshare.gps + +# غیرفعال کردن برنامه‌های چندرسانه‌ای و سرگرمی +adb shell pm disable-user com.google.android.youtube +adb shell pm disable-user com.android.gallery3d +adb shell pm disable-user com.android.musicfx +adb shell pm disable-user com.dw.music +adb shell pm disable-user com.dw.calendar +adb shell pm disable-user com.dw.calculator +adb shell pm disable-user com.dw.timer +adb shell pm disable-user com.dw.stopwatch +adb shell pm disable-user com.dw.deskclock + +# غیرفعال کردن برنامه‌های بی‌سیم و بلوتوث اضافی +adb shell pm disable-user com.sprd.wirelesstools +adb shell pm disable-user com.sprd.firewall + +#قطع کامل دوربین +adb shell pm disable-user com.android.camera2 +adb shell settings put secure camera_disabled 1 + +#غیرفعال کردن gps +adb shell pm disable-user com.android.location.fused +adb shell settings put secure location_providers_allowed -gps +adb shell settings put secure location_providers_allowed -network diff --git a/admin_panel/lib/config/app_config.dart b/admin_panel/lib/config/app_config.dart index f37a877..2696ec4 100644 --- a/admin_panel/lib/config/app_config.dart +++ b/admin_panel/lib/config/app_config.dart @@ -4,10 +4,10 @@ class AppConfig { // ─── Debug Toggle ───────────────────────────────────────────────────────── /// When true, the app uses in-memory mock data (no network calls). /// When false, the app communicates with the real backend API. - static const bool debugMode = true; + static const bool debugMode = false; // ─── API Settings ───────────────────────────────────────────────────────── - static const String baseUrl = 'http://localhost:8000'; + static const String baseUrl = 'http://192.168.3.9:8000'; // ─── App Metadata ───────────────────────────────────────────────────────── static const String appName = 'NEDA Admin'; diff --git a/admin_panel/lib/main.dart b/admin_panel/lib/main.dart index aed6417..6b2fd30 100644 --- a/admin_panel/lib/main.dart +++ b/admin_panel/lib/main.dart @@ -4,6 +4,7 @@ import 'config/app_config.dart'; import 'providers/auth_provider.dart'; import 'providers/user_provider.dart'; import 'providers/group_provider.dart'; +import 'providers/notification_provider.dart'; import 'router/app_router.dart'; import 'services/service_locator.dart'; import 'theme/app_theme.dart'; @@ -23,6 +24,7 @@ class NedaAdminApp extends StatelessWidget { ChangeNotifierProvider(create: (_) => AuthProvider()), ChangeNotifierProvider(create: (_) => UserProvider()), ChangeNotifierProvider(create: (_) => GroupProvider()), + ChangeNotifierProvider(create: (_) => NotificationProvider()), ], child: MaterialApp.router( title: AppConfig.appName, diff --git a/admin_panel/lib/models/group_member_model.dart b/admin_panel/lib/models/group_member_model.dart index f7c7b04..31017ec 100644 --- a/admin_panel/lib/models/group_member_model.dart +++ b/admin_panel/lib/models/group_member_model.dart @@ -4,9 +4,9 @@ extension GroupRoleExtension on GroupRole { String get label { switch (this) { case GroupRole.manager: - return 'Manager'; + return 'مدیر'; case GroupRole.member: - return 'Member'; + return 'عضو'; } } @@ -15,56 +15,48 @@ extension GroupRoleExtension on GroupRole { class GroupMemberModel { final String userId; - final String groupId; final GroupRole role; /// Denormalized username for display — populated from local user cache final String? username; - final DateTime? joinedAt; + final bool isOnline; const GroupMemberModel({ required this.userId, - required this.groupId, required this.role, this.username, - this.joinedAt, + this.isOnline = false, }); factory GroupMemberModel.fromJson(Map json) { return GroupMemberModel( - userId: json['user_id'] as String, - groupId: json['group_id'] as String, + userId: json['user_id'].toString(), role: GroupRole.values.firstWhere( (r) => r.name == (json['role'] as String), orElse: () => GroupRole.member, ), username: json['username'] as String?, - joinedAt: json['joined_at'] != null - ? DateTime.tryParse(json['joined_at'] as String) - : null, + isOnline: (json['is_online'] as bool?) ?? false, ); } Map toJson() => { 'user_id': userId, - 'group_id': groupId, 'role': role.apiValue, if (username != null) 'username': username, - if (joinedAt != null) 'joined_at': joinedAt!.toIso8601String(), + 'is_online': isOnline, }; GroupMemberModel copyWith({ String? userId, - String? groupId, GroupRole? role, String? username, - DateTime? joinedAt, + bool? isOnline, }) { return GroupMemberModel( userId: userId ?? this.userId, - groupId: groupId ?? this.groupId, role: role ?? this.role, username: username ?? this.username, - joinedAt: joinedAt ?? this.joinedAt, + isOnline: isOnline ?? this.isOnline, ); } } diff --git a/admin_panel/lib/models/group_model.dart b/admin_panel/lib/models/group_model.dart index 6705ef1..b7b2ee0 100644 --- a/admin_panel/lib/models/group_model.dart +++ b/admin_panel/lib/models/group_model.dart @@ -1,68 +1,59 @@ -enum GroupType { group, direct } +enum GroupType { public, private } + +extension GroupTypeExtension on GroupType { + String get label { + switch (this) { + case GroupType.public: + return 'عمومی'; + case GroupType.private: + return 'خصوصی'; + } + } +} class GroupModel { final String id; final String name; - final String? description; final bool isActive; final GroupType type; - final DateTime? createdAt; - final int memberCount; const GroupModel({ required this.id, required this.name, - this.description, required this.isActive, - this.type = GroupType.group, - this.createdAt, - this.memberCount = 0, + this.type = GroupType.public, }); factory GroupModel.fromJson(Map json) { return GroupModel( - id: json['id'] as String, + id: json['id'].toString(), name: json['name'] as String, - description: json['description'] as String?, isActive: (json['is_active'] as bool?) ?? true, type: GroupType.values.firstWhere( - (t) => t.name == (json['type'] as String? ?? 'group'), - orElse: () => GroupType.group, + (t) => t.name == (json['type'] as String? ?? 'public'), + orElse: () => GroupType.public, ), - createdAt: json['created_at'] != null - ? DateTime.tryParse(json['created_at'] as String) - : null, - memberCount: (json['member_count'] as int?) ?? 0, ); } Map toJson() => { 'id': id, 'name': name, - if (description != null) 'description': description, 'is_active': isActive, 'type': type.name, - if (createdAt != null) 'created_at': createdAt!.toIso8601String(), - 'member_count': memberCount, }; GroupModel copyWith({ String? id, String? name, - String? description, bool? isActive, GroupType? type, - DateTime? createdAt, - int? memberCount, }) { return GroupModel( id: id ?? this.id, name: name ?? this.name, - description: description ?? this.description, isActive: isActive ?? this.isActive, type: type ?? this.type, - createdAt: createdAt ?? this.createdAt, - memberCount: memberCount ?? this.memberCount, ); } } diff --git a/admin_panel/lib/models/notification_model.dart b/admin_panel/lib/models/notification_model.dart new file mode 100644 index 0000000..7597b27 --- /dev/null +++ b/admin_panel/lib/models/notification_model.dart @@ -0,0 +1,78 @@ +enum NotificationType { public, joinRequest } + +extension NotificationTypeExtension on NotificationType { + String get label { + switch (this) { + case NotificationType.public: + return 'عمومی'; + case NotificationType.joinRequest: + return 'درخواست عضویت'; + } + } + + String get apiValue { + switch (this) { + case NotificationType.public: + return 'public'; + case NotificationType.joinRequest: + return 'join_request'; + } + } + + static NotificationType fromApi(String value) { + switch (value) { + case 'public': + return NotificationType.public; + case 'join_request': + return NotificationType.joinRequest; + default: + return NotificationType.public; + } + } +} + +class NotificationModel { + final String id; + final String title; + final String? description; + final NotificationType type; + final bool? isAccepted; + final String receiverId; + final String? senderId; + final String? groupId; + + const NotificationModel({ + required this.id, + required this.title, + this.description, + required this.type, + this.isAccepted, + required this.receiverId, + this.senderId, + this.groupId, + }); + + factory NotificationModel.fromJson(Map json) { + return NotificationModel( + id: json['id'].toString(), + title: json['title'] as String, + description: json['description'] as String?, + type: NotificationTypeExtension.fromApi(json['type'] as String), + isAccepted: json['is_accepted'] as bool?, + receiverId: json['receiver_id'].toString(), + senderId: json['sender_id']?.toString(), + groupId: json['group_id']?.toString(), + ); + } + + Map toJson() => { + 'id': id, + 'title': title, + 'description': description, + 'type': type.apiValue, + 'is_accepted': isAccepted, + 'receiver_id': receiverId, + 'sender_id': senderId, + 'group_id': groupId, + }; +} diff --git a/admin_panel/lib/models/user_model.dart b/admin_panel/lib/models/user_model.dart index 172516c..c0f7f0b 100644 --- a/admin_panel/lib/models/user_model.dart +++ b/admin_panel/lib/models/user_model.dart @@ -1,14 +1,12 @@ -enum UserRole { admin, group_manager, member } +enum UserRole { admin, member } extension UserRoleExtension on UserRole { String get label { switch (this) { case UserRole.admin: - return 'Admin'; - case UserRole.group_manager: - return 'Group Manager'; + return 'ادمین'; case UserRole.member: - return 'Member'; + return 'کاربر'; } } @@ -18,15 +16,18 @@ extension UserRoleExtension on UserRole { class UserModel { final String id; final String username; + final String? phoneNumber; final UserRole role; final bool isActive; final DateTime? createdAt; + /// Only available immediately after creation or secret reset final String? secret; const UserModel({ required this.id, required this.username, + this.phoneNumber, required this.role, required this.isActive, this.createdAt, @@ -34,13 +35,16 @@ class UserModel { }); factory UserModel.fromJson(Map json) { + // Backend only exposes is_admin (no role field) + UserRole mappedRole = json['is_admin'] == true + ? UserRole.admin + : UserRole.member; + return UserModel( - id: json['id'] as String, + id: json['id'].toString(), username: json['username'] as String, - role: UserRole.values.firstWhere( - (r) => r.name == (json['role'] as String), - orElse: () => UserRole.member, - ), + phoneNumber: json['phone_number'] as String?, + role: mappedRole, isActive: (json['is_active'] as bool?) ?? true, createdAt: json['created_at'] != null ? DateTime.tryParse(json['created_at'] as String) @@ -51,7 +55,8 @@ class UserModel { Map toJson() => { 'id': id, 'username': username, - 'role': role.apiValue, + 'phone_number': phoneNumber, + 'is_admin': role == UserRole.admin, 'is_active': isActive, if (createdAt != null) 'created_at': createdAt!.toIso8601String(), }; @@ -59,6 +64,7 @@ class UserModel { UserModel copyWith({ String? id, String? username, + String? phoneNumber, UserRole? role, bool? isActive, DateTime? createdAt, @@ -67,6 +73,7 @@ class UserModel { return UserModel( id: id ?? this.id, username: username ?? this.username, + phoneNumber: phoneNumber ?? this.phoneNumber, role: role ?? this.role, isActive: isActive ?? this.isActive, createdAt: createdAt ?? this.createdAt, diff --git a/admin_panel/lib/providers/group_provider.dart b/admin_panel/lib/providers/group_provider.dart index 8067757..9240a2b 100644 --- a/admin_panel/lib/providers/group_provider.dart +++ b/admin_panel/lib/providers/group_provider.dart @@ -39,10 +39,10 @@ class GroupProvider extends ChangeNotifier { notifyListeners(); } - Future createGroup(String name, String? description) async { + Future createGroup(String name) async { _error = null; try { - final group = await ServiceLocator().groups.createGroup(name, description); + final group = await ServiceLocator().groups.createGroup(name); _groups = [..._groups, group]; _membersCache[group.id] = []; notifyListeners(); @@ -58,36 +58,40 @@ class GroupProvider extends ChangeNotifier { } } - Future addMember( - String groupId, - String userId, - GroupRole role, - String? username, - ) async { + Future inviteMember(String groupId, String username) async { _error = null; try { - final member = - await ServiceLocator().groups.addMember(groupId, userId, role); - final withUsername = member.copyWith(username: username); - _membersCache.putIfAbsent(groupId, () => []).add(withUsername); - - // Refresh member count on cached group - final idx = _groups.indexWhere((g) => g.id == groupId); - if (idx != -1) { - _groups[idx] = _groups[idx].copyWith( - memberCount: _membersCache[groupId]!.length, - ); - } - notifyListeners(); - return withUsername; + await ServiceLocator().groups.inviteMember(groupId, username); + // We don't necessarily add to cache here because it's an invitation. + // But we can reload members to be sure. + await loadGroupMembers(groupId); + return true; } on ApiException catch (e) { _error = e.message; notifyListeners(); - return null; + return false; } catch (e) { - _error = 'خطا در افزودن عضو'; + _error = 'خطا در دعوت عضو'; notifyListeners(); - return null; + return false; + } + } + + Future removeMember(String groupId, String userId) async { + _error = null; + try { + await ServiceLocator().groups.removeMember(groupId, userId); + _membersCache[groupId]?.removeWhere((m) => m.userId == userId); + notifyListeners(); + return true; + } on ApiException catch (e) { + _error = e.message; + notifyListeners(); + return false; + } catch (e) { + _error = 'خطا در حذف عضو'; + notifyListeners(); + return false; } } diff --git a/admin_panel/lib/providers/notification_provider.dart b/admin_panel/lib/providers/notification_provider.dart new file mode 100644 index 0000000..dbdfcb0 --- /dev/null +++ b/admin_panel/lib/providers/notification_provider.dart @@ -0,0 +1,55 @@ +import 'package:flutter/material.dart'; +import '../models/notification_model.dart'; +import '../services/service_locator.dart'; +import '../services/api/api_client.dart'; + +enum NotificationLoadStatus { idle, loading, success, error } + +class NotificationProvider extends ChangeNotifier { + List _items = []; + NotificationLoadStatus _status = NotificationLoadStatus.idle; + String? _error; + + List get items => List.unmodifiable(_items); + NotificationLoadStatus get status => _status; + String? get error => _error; + bool get isLoading => _status == NotificationLoadStatus.loading; + + Future loadNotifications() async { + _status = NotificationLoadStatus.loading; + _error = null; + notifyListeners(); + + try { + _items = await ServiceLocator().notifications.getNotifications(); + _status = NotificationLoadStatus.success; + } on ApiException catch (e) { + _error = e.message; + _status = NotificationLoadStatus.error; + } catch (e) { + _error = 'خطا در دریافت اعلان‌ها'; + _status = NotificationLoadStatus.error; + } + notifyListeners(); + } + + Future sendPublic(String title, String description) async { + _error = null; + try { + await ServiceLocator().notifications.sendPublicNotification( + title, + description, + ); + await loadNotifications(); + return true; + } on ApiException catch (e) { + _error = e.message; + notifyListeners(); + return false; + } catch (_) { + _error = 'خطا در ارسال اعلان'; + notifyListeners(); + return false; + } + } +} diff --git a/admin_panel/lib/providers/user_provider.dart b/admin_panel/lib/providers/user_provider.dart index a54b269..8a1ea82 100644 --- a/admin_panel/lib/providers/user_provider.dart +++ b/admin_panel/lib/providers/user_provider.dart @@ -38,12 +38,15 @@ class UserProvider extends ChangeNotifier { /// Returns the new user and its generated secret. Future<({UserModel user, String secret})?> createUser( - String username, - UserRole role, - ) async { + String username, { + String? phoneNumber, + }) async { _error = null; try { - final result = await ServiceLocator().users.createUser(username, role); + final result = await ServiceLocator().users.createUser( + username, + phoneNumber: phoneNumber, + ); _users = [..._users, result.user]; notifyListeners(); return result; @@ -75,6 +78,22 @@ class UserProvider extends ChangeNotifier { } } + Future logoutUser(String userId) async { + _error = null; + try { + await ServiceLocator().users.logoutUser(userId); + return true; + } on ApiException catch (e) { + _error = e.message; + notifyListeners(); + return false; + } catch (e) { + _error = 'خطا در خروج کاربر'; + notifyListeners(); + return false; + } + } + void clearError() { _error = null; notifyListeners(); diff --git a/admin_panel/lib/router/app_router.dart b/admin_panel/lib/router/app_router.dart index ea0b22c..f9583ab 100644 --- a/admin_panel/lib/router/app_router.dart +++ b/admin_panel/lib/router/app_router.dart @@ -7,6 +7,7 @@ import '../screens/dashboard_screen.dart'; import '../screens/users_screen.dart'; import '../screens/groups_screen.dart'; import '../screens/group_detail_screen.dart'; +import '../screens/notifications_screen.dart'; final appRouter = GoRouter( initialLocation: '/login', @@ -34,6 +35,10 @@ final appRouter = GoRouter( groupId: state.pathParameters['id']!, ), ), + GoRoute( + path: '/notifications', + builder: (_, __) => const NotificationsScreen(), + ), ], ); diff --git a/admin_panel/lib/screens/dashboard_screen.dart b/admin_panel/lib/screens/dashboard_screen.dart index f4f0e20..853ebc4 100644 --- a/admin_panel/lib/screens/dashboard_screen.dart +++ b/admin_panel/lib/screens/dashboard_screen.dart @@ -72,8 +72,8 @@ class _DashboardBody extends StatelessWidget { ), if (AppConfig.debugMode) Container( - padding: const EdgeInsets.symmetric( - horizontal: 12, vertical: 6), + padding: + const EdgeInsets.symmetric(horizontal: 12, vertical: 6), decoration: BoxDecoration( color: AppTheme.warning.withValues(alpha: 0.1), borderRadius: BorderRadius.circular(20), @@ -116,35 +116,6 @@ class _DashboardBody extends StatelessWidget { ), const SizedBox(height: 16), _QuickActions(), - const SizedBox(height: 28), - - // ── Info banner (real API mode) ─────────────────────────── - if (!AppConfig.debugMode) - Container( - padding: const EdgeInsets.all(16), - decoration: BoxDecoration( - color: AppTheme.primary.withValues(alpha: 0.06), - borderRadius: BorderRadius.circular(12), - border: Border.all( - color: AppTheme.primary.withValues(alpha: 0.2)), - ), - child: Row( - children: [ - const Icon(Icons.info_outline_rounded, - color: AppTheme.primary, size: 20), - const SizedBox(width: 12), - const Expanded( - child: Text( - 'در حالت واقعی، لیست کاربران و گروه‌ها فقط شامل آیتم‌های ایجادشده در همین نشست می‌باشد. بک‌اند فاقد endpoint لیست است.', - style: TextStyle( - fontSize: 13, - color: AppTheme.primary, - ), - ), - ), - ], - ), - ), ], ), ); @@ -239,12 +210,20 @@ class _QuickActions extends StatelessWidget { color: AppTheme.success, onTap: () => context.go('/groups'), ), - ].map((w) => SizedBox( - width: isWide - ? (constraints.maxWidth - 36) / 4 - : (constraints.maxWidth - 12) / 2, - child: w, - )).toList(), + _ActionCard( + label: 'ارسال اعلان عمومی', + icon: Icons.campaign_rounded, + color: const Color(0xFFEA580C), + onTap: () => context.go('/notifications'), + ), + ] + .map((w) => SizedBox( + width: isWide + ? (constraints.maxWidth - 48) / 5 + : (constraints.maxWidth - 12) / 2, + child: w, + )) + .toList(), ); }); } diff --git a/admin_panel/lib/screens/group_detail_screen.dart b/admin_panel/lib/screens/group_detail_screen.dart index a2df3c6..9d50bfe 100644 --- a/admin_panel/lib/screens/group_detail_screen.dart +++ b/admin_panel/lib/screens/group_detail_screen.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; -import 'package:intl/intl.dart' hide TextDirection; import 'package:provider/provider.dart'; import '../models/group_member_model.dart'; import '../models/user_model.dart'; @@ -34,9 +33,8 @@ class _GroupDetailScreenState extends State { @override Widget build(BuildContext context) { return Consumer(builder: (_, groupProvider, __) { - final group = groupProvider.groups - .where((g) => g.id == widget.groupId) - .firstOrNull; + final group = + groupProvider.groups.where((g) => g.id == widget.groupId).firstOrNull; return ResponsiveLayout( title: group?.name ?? 'جزئیات گروه', @@ -44,9 +42,7 @@ class _GroupDetailScreenState extends State { body: _GroupDetailBody( groupId: widget.groupId, groupName: group?.name ?? '...', - groupDescription: group?.description, isActive: group?.isActive ?? true, - createdAt: group?.createdAt, ), ); }); @@ -56,16 +52,12 @@ class _GroupDetailScreenState extends State { class _GroupDetailBody extends StatelessWidget { final String groupId; final String groupName; - final String? groupDescription; final bool isActive; - final DateTime? createdAt; const _GroupDetailBody({ required this.groupId, required this.groupName, - required this.groupDescription, required this.isActive, - required this.createdAt, }); @override @@ -141,26 +133,6 @@ class _GroupDetailBody extends StatelessWidget { _StatusBadge(isActive: isActive), ], ), - if (groupDescription != null) ...[ - const SizedBox(height: 4), - Text( - groupDescription!, - style: const TextStyle( - color: AppTheme.textSecondary, - fontSize: 14, - ), - ), - ], - const SizedBox(height: 4), - Text( - createdAt != null - ? 'ایجاد شده در ${DateFormat('yyyy/MM/dd').format(createdAt!)}' - : '', - style: const TextStyle( - color: AppTheme.textSecondary, - fontSize: 12, - ), - ), ], ), ), @@ -206,7 +178,6 @@ class _AddMemberDialog extends StatefulWidget { class _AddMemberDialogState extends State<_AddMemberDialog> { UserModel? _selectedUser; - GroupRole _role = GroupRole.member; bool _loading = false; String? _error; @@ -222,7 +193,7 @@ class _AddMemberDialogState extends State<_AddMemberDialog> { final provider = context.read(); final currentMembers = provider.membersOf(widget.groupId); - if (currentMembers.any((m) => m.userId == _selectedUser!.id)) { + if (currentMembers.any((m) => m.username == _selectedUser!.username)) { setState(() { _loading = false; _error = 'این کاربر قبلاً عضو این گروه است'; @@ -230,22 +201,19 @@ class _AddMemberDialogState extends State<_AddMemberDialog> { return; } - final result = await provider.addMember( + final success = await provider.inviteMember( widget.groupId, - _selectedUser!.id, - _role, _selectedUser!.username, ); if (!mounted) return; setState(() => _loading = false); - if (result != null) { + if (success) { Navigator.of(context).pop(); ScaffoldMessenger.of(context).showSnackBar( SnackBar( - content: - Text('«${_selectedUser!.username}» به گروه اضافه شد'), + content: Text('«${_selectedUser!.username}» به گروه اضافه شد'), backgroundColor: AppTheme.success, ), ); @@ -291,23 +259,6 @@ class _AddMemberDialogState extends State<_AddMemberDialog> { .toList(), onChanged: (v) => setState(() => _selectedUser = v), ), - const SizedBox(height: 16), - - // Role selector - DropdownButtonFormField( - initialValue: _role, - decoration: const InputDecoration( - labelText: 'نقش در گروه', - prefixIcon: Icon(Icons.badge_outlined), - ), - items: GroupRole.values - .map((r) => DropdownMenuItem( - value: r, - child: Text(r.label), - )) - .toList(), - onChanged: (v) => setState(() => _role = v!), - ), if (_error != null) ...[ const SizedBox(height: 12), @@ -321,8 +272,8 @@ class _AddMemberDialogState extends State<_AddMemberDialog> { ), child: Text( _error!, - style: const TextStyle( - color: AppTheme.danger, fontSize: 13), + style: + const TextStyle(color: AppTheme.danger, fontSize: 13), ), ), ], @@ -401,9 +352,10 @@ class _MembersTable extends StatelessWidget { columns: const [ DataColumn(label: Text('کاربر')), DataColumn(label: Text('نقش در گروه')), - DataColumn(label: Text('تاریخ عضویت')), + DataColumn(label: Text('وضعیت آنلاین')), + DataColumn(label: Text('عملیات')), ], - rows: members.map((m) => _buildRow(m)).toList(), + rows: members.map((m) => _buildRow(context, m)).toList(), ), ), ), @@ -412,7 +364,7 @@ class _MembersTable extends StatelessWidget { }); } - DataRow _buildRow(GroupMemberModel member) { + DataRow _buildRow(BuildContext context, GroupMemberModel member) { final color = member.role == GroupRole.manager ? const Color(0xFF0891B2) : AppTheme.textSecondary; @@ -461,18 +413,92 @@ class _MembersTable extends StatelessWidget { ), ), DataCell( - Text( - member.joinedAt != null - ? DateFormat('yyyy/MM/dd').format(member.joinedAt!) - : '—', - style: const TextStyle(color: AppTheme.textSecondary), - ), + _OnlineBadge(isOnline: member.isOnline), + ), + DataCell( + _RemoveMemberButton(groupId: groupId, member: member), ), ], ); } } +class _RemoveMemberButton extends StatefulWidget { + final String groupId; + final GroupMemberModel member; + const _RemoveMemberButton({required this.groupId, required this.member}); + + @override + State<_RemoveMemberButton> createState() => _RemoveMemberButtonState(); +} + +class _RemoveMemberButtonState extends State<_RemoveMemberButton> { + bool _loading = false; + + Future _remove() async { + final confirmed = await showDialog( + context: context, + builder: (_) => AlertDialog( + title: const Text('تأیید حذف عضو'), + content: Text( + 'آیا مطمئن هستید که می‌خواهید «${widget.member.username ?? widget.member.userId}» را از این گروه حذف کنید؟'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text('انصراف'), + ), + ElevatedButton( + onPressed: () => Navigator.pop(context, true), + style: ElevatedButton.styleFrom(backgroundColor: AppTheme.danger), + child: const Text('حذف'), + ), + ], + ), + ); + + if (confirmed != true || !mounted) return; + setState(() => _loading = true); + + final provider = context.read(); + final success = + await provider.removeMember(widget.groupId, widget.member.userId); + if (!mounted) return; + setState(() => _loading = false); + + if (success) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('عضو از گروه حذف شد'), + backgroundColor: AppTheme.success, + ), + ); + } else if (provider.error != null) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(provider.error!), + backgroundColor: AppTheme.danger, + ), + ); + } + } + + @override + Widget build(BuildContext context) { + if (_loading) { + return const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2)); + } + return IconButton( + onPressed: _remove, + icon: const Icon(Icons.person_remove_rounded, size: 18), + color: AppTheme.danger, + tooltip: 'حذف از گروه', + ); + } +} + // ── Status Badge ───────────────────────────────────────────────────────────── class _StatusBadge extends StatelessWidget { @@ -499,3 +525,39 @@ class _StatusBadge extends StatelessWidget { ); } } + +class _OnlineBadge extends StatelessWidget { + final bool isOnline; + const _OnlineBadge({required this.isOnline}); + + @override + Widget build(BuildContext context) { + final color = isOnline ? AppTheme.success : AppTheme.textSecondary; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: color.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(20), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + width: 6, + height: 6, + decoration: BoxDecoration(color: color, shape: BoxShape.circle), + ), + const SizedBox(width: 5), + Text( + isOnline ? 'آنلاین' : 'آفلاین', + style: TextStyle( + color: color, + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ), + ], + ), + ); + } +} diff --git a/admin_panel/lib/screens/groups_screen.dart b/admin_panel/lib/screens/groups_screen.dart index 3d97c2b..c99aba6 100644 --- a/admin_panel/lib/screens/groups_screen.dart +++ b/admin_panel/lib/screens/groups_screen.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; -import 'package:intl/intl.dart' hide TextDirection; import 'package:provider/provider.dart'; import '../models/group_model.dart'; import '../providers/group_provider.dart'; @@ -125,10 +124,7 @@ class _GroupsBody extends StatelessWidget { final filtered = provider.groups .where((g) => - search.isEmpty || - g.name.toLowerCase().contains(search) || - (g.description?.toLowerCase().contains(search) ?? - false)) + search.isEmpty || g.name.toLowerCase().contains(search)) .toList(); if (filtered.isEmpty) { @@ -167,14 +163,12 @@ class _CreateGroupDialog extends StatefulWidget { class _CreateGroupDialogState extends State<_CreateGroupDialog> { final _formKey = GlobalKey(); final _nameCtrl = TextEditingController(); - final _descCtrl = TextEditingController(); bool _loading = false; String? _error; @override void dispose() { _nameCtrl.dispose(); - _descCtrl.dispose(); super.dispose(); } @@ -188,7 +182,6 @@ class _CreateGroupDialogState extends State<_CreateGroupDialog> { final provider = context.read(); final group = await provider.createGroup( _nameCtrl.text.trim(), - _descCtrl.text.trim().isEmpty ? null : _descCtrl.text.trim(), ); if (!mounted) return; @@ -231,18 +224,9 @@ class _CreateGroupDialogState extends State<_CreateGroupDialog> { labelText: 'نام گروه', prefixIcon: Icon(Icons.groups_rounded), ), - validator: (v) => - (v == null || v.trim().isEmpty) ? 'نام گروه الزامی است' : null, - ), - const SizedBox(height: 16), - TextFormField( - controller: _descCtrl, - maxLines: 3, - decoration: const InputDecoration( - labelText: 'توضیحات (اختیاری)', - prefixIcon: Icon(Icons.description_outlined), - alignLabelWithHint: true, - ), + validator: (v) => (v == null || v.trim().isEmpty) + ? 'نام گروه الزامی است' + : null, ), if (_error != null) ...[ const SizedBox(height: 12), @@ -256,8 +240,8 @@ class _CreateGroupDialogState extends State<_CreateGroupDialog> { ), child: Text( _error!, - style: const TextStyle( - color: AppTheme.danger, fontSize: 13), + style: + const TextStyle(color: AppTheme.danger, fontSize: 13), ), ), ], @@ -303,15 +287,11 @@ class _GroupsTable extends StatelessWidget { child: DataTable( columns: const [ DataColumn(label: Text('نام گروه')), - DataColumn(label: Text('توضیحات')), - DataColumn(label: Text('اعضا')), + DataColumn(label: Text('نوع')), DataColumn(label: Text('وضعیت')), - DataColumn(label: Text('تاریخ ایجاد')), DataColumn(label: Text('عملیات')), ], - rows: groups - .map((g) => _buildRow(context, g)) - .toList(), + rows: groups.map((g) => _buildRow(context, g)).toList(), ), ), ), @@ -347,36 +327,13 @@ class _GroupsTable extends StatelessWidget { ], ), ), - DataCell( - SizedBox( - width: 180, - child: Text( - group.description ?? '—', - style: const TextStyle(color: AppTheme.textSecondary), - overflow: TextOverflow.ellipsis, - ), - ), - ), - DataCell( - Row( - mainAxisSize: MainAxisSize.min, - children: [ - const Icon(Icons.people_rounded, - size: 14, color: AppTheme.textSecondary), - const SizedBox(width: 4), - Text('${group.memberCount}'), - ], - ), - ), - DataCell(_StatusBadge(isActive: group.isActive)), DataCell( Text( - group.createdAt != null - ? DateFormat('yyyy/MM/dd').format(group.createdAt!) - : '—', + group.type.label, style: const TextStyle(color: AppTheme.textSecondary), ), ), + DataCell(_StatusBadge(isActive: group.isActive)), DataCell( TextButton.icon( onPressed: () => context.go('/groups/${group.id}'), @@ -442,8 +399,7 @@ class _EmptyView extends StatelessWidget { const SizedBox(height: 16), Text( message, - style: const TextStyle( - color: AppTheme.textSecondary, fontSize: 16), + style: const TextStyle(color: AppTheme.textSecondary, fontSize: 16), ), ], ), @@ -465,8 +421,7 @@ class _ErrorView extends StatelessWidget { const Icon(Icons.error_outline_rounded, size: 64, color: AppTheme.danger), const SizedBox(height: 16), - Text(message, - style: const TextStyle(color: AppTheme.textSecondary)), + Text(message, style: const TextStyle(color: AppTheme.textSecondary)), const SizedBox(height: 16), ElevatedButton.icon( onPressed: onRetry, diff --git a/admin_panel/lib/screens/notifications_screen.dart b/admin_panel/lib/screens/notifications_screen.dart new file mode 100644 index 0000000..e983b5a --- /dev/null +++ b/admin_panel/lib/screens/notifications_screen.dart @@ -0,0 +1,492 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import '../models/notification_model.dart'; +import '../providers/notification_provider.dart'; +import '../theme/app_theme.dart'; +import '../widgets/app_sidebar.dart'; +import '../widgets/responsive_layout.dart'; + +class NotificationsScreen extends StatelessWidget { + const NotificationsScreen({super.key}); + + @override + Widget build(BuildContext context) { + return const ResponsiveLayout( + title: 'اعلان‌ها', + sidebar: AppSidebar(), + body: _NotificationsBody(), + ); + } +} + +class _NotificationsBody extends StatefulWidget { + const _NotificationsBody(); + + @override + State<_NotificationsBody> createState() => _NotificationsBodyState(); +} + +class _NotificationsBodyState extends State<_NotificationsBody> { + final _searchCtrl = TextEditingController(); + String _search = ''; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + context.read().loadNotifications(); + }); + } + + @override + void dispose() { + _searchCtrl.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.all(24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // ── Header ──────────────────────────────────────────────── + Row( + children: [ + const Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'اعلان‌های سیستم', + style: TextStyle( + fontSize: 24, + fontWeight: FontWeight.w800, + color: AppTheme.textPrimary, + ), + ), + SizedBox(height: 4), + Text( + 'مشاهده اعلان‌ها و ارسال اعلان عمومی', + style: TextStyle( + fontSize: 14, color: AppTheme.textSecondary), + ), + ], + ), + ), + ElevatedButton.icon( + onPressed: () => _showBroadcastDialog(context), + icon: const Icon(Icons.campaign_rounded, size: 18), + label: const Text('ارسال اعلان عمومی'), + ), + ], + ), + const SizedBox(height: 20), + + // ── Search ─────────────────────────────────────────────── + TextField( + controller: _searchCtrl, + onChanged: (v) => setState(() => _search = v.toLowerCase()), + decoration: const InputDecoration( + hintText: 'جستجوی اعلان...', + prefixIcon: Icon(Icons.search_rounded), + ), + ), + const SizedBox(height: 16), + + // ── Table ──────────────────────────────────────────────── + Expanded( + child: Consumer( + builder: (_, provider, __) { + if (provider.isLoading) { + return const Center(child: CircularProgressIndicator()); + } + if (provider.status == NotificationLoadStatus.error) { + return _ErrorView( + message: provider.error ?? 'خطا', + onRetry: () => provider.loadNotifications(), + ); + } + + final filtered = provider.items.where((n) { + if (_search.isEmpty) return true; + final text = [ + n.title, + n.description ?? '', + n.receiverId, + n.senderId ?? '', + ].join(' ').toLowerCase(); + return text.contains(_search); + }).toList(); + + if (filtered.isEmpty) { + return const _EmptyView( + icon: Icons.notifications_none_rounded, + message: 'اعلانی یافت نشد', + ); + } + + return _NotificationsTable(items: filtered); + }, + ), + ), + ], + ), + ); + } + + void _showBroadcastDialog(BuildContext context) { + showDialog( + context: context, + builder: (_) => const _BroadcastDialog(), + ); + } +} + +// ── Broadcast Dialog ───────────────────────────────────────────────────────── + +class _BroadcastDialog extends StatefulWidget { + const _BroadcastDialog(); + + @override + State<_BroadcastDialog> createState() => _BroadcastDialogState(); +} + +class _BroadcastDialogState extends State<_BroadcastDialog> { + final _formKey = GlobalKey(); + final _titleCtrl = TextEditingController(); + final _descCtrl = TextEditingController(); + bool _loading = false; + String? _error; + bool _sent = false; + + @override + void dispose() { + _titleCtrl.dispose(); + _descCtrl.dispose(); + super.dispose(); + } + + Future _submit() async { + if (!_formKey.currentState!.validate()) return; + setState(() { + _loading = true; + _error = null; + }); + + final title = _titleCtrl.text.trim(); + final desc = _descCtrl.text.trim(); + final provider = context.read(); + + final success = await provider.sendPublic(title, desc); + + if (!mounted) return; + setState(() => _loading = false); + + if (success) { + setState(() => _sent = true); + } else { + setState(() => _error = provider.error ?? 'خطا در ارسال اعلان'); + } + } + + @override + Widget build(BuildContext context) { + if (_sent) { + return AlertDialog( + title: const Row( + children: [ + Icon(Icons.check_circle_rounded, color: AppTheme.success), + SizedBox(width: 10), + Text('اعلان ارسال شد'), + ], + ), + content: const Text('اعلان عمومی با موفقیت به همه کاربران ارسال شد.'), + actions: [ + ElevatedButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('بستن'), + ), + ], + ); + } + + return AlertDialog( + title: const Row( + children: [ + Icon(Icons.campaign_rounded, color: AppTheme.primary), + SizedBox(width: 10), + Text('ارسال اعلان عمومی'), + ], + ), + content: SizedBox( + width: 440, + child: Form( + key: _formKey, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + TextFormField( + controller: _titleCtrl, + decoration: const InputDecoration( + labelText: 'عنوان اعلان', + prefixIcon: Icon(Icons.title_rounded), + ), + validator: (v) => + (v == null || v.trim().isEmpty) ? 'عنوان الزامی است' : null, + ), + const SizedBox(height: 16), + TextFormField( + controller: _descCtrl, + maxLines: 4, + decoration: const InputDecoration( + labelText: 'متن اعلان (اختیاری)', + prefixIcon: Icon(Icons.description_outlined), + alignLabelWithHint: true, + ), + ), + if (_error != null) ...[ + const SizedBox(height: 12), + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: AppTheme.danger.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: AppTheme.danger.withValues(alpha: 0.3)), + ), + child: Text( + _error!, + style: const TextStyle( + color: AppTheme.danger, fontSize: 13), + ), + ), + ], + ], + ), + ), + ), + actions: [ + TextButton( + onPressed: _loading ? null : () => Navigator.of(context).pop(), + child: const Text('انصراف'), + ), + ElevatedButton.icon( + onPressed: _loading ? null : _submit, + icon: _loading + ? const SizedBox( + width: 14, + height: 14, + child: CircularProgressIndicator( + color: Colors.white, strokeWidth: 2)) + : const Icon(Icons.send_rounded, size: 16), + label: const Text('ارسال به همه'), + ), + ], + ); + } +} + +// ── Notifications Table ───────────────────────────────────────────────────── + +class _NotificationsTable extends StatelessWidget { + final List items; + + const _NotificationsTable({required this.items}); + + @override + Widget build(BuildContext context) { + return Card( + child: ClipRRect( + borderRadius: BorderRadius.circular(12), + child: SingleChildScrollView( + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: DataTable( + columns: const [ + DataColumn(label: Text('عنوان')), + DataColumn(label: Text('نوع')), + DataColumn(label: Text('گیرنده')), + DataColumn(label: Text('وضعیت')), + ], + rows: items.map((n) => _buildRow(n)).toList(), + ), + ), + ), + ), + ); + } + + DataRow _buildRow(NotificationModel n) { + return DataRow( + cells: [ + DataCell( + SizedBox( + width: 280, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + n.title, + style: const TextStyle(fontWeight: FontWeight.w600), + ), + if ((n.description ?? '').isNotEmpty) ...[ + const SizedBox(height: 4), + Text( + n.description!, + style: const TextStyle( + color: AppTheme.textSecondary, + fontSize: 12, + ), + ), + ], + if (n.groupId != null) ...[ + const SizedBox(height: 4), + Text( + 'گروه: ${n.groupId}', + style: const TextStyle( + color: AppTheme.textSecondary, + fontSize: 11, + ), + ), + ], + ], + ), + ), + ), + DataCell(_TypeBadge(type: n.type)), + DataCell( + Text( + n.receiverId, + style: const TextStyle(color: AppTheme.textSecondary), + ), + ), + DataCell(_StatusBadge(type: n.type, isAccepted: n.isAccepted)), + ], + ); + } +} + +class _TypeBadge extends StatelessWidget { + final NotificationType type; + const _TypeBadge({required this.type}); + + @override + Widget build(BuildContext context) { + final color = type == NotificationType.public + ? AppTheme.primary + : const Color(0xFF0891B2); + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: color.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(20), + ), + child: Text( + type.label, + style: TextStyle( + color: color, + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ), + ); + } +} + +class _StatusBadge extends StatelessWidget { + final NotificationType type; + final bool? isAccepted; + const _StatusBadge({required this.type, required this.isAccepted}); + + @override + Widget build(BuildContext context) { + String label; + Color color; + + if (type == NotificationType.public) { + label = 'ارسال شد'; + color = AppTheme.success; + } else { + if (isAccepted == true) { + label = 'تأیید شد'; + color = AppTheme.success; + } else if (isAccepted == false) { + label = 'رد شد'; + color = AppTheme.danger; + } else { + label = 'در انتظار'; + color = AppTheme.warning; + } + } + + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: color.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(20), + ), + child: Text( + label, + style: TextStyle( + color: color, + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ), + ); + } +} + +class _EmptyView extends StatelessWidget { + final IconData icon; + final String message; + const _EmptyView({required this.icon, required this.message}); + + @override + Widget build(BuildContext context) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(icon, size: 64, color: AppTheme.border), + const SizedBox(height: 16), + Text( + message, + style: const TextStyle(color: AppTheme.textSecondary, fontSize: 16), + ), + ], + ), + ); + } +} + +class _ErrorView extends StatelessWidget { + final String message; + final VoidCallback onRetry; + const _ErrorView({required this.message, required this.onRetry}); + + @override + Widget build(BuildContext context) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.error_outline_rounded, + size: 64, color: AppTheme.danger), + const SizedBox(height: 16), + Text(message, style: const TextStyle(color: AppTheme.textSecondary)), + const SizedBox(height: 16), + ElevatedButton.icon( + onPressed: onRetry, + icon: const Icon(Icons.refresh_rounded), + label: const Text('تلاش مجدد'), + ), + ], + ), + ); + } +} diff --git a/admin_panel/lib/screens/users_screen.dart b/admin_panel/lib/screens/users_screen.dart index 51a835f..15d2e65 100644 --- a/admin_panel/lib/screens/users_screen.dart +++ b/admin_panel/lib/screens/users_screen.dart @@ -125,8 +125,7 @@ class _UsersBody extends StatelessWidget { final filtered = provider.users .where((u) => search.isEmpty || - u.username.toLowerCase().contains(search) || - u.role.label.toLowerCase().contains(search)) + u.username.toLowerCase().contains(search)) .toList(); if (filtered.isEmpty) { @@ -165,13 +164,14 @@ class _CreateUserDialog extends StatefulWidget { class _CreateUserDialogState extends State<_CreateUserDialog> { final _formKey = GlobalKey(); final _usernameCtrl = TextEditingController(); - UserRole _role = UserRole.member; + final _phoneCtrl = TextEditingController(); bool _loading = false; String? _error; @override void dispose() { _usernameCtrl.dispose(); + _phoneCtrl.dispose(); super.dispose(); } @@ -185,7 +185,8 @@ class _CreateUserDialogState extends State<_CreateUserDialog> { final provider = context.read(); final result = await provider.createUser( _usernameCtrl.text.trim(), - _role, + phoneNumber: + _phoneCtrl.text.trim().isEmpty ? null : _phoneCtrl.text.trim(), ); if (!mounted) return; @@ -228,23 +229,27 @@ class _CreateUserDialogState extends State<_CreateUserDialog> { labelText: 'نام کاربری', prefixIcon: Icon(Icons.person_outline_rounded), ), - validator: (v) => - (v == null || v.trim().isEmpty) ? 'نام کاربری الزامی است' : null, + validator: (v) => (v == null || v.trim().isEmpty) + ? 'نام کاربری الزامی است' + : null, ), const SizedBox(height: 16), - DropdownButtonFormField( - initialValue: _role, + TextFormField( + controller: _phoneCtrl, + textDirection: TextDirection.ltr, decoration: const InputDecoration( - labelText: 'نقش', - prefixIcon: Icon(Icons.badge_outlined), + labelText: 'شماره همراه (اختیاری)', + prefixIcon: Icon(Icons.phone_android_rounded), ), - items: UserRole.values - .map((r) => DropdownMenuItem( - value: r, - child: Text(r.label), - )) - .toList(), - onChanged: (v) => setState(() => _role = v!), + validator: (v) { + if (v != null && v.trim().isNotEmpty) { + if (v.trim().length != 11 || + !RegExp(r'^\d+$').hasMatch(v.trim())) { + return 'شماره همراه معتبر نیست (۱۱ رقم)'; + } + } + return null; + }, ), if (_error != null) ...[ const SizedBox(height: 12), @@ -253,11 +258,13 @@ class _CreateUserDialogState extends State<_CreateUserDialog> { decoration: BoxDecoration( color: AppTheme.danger.withValues(alpha: 0.08), borderRadius: BorderRadius.circular(8), - border: Border.all(color: AppTheme.danger.withValues(alpha: 0.3)), + border: Border.all( + color: AppTheme.danger.withValues(alpha: 0.3)), ), child: Text( _error!, - style: const TextStyle(color: AppTheme.danger, fontSize: 13), + style: + const TextStyle(color: AppTheme.danger, fontSize: 13), ), ), ], @@ -303,6 +310,7 @@ class _UsersTable extends StatelessWidget { child: DataTable( columns: const [ DataColumn(label: Text('نام کاربری')), + DataColumn(label: Text('شماره همراه')), DataColumn(label: Text('نقش')), DataColumn(label: Text('وضعیت')), DataColumn(label: Text('تاریخ ایجاد')), @@ -343,6 +351,12 @@ class _UsersTable extends StatelessWidget { ], ), ), + DataCell( + Text( + user.phoneNumber ?? '—', + style: const TextStyle(color: AppTheme.textSecondary), + ), + ), DataCell(_RoleBadge(role: user.role)), DataCell(_StatusBadge(isActive: user.isActive)), DataCell( @@ -354,7 +368,14 @@ class _UsersTable extends StatelessWidget { ), ), DataCell( - _ResetSecretButton(user: user), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + _ResetSecretButton(user: user), + const SizedBox(width: 8), + _LogoutUserButton(user: user), + ], + ), ), ], ); @@ -513,8 +534,7 @@ class _EmptyView extends StatelessWidget { const SizedBox(height: 16), Text( message, - style: const TextStyle( - color: AppTheme.textSecondary, fontSize: 16), + style: const TextStyle(color: AppTheme.textSecondary, fontSize: 16), ), ], ), @@ -536,8 +556,7 @@ class _ErrorView extends StatelessWidget { const Icon(Icons.error_outline_rounded, size: 64, color: AppTheme.danger), const SizedBox(height: 16), - Text(message, - style: const TextStyle(color: AppTheme.textSecondary)), + Text(message, style: const TextStyle(color: AppTheme.textSecondary)), const SizedBox(height: 16), ElevatedButton.icon( onPressed: onRetry, @@ -549,3 +568,77 @@ class _ErrorView extends StatelessWidget { ); } } + +class _LogoutUserButton extends StatefulWidget { + final UserModel user; + const _LogoutUserButton({required this.user}); + + @override + State<_LogoutUserButton> createState() => _LogoutUserButtonState(); +} + +class _LogoutUserButtonState extends State<_LogoutUserButton> { + bool _loading = false; + + Future _logout() async { + final confirmed = await showDialog( + context: context, + builder: (_) => AlertDialog( + title: const Text('تأیید خروج اجباری'), + content: Text( + 'آیا مطمئن هستید که می‌خواهید «${widget.user.username}» را از تمام دستگاه‌ها خارج کنید؟'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: const Text('انصراف'), + ), + ElevatedButton( + onPressed: () => Navigator.pop(context, true), + style: ElevatedButton.styleFrom(backgroundColor: AppTheme.danger), + child: const Text('خروج اجباری'), + ), + ], + ), + ); + + if (confirmed != true || !mounted) return; + setState(() => _loading = true); + + final provider = context.read(); + final success = await provider.logoutUser(widget.user.id); + if (!mounted) return; + setState(() => _loading = false); + + if (success) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('کاربر با موفقیت خارج شد'), + backgroundColor: AppTheme.success, + ), + ); + } else if (provider.error != null) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(provider.error!), + backgroundColor: AppTheme.danger, + ), + ); + } + } + + @override + Widget build(BuildContext context) { + if (_loading) { + return const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2)); + } + return TextButton.icon( + onPressed: _logout, + icon: const Icon(Icons.logout_rounded, size: 16), + label: const Text('خروج'), + style: TextButton.styleFrom(foregroundColor: AppTheme.danger), + ); + } +} diff --git a/admin_panel/lib/services/api/api_client.dart b/admin_panel/lib/services/api/api_client.dart index e3c2a64..476c592 100644 --- a/admin_panel/lib/services/api/api_client.dart +++ b/admin_panel/lib/services/api/api_client.dart @@ -42,13 +42,23 @@ class ApiClient { return _handleResponse(response); } + Future delete(String path) async { + final response = await http.delete( + Uri.parse('$baseUrl$path'), + headers: _headers, + ); + return _handleResponse(response); + } + dynamic _handleResponse(http.Response response) { if (response.body.isEmpty) return null; final data = jsonDecode(response.body); if (response.statusCode >= 200 && response.statusCode < 300) { return data; } - final detail = data is Map ? (data['detail'] ?? 'Unknown error') : 'Unknown error'; - throw ApiException(statusCode: response.statusCode, message: detail.toString()); + final detail = + data is Map ? (data['detail'] ?? 'Unknown error') : 'Unknown error'; + throw ApiException( + statusCode: response.statusCode, message: detail.toString()); } } diff --git a/admin_panel/lib/services/api/group_api_service.dart b/admin_panel/lib/services/api/group_api_service.dart index d973548..c5a087a 100644 --- a/admin_panel/lib/services/api/group_api_service.dart +++ b/admin_panel/lib/services/api/group_api_service.dart @@ -4,58 +4,42 @@ import '../interfaces/group_service.dart'; import 'api_client.dart'; /// Real API implementation. -/// NOTE: The backend has no list-groups or list-members endpoint. -/// Groups and members are tracked in memory per session. class GroupApiService implements GroupService { final ApiClient _client; - final List _sessionGroups = []; - final Map> _sessionMembers = {}; GroupApiService(this._client); @override Future> getGroups() async { - return List.unmodifiable(_sessionGroups); + final List data = await _client.get('/admin/groups'); + return data + .map((json) => GroupModel.fromJson(json as Map)) + .toList(); } @override - Future createGroup(String name, String? description) async { - final body = {'name': name}; - if (description != null && description.isNotEmpty) { - body['description'] = description; - } - final data = await _client.post('/groups/', body); - final group = GroupModel.fromJson(data as Map); - _sessionGroups.add(group); - _sessionMembers[group.id] = []; - return group; + Future createGroup(String name) async { + final data = await _client.post('/groups/', {'name': name}); + return GroupModel.fromJson(data as Map); } @override - Future addMember( - String groupId, - String userId, - GroupRole role, - ) async { - final data = await _client.post('/groups/$groupId/members', { - 'user_id': userId, - 'role': role.apiValue, + Future inviteMember(String groupId, String username) async { + await _client.post('/groups/$groupId/invite', { + 'username': username, }); - final member = GroupMemberModel.fromJson(data as Map); - _sessionMembers.putIfAbsent(groupId, () => []).add(member); + } - // Update member count on the cached group - final idx = _sessionGroups.indexWhere((g) => g.id == groupId); - if (idx != -1) { - _sessionGroups[idx] = _sessionGroups[idx].copyWith( - memberCount: (_sessionMembers[groupId]?.length ?? 1), - ); - } - return member; + @override + Future removeMember(String groupId, String userId) async { + await _client.delete('/groups/$groupId/members/$userId'); } @override Future> getGroupMembers(String groupId) async { - return List.unmodifiable(_sessionMembers[groupId] ?? []); + final List data = await _client.get('/groups/$groupId/members'); + return data + .map((json) => GroupMemberModel.fromJson(json as Map)) + .toList(); } } diff --git a/admin_panel/lib/services/api/notification_api_service.dart b/admin_panel/lib/services/api/notification_api_service.dart new file mode 100644 index 0000000..bf7b423 --- /dev/null +++ b/admin_panel/lib/services/api/notification_api_service.dart @@ -0,0 +1,27 @@ +import '../../models/notification_model.dart'; +import '../interfaces/notification_service.dart'; +import 'api_client.dart'; + +class NotificationApiService implements NotificationService { + final ApiClient _client; + + NotificationApiService(this._client); + + @override + Future getNotifications() async { + final List data = await _client.get('/admin/notifications'); + return data + .map((json) => NotificationModel.fromJson(json as Map)) + .toList(); + } + + @override + Future sendPublicNotification(String title, String description) async { + final encodedTitle = Uri.encodeQueryComponent(title); + final encodedDesc = Uri.encodeQueryComponent(description); + await _client.post( + '/notifications/public?title=$encodedTitle&description=$encodedDesc', + {}, + ); + } +} diff --git a/admin_panel/lib/services/api/user_api_service.dart b/admin_panel/lib/services/api/user_api_service.dart index 21084b6..01889e1 100644 --- a/admin_panel/lib/services/api/user_api_service.dart +++ b/admin_panel/lib/services/api/user_api_service.dart @@ -3,28 +3,30 @@ import '../interfaces/user_service.dart'; import 'api_client.dart'; /// Real API implementation. -/// NOTE: The backend has no list-users endpoint, so [getUsers] returns only -/// users created during the current session (stored in memory). class UserApiService implements UserService { final ApiClient _client; - final List _sessionUsers = []; UserApiService(this._client); @override Future> getUsers() async { - return List.unmodifiable(_sessionUsers); + final List data = await _client.get('/admin/users'); + return data + .map((json) => UserModel.fromJson(json as Map)) + .toList(); } @override - Future createUser(String username, UserRole role) async { + Future createUser( + String username, { + String? phoneNumber, + }) async { final data = await _client.post('/admin/users', { 'username': username, - 'role': role.apiValue, + if (phoneNumber != null) 'phone_number': phoneNumber, }); final user = UserModel.fromJson(data['user'] as Map); final secret = data['secret'] as String; - _sessionUsers.add(user); return (user: user, secret: secret); } @@ -36,4 +38,9 @@ class UserApiService implements UserService { ); return data['secret'] as String; } + + @override + Future logoutUser(String userId) async { + await _client.post('/admin/users/$userId/logout', {}); + } } diff --git a/admin_panel/lib/services/interfaces/group_service.dart b/admin_panel/lib/services/interfaces/group_service.dart index 586c3aa..48e8c10 100644 --- a/admin_panel/lib/services/interfaces/group_service.dart +++ b/admin_panel/lib/services/interfaces/group_service.dart @@ -6,14 +6,13 @@ abstract class GroupService { Future> getGroups(); /// Creates a new group. - Future createGroup(String name, String? description); + Future createGroup(String name); - /// Adds a user to a group with the given role. - Future addMember( - String groupId, - String userId, - GroupRole role, - ); + /// Invites a user to a group by username. + Future inviteMember(String groupId, String username); + + /// Removes a member from a group. + Future removeMember(String groupId, String userId); /// Returns all members of a group. Future> getGroupMembers(String groupId); diff --git a/admin_panel/lib/services/interfaces/notification_service.dart b/admin_panel/lib/services/interfaces/notification_service.dart new file mode 100644 index 0000000..87f3bae --- /dev/null +++ b/admin_panel/lib/services/interfaces/notification_service.dart @@ -0,0 +1,11 @@ +import '../../models/notification_model.dart'; + +typedef NotificationList = List; + +abstract class NotificationService { + /// Returns all notifications for admin. + Future getNotifications(); + + /// Broadcasts a public notification to all users. + Future sendPublicNotification(String title, String description); +} diff --git a/admin_panel/lib/services/interfaces/user_service.dart b/admin_panel/lib/services/interfaces/user_service.dart index 60a7ecb..98d2e53 100644 --- a/admin_panel/lib/services/interfaces/user_service.dart +++ b/admin_panel/lib/services/interfaces/user_service.dart @@ -4,12 +4,17 @@ typedef CreateUserResult = ({UserModel user, String secret}); abstract class UserService { /// Returns all users. - /// In real-API mode, returns only in-session created users (no list endpoint). Future> getUsers(); /// Creates a new user and returns the user along with the generated secret. - Future createUser(String username, UserRole role); + Future createUser( + String username, { + String? phoneNumber, + }); /// Resets the secret for [userId] and returns the new secret. Future resetSecret(String userId); + + /// Logs out the user with the given [userId] by incrementing their token version. + Future logoutUser(String userId); } diff --git a/admin_panel/lib/services/mock/mock_data.dart b/admin_panel/lib/services/mock/mock_data.dart index cffa960..ac284c5 100644 --- a/admin_panel/lib/services/mock/mock_data.dart +++ b/admin_panel/lib/services/mock/mock_data.dart @@ -10,84 +10,72 @@ class MockData { username: 'admin', role: UserRole.admin, isActive: true, - createdAt: DateTime(2025, 1, 10), ), UserModel( id: 'u-0002', username: 'ali_karimi', - role: UserRole.group_manager, + role: UserRole.member, isActive: true, - createdAt: DateTime(2025, 2, 3), ), UserModel( id: 'u-0003', username: 'sara_mohammadi', role: UserRole.member, isActive: true, - createdAt: DateTime(2025, 2, 5), ), UserModel( id: 'u-0004', username: 'reza_ahmadi', role: UserRole.member, isActive: true, - createdAt: DateTime(2025, 2, 10), ), UserModel( id: 'u-0005', username: 'maryam_hosseini', - role: UserRole.group_manager, + role: UserRole.member, isActive: true, - createdAt: DateTime(2025, 2, 15), ), UserModel( id: 'u-0006', username: 'javad_rezaei', role: UserRole.member, isActive: false, - createdAt: DateTime(2025, 3, 1), ), UserModel( id: 'u-0007', username: 'nasrin_bagheri', role: UserRole.member, isActive: true, - createdAt: DateTime(2025, 3, 5), ), UserModel( id: 'u-0008', username: 'hamed_safari', role: UserRole.member, isActive: true, - createdAt: DateTime(2025, 3, 10), ), UserModel( id: 'u-0009', username: 'leila_moradi', role: UserRole.member, isActive: true, - createdAt: DateTime(2025, 4, 2), ), UserModel( id: 'u-0010', username: 'mehdi_tavakoli', - role: UserRole.group_manager, + role: UserRole.member, isActive: false, - createdAt: DateTime(2025, 4, 8), ), UserModel( id: 'u-0011', username: 'fatemeh_nazari', role: UserRole.member, isActive: true, - createdAt: DateTime(2025, 5, 1), ), UserModel( id: 'u-0012', username: 'omid_shahidi', role: UserRole.member, isActive: true, - createdAt: DateTime(2025, 5, 15), ), ]; @@ -95,77 +83,147 @@ class MockData { GroupModel( id: 'g-0001', name: 'تیم آلفا', - description: 'واحد عملیاتی اصلی', isActive: true, - type: GroupType.group, - createdAt: DateTime(2025, 1, 15), - memberCount: 4, + type: GroupType.public, ), GroupModel( id: 'g-0002', name: 'تیم براوو', - description: 'واحد پشتیبانی و لجستیک', isActive: true, - type: GroupType.group, - createdAt: DateTime(2025, 1, 20), - memberCount: 3, + type: GroupType.public, ), GroupModel( id: 'g-0003', name: 'مرکز فرماندهی', - description: 'هماهنگی مرکزی تمام تیم‌ها', isActive: true, - type: GroupType.group, - createdAt: DateTime(2025, 2, 1), - memberCount: 5, + type: GroupType.public, ), GroupModel( id: 'g-0004', name: 'لجستیک', - description: 'مدیریت تجهیزات و منابع', isActive: true, - type: GroupType.group, - createdAt: DateTime(2025, 2, 10), - memberCount: 3, + type: GroupType.public, ), GroupModel( id: 'g-0005', name: 'واکنش اضطراری', - description: 'تیم پاسخ سریع به حوادث', isActive: false, - type: GroupType.group, - createdAt: DateTime(2025, 3, 5), - memberCount: 2, + type: GroupType.public, ), ]; static final Map> memberships = { 'g-0001': [ - GroupMemberModel(userId: 'u-0002', groupId: 'g-0001', role: GroupRole.manager, username: 'ali_karimi', joinedAt: DateTime(2025, 1, 15)), - GroupMemberModel(userId: 'u-0003', groupId: 'g-0001', role: GroupRole.member, username: 'sara_mohammadi', joinedAt: DateTime(2025, 1, 16)), - GroupMemberModel(userId: 'u-0004', groupId: 'g-0001', role: GroupRole.member, username: 'reza_ahmadi', joinedAt: DateTime(2025, 1, 17)), - GroupMemberModel(userId: 'u-0007', groupId: 'g-0001', role: GroupRole.member, username: 'nasrin_bagheri', joinedAt: DateTime(2025, 2, 1)), + GroupMemberModel( + userId: 'u-0002', + role: GroupRole.manager, + username: 'ali_karimi', + isOnline: true, + ), + GroupMemberModel( + userId: 'u-0003', + role: GroupRole.member, + username: 'sara_mohammadi', + isOnline: false, + ), + GroupMemberModel( + userId: 'u-0004', + role: GroupRole.member, + username: 'reza_ahmadi', + isOnline: true, + ), + GroupMemberModel( + userId: 'u-0007', + role: GroupRole.member, + username: 'nasrin_bagheri', + isOnline: false, + ), ], 'g-0002': [ - GroupMemberModel(userId: 'u-0005', groupId: 'g-0002', role: GroupRole.manager, username: 'maryam_hosseini', joinedAt: DateTime(2025, 1, 20)), - GroupMemberModel(userId: 'u-0008', groupId: 'g-0002', role: GroupRole.member, username: 'hamed_safari', joinedAt: DateTime(2025, 1, 21)), - GroupMemberModel(userId: 'u-0009', groupId: 'g-0002', role: GroupRole.member, username: 'leila_moradi', joinedAt: DateTime(2025, 1, 22)), + GroupMemberModel( + userId: 'u-0005', + role: GroupRole.manager, + username: 'maryam_hosseini', + isOnline: true, + ), + GroupMemberModel( + userId: 'u-0008', + role: GroupRole.member, + username: 'hamed_safari', + isOnline: false, + ), + GroupMemberModel( + userId: 'u-0009', + role: GroupRole.member, + username: 'leila_moradi', + isOnline: true, + ), ], 'g-0003': [ - GroupMemberModel(userId: 'u-0001', groupId: 'g-0003', role: GroupRole.manager, username: 'admin', joinedAt: DateTime(2025, 2, 1)), - GroupMemberModel(userId: 'u-0002', groupId: 'g-0003', role: GroupRole.member, username: 'ali_karimi', joinedAt: DateTime(2025, 2, 2)), - GroupMemberModel(userId: 'u-0005', groupId: 'g-0003', role: GroupRole.member, username: 'maryam_hosseini', joinedAt: DateTime(2025, 2, 3)), - GroupMemberModel(userId: 'u-0010', groupId: 'g-0003', role: GroupRole.member, username: 'mehdi_tavakoli', joinedAt: DateTime(2025, 2, 5)), - GroupMemberModel(userId: 'u-0011', groupId: 'g-0003', role: GroupRole.member, username: 'fatemeh_nazari', joinedAt: DateTime(2025, 2, 10)), + GroupMemberModel( + userId: 'u-0001', + role: GroupRole.manager, + username: 'admin', + isOnline: true, + ), + GroupMemberModel( + userId: 'u-0002', + role: GroupRole.member, + username: 'ali_karimi', + isOnline: true, + ), + GroupMemberModel( + userId: 'u-0005', + role: GroupRole.member, + username: 'maryam_hosseini', + isOnline: false, + ), + GroupMemberModel( + userId: 'u-0010', + role: GroupRole.member, + username: 'mehdi_tavakoli', + isOnline: false, + ), + GroupMemberModel( + userId: 'u-0011', + role: GroupRole.member, + username: 'fatemeh_nazari', + isOnline: true, + ), ], 'g-0004': [ - GroupMemberModel(userId: 'u-0010', groupId: 'g-0004', role: GroupRole.manager, username: 'mehdi_tavakoli', joinedAt: DateTime(2025, 2, 10)), - GroupMemberModel(userId: 'u-0011', groupId: 'g-0004', role: GroupRole.member, username: 'fatemeh_nazari', joinedAt: DateTime(2025, 2, 11)), - GroupMemberModel(userId: 'u-0012', groupId: 'g-0004', role: GroupRole.member, username: 'omid_shahidi', joinedAt: DateTime(2025, 2, 12)), + GroupMemberModel( + userId: 'u-0010', + role: GroupRole.manager, + username: 'mehdi_tavakoli', + isOnline: true, + ), + GroupMemberModel( + userId: 'u-0011', + role: GroupRole.member, + username: 'fatemeh_nazari', + isOnline: false, + ), + GroupMemberModel( + userId: 'u-0012', + role: GroupRole.member, + username: 'omid_shahidi', + isOnline: true, + ), ], 'g-0005': [ - GroupMemberModel(userId: 'u-0002', groupId: 'g-0005', role: GroupRole.manager, username: 'ali_karimi', joinedAt: DateTime(2025, 3, 5)), - GroupMemberModel(userId: 'u-0006', groupId: 'g-0005', role: GroupRole.member, username: 'javad_rezaei', joinedAt: DateTime(2025, 3, 6)), + GroupMemberModel( + userId: 'u-0002', + role: GroupRole.manager, + username: 'ali_karimi', + isOnline: false, + ), + GroupMemberModel( + userId: 'u-0006', + role: GroupRole.member, + username: 'javad_rezaei', + isOnline: false, + ), ], }; } diff --git a/admin_panel/lib/services/mock/mock_group_service.dart b/admin_panel/lib/services/mock/mock_group_service.dart index 21eba46..78205fc 100644 --- a/admin_panel/lib/services/mock/mock_group_service.dart +++ b/admin_panel/lib/services/mock/mock_group_service.dart @@ -8,8 +8,7 @@ import 'mock_data.dart'; class MockGroupService implements GroupService { final List _groups = List.from(MockData.groups); final Map> _members = { - for (final e in MockData.memberships.entries) - e.key: List.from(e.value), + for (final e in MockData.memberships.entries) e.key: List.from(e.value), }; final _uuid = const Uuid(); @@ -20,17 +19,14 @@ class MockGroupService implements GroupService { } @override - Future createGroup(String name, String? description) async { + Future createGroup(String name) async { await Future.delayed(const Duration(milliseconds: 500)); final group = GroupModel( id: 'g-${_uuid.v4().substring(0, 8)}', name: name, - description: description, isActive: true, - type: GroupType.group, - createdAt: DateTime.now(), - memberCount: 0, + type: GroupType.public, ); _groups.add(group); _members[group.id] = []; @@ -38,11 +34,7 @@ class MockGroupService implements GroupService { } @override - Future addMember( - String groupId, - String userId, - GroupRole role, - ) async { + Future inviteMember(String groupId, String username) async { await Future.delayed(const Duration(milliseconds: 400)); final groupIdx = _groups.indexWhere((g) => g.id == groupId); @@ -51,23 +43,21 @@ class MockGroupService implements GroupService { } final existingMembers = _members.putIfAbsent(groupId, () => []); - if (existingMembers.any((m) => m.userId == userId)) { - throw const ApiException(statusCode: 400, message: 'کاربر قبلاً عضو این گروه است'); - } - final member = GroupMemberModel( - userId: userId, - groupId: groupId, - role: role, - joinedAt: DateTime.now(), + userId: _uuid.v4().substring(0, 8), + username: username, + role: GroupRole.member, ); existingMembers.add(member); + } - _groups[groupIdx] = _groups[groupIdx].copyWith( - memberCount: existingMembers.length, - ); - - return member; + @override + Future removeMember(String groupId, String userId) async { + await Future.delayed(const Duration(milliseconds: 300)); + final members = _members[groupId]; + if (members != null) { + members.removeWhere((m) => m.userId == userId); + } } @override diff --git a/admin_panel/lib/services/mock/mock_notification_service.dart b/admin_panel/lib/services/mock/mock_notification_service.dart new file mode 100644 index 0000000..266ec0b --- /dev/null +++ b/admin_panel/lib/services/mock/mock_notification_service.dart @@ -0,0 +1,53 @@ +import '../../models/notification_model.dart'; +import '../interfaces/notification_service.dart'; +import '../api/api_client.dart'; + +class MockNotificationService implements NotificationService { + final List _items = [ + const NotificationModel( + id: 'n-0001', + title: 'به‌روزرسانی سامانه', + description: 'ساعت ۲۲ سرویس برای ۱۵ دقیقه در دسترس نیست.', + type: NotificationType.public, + isAccepted: null, + receiverId: 'all', + senderId: 'admin', + groupId: null, + ), + const NotificationModel( + id: 'n-0002', + title: 'درخواست عضویت', + description: 'کاربر ali_karimi درخواست عضویت ارسال کرده است.', + type: NotificationType.joinRequest, + isAccepted: null, + receiverId: 'admin', + senderId: 'u-0002', + groupId: 'g-0001', + ), + ]; + + @override + Future getNotifications() async { + await Future.delayed(const Duration(milliseconds: 350)); + return List.unmodifiable(_items); + } + + @override + Future sendPublicNotification(String title, String description) async { + await Future.delayed(const Duration(milliseconds: 300)); + if (title.trim().isEmpty) { + throw const ApiException(statusCode: 400, message: 'عنوان الزامی است'); + } + final item = NotificationModel( + id: 'n-${_items.length + 1}', + title: title, + description: description, + type: NotificationType.public, + isAccepted: null, + receiverId: 'all', + senderId: 'admin', + groupId: null, + ); + _items.insert(0, item); + } +} diff --git a/admin_panel/lib/services/mock/mock_user_service.dart b/admin_panel/lib/services/mock/mock_user_service.dart index 18ae214..5d3b319 100644 --- a/admin_panel/lib/services/mock/mock_user_service.dart +++ b/admin_panel/lib/services/mock/mock_user_service.dart @@ -15,18 +15,23 @@ class MockUserService implements UserService { } @override - Future createUser(String username, UserRole role) async { + Future createUser( + String username, { + String? phoneNumber, + }) async { await Future.delayed(const Duration(milliseconds: 500)); if (_users.any((u) => u.username == username)) { - throw const ApiException(statusCode: 400, message: 'این نام کاربری قبلاً ثبت شده است'); + throw const ApiException( + statusCode: 400, message: 'این نام کاربری قبلاً ثبت شده است'); } final secret = _generateSecret(); final user = UserModel( id: 'u-${_uuid.v4().substring(0, 8)}', username: username, - role: role, + phoneNumber: phoneNumber, + role: UserRole.member, isActive: true, createdAt: DateTime.now(), ); @@ -45,6 +50,15 @@ class MockUserService implements UserService { return _generateSecret(); } + @override + Future logoutUser(String userId) async { + await Future.delayed(const Duration(milliseconds: 300)); + final idx = _users.indexWhere((u) => u.id == userId); + if (idx == -1) { + throw const ApiException(statusCode: 404, message: 'کاربر یافت نشد'); + } + } + String _generateSecret() { final uuid = _uuid.v4().replaceAll('-', ''); return uuid.substring(0, 16); diff --git a/admin_panel/lib/services/service_locator.dart b/admin_panel/lib/services/service_locator.dart index df1767b..21bab6c 100644 --- a/admin_panel/lib/services/service_locator.dart +++ b/admin_panel/lib/services/service_locator.dart @@ -2,13 +2,16 @@ import '../config/app_config.dart'; import 'interfaces/auth_service.dart'; import 'interfaces/user_service.dart'; import 'interfaces/group_service.dart'; +import 'interfaces/notification_service.dart'; import 'api/api_client.dart'; import 'api/auth_api_service.dart'; import 'api/user_api_service.dart'; import 'api/group_api_service.dart'; +import 'api/notification_api_service.dart'; import 'mock/mock_auth_service.dart'; import 'mock/mock_user_service.dart'; import 'mock/mock_group_service.dart'; +import 'mock/mock_notification_service.dart'; /// Singleton that wires together the correct service implementations /// based on [AppConfig.debugMode]. @@ -20,6 +23,7 @@ class ServiceLocator { late final AuthService auth; late final UserService users; late final GroupService groups; + late final NotificationService notifications; ApiClient? _apiClient; @@ -28,14 +32,24 @@ class ServiceLocator { auth = MockAuthService(); users = MockUserService(); groups = MockGroupService(); + notifications = MockNotificationService(); } else { _apiClient = ApiClient(baseUrl: AppConfig.baseUrl); auth = AuthApiService(_apiClient!); users = UserApiService(_apiClient!); groups = GroupApiService(_apiClient!); + notifications = NotificationApiService(_apiClient!); } } void setToken(String token) => _apiClient?.setToken(token); void clearToken() => _apiClient?.clearToken(); + + /// Exposed for one-off direct API calls (e.g. notifications). + ApiClient get apiClient { + if (_apiClient == null) { + throw StateError('ApiClient not initialized – running in debug mode?'); + } + return _apiClient!; + } } diff --git a/admin_panel/lib/theme/app_theme.dart b/admin_panel/lib/theme/app_theme.dart index 3fd3fc5..84bf867 100644 --- a/admin_panel/lib/theme/app_theme.dart +++ b/admin_panel/lib/theme/app_theme.dart @@ -22,8 +22,6 @@ class AppTheme { switch (role) { case 'admin': return const Color(0xFF7C3AED); - case 'group_manager': - return const Color(0xFF0891B2); default: return const Color(0xFF64748B); } diff --git a/admin_panel/lib/widgets/app_sidebar.dart b/admin_panel/lib/widgets/app_sidebar.dart index 06562a6..18d9c6c 100644 --- a/admin_panel/lib/widgets/app_sidebar.dart +++ b/admin_panel/lib/widgets/app_sidebar.dart @@ -9,9 +9,14 @@ class AppSidebar extends StatelessWidget { const AppSidebar({super.key}); static const _navItems = [ - _NavItem(label: 'داشبورد', icon: Icons.dashboard_rounded, route: '/dashboard'), + _NavItem( + label: 'داشبورد', icon: Icons.dashboard_rounded, route: '/dashboard'), _NavItem(label: 'کاربران', icon: Icons.people_rounded, route: '/users'), _NavItem(label: 'گروه‌ها', icon: Icons.groups_rounded, route: '/groups'), + _NavItem( + label: 'اعلان‌ها', + icon: Icons.campaign_rounded, + route: '/notifications'), ]; @override @@ -75,7 +80,8 @@ class AppSidebar extends StatelessWidget { decoration: BoxDecoration( color: AppTheme.warning.withValues(alpha: 0.15), borderRadius: BorderRadius.circular(6), - border: Border.all(color: AppTheme.warning.withValues(alpha: 0.4)), + border: + Border.all(color: AppTheme.warning.withValues(alpha: 0.4)), ), child: const Row( children: [ diff --git a/call/.gitignore b/call/.gitignore new file mode 100644 index 0000000..3820a95 --- /dev/null +++ b/call/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/call/.metadata b/call/.metadata new file mode 100644 index 0000000..54bb785 --- /dev/null +++ b/call/.metadata @@ -0,0 +1,45 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "cd9e44ff10cac283eafc97d6ed58720c45f1be9e" + channel: "master" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + base_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + - platform: android + create_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + base_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + - platform: ios + create_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + base_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + - platform: linux + create_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + base_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + - platform: macos + create_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + base_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + - platform: web + create_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + base_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + - platform: windows + create_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + base_revision: cd9e44ff10cac283eafc97d6ed58720c45f1be9e + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/call/README.md b/call/README.md new file mode 100644 index 0000000..91925d5 --- /dev/null +++ b/call/README.md @@ -0,0 +1,3 @@ +# call + +A new Flutter project. diff --git a/call/analysis_options.yaml b/call/analysis_options.yaml new file mode 100644 index 0000000..f9b3034 --- /dev/null +++ b/call/analysis_options.yaml @@ -0,0 +1 @@ +include: package:flutter_lints/flutter.yaml diff --git a/call/android/.gitignore b/call/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/call/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/call/android/app/build.gradle.kts b/call/android/app/build.gradle.kts new file mode 100644 index 0000000..56ecfc4 --- /dev/null +++ b/call/android/app/build.gradle.kts @@ -0,0 +1,44 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "com.example.call" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_17.toString() + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.example.call" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} diff --git a/call/android/app/src/debug/AndroidManifest.xml b/call/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/call/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + 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_