using System; using System.IO; using System.Runtime.InteropServices; using System.Speech.Synthesis; using System.Threading; using System.Windows; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Threading; using ClassNotify.Client.Services; using ClassNotify.Shared.Enums; using ClassNotify.Shared.Models; namespace ClassNotify.Client { public partial class MainWindow : Window { private readonly NotificationDto _notification; private readonly Action _onAckCompleted; private DispatcherTimer? _countdownTimer; private DispatcherTimer? _topmostGuardTimer; private DispatcherTimer? _autoScrollTimer; private double _autoScrollOffset = 0; private bool _isAutoScrollHolding = false; private int _autoScrollHoldTicks = 0; private int _remainingSeconds = 15; public MainWindow(NotificationDto notification, Action onAckCompleted) { InitializeComponent(); _notification = notification; _onAckCompleted = onAckCompleted; // Monitor & DPI-Aware True Fullscreen (GPT Turn 80 Architecture Specification) DisplayBoundsService.ApplyFullscreenBounds(this); this.Topmost = true; ApplyData(); this.SourceInitialized += (s, e) => { DisplayBoundsService.ApplyFullscreenBounds(this); }; this.Loaded += MainWindow_Loaded; this.SizeChanged += (s, e) => ApplyAdaptiveTypography(); this.DpiChanged += (s, e) => { DisplayBoundsService.ApplyFullscreenBounds(this); ApplyAdaptiveTypography(); }; this.Deactivated += (s, e) => ForceTopmost(); this.Closed += (s, e) => { StopShake(); _autoScrollTimer?.Stop(); _countdownTimer?.Stop(); _topmostGuardTimer?.Stop(); }; } private void ApplyData() { TxtTitle.Text = _notification.Title; TxtMessage.Text = _notification.Message; _remainingSeconds = _notification.DurationSeconds; // Apply theme color based on type switch (_notification.Type) { case NotificationType.Call: TxtIcon.Text = "πŸ””"; HeaderBorder.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#2563EB")); BtnAcknowledge.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#2563EB")); break; case NotificationType.Notice: TxtIcon.Text = "πŸ“’"; HeaderBorder.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#059669")); BtnAcknowledge.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#059669")); break; case NotificationType.Urgent: TxtIcon.Text = "⚠️"; HeaderBorder.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); BtnAcknowledge.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); break; } } private void MainWindow_Loaded(object sender, RoutedEventArgs e) { DisplayBoundsService.ApplyFullscreenBounds(this); ApplyAdaptiveTypography(); ForceTopmost(); StartTopmostGuard(); // Shake window + Play Xiaoxiao alert voice if (_notification.Shake) { StartStrongShake(); AudioTtsService.PlayShakeSound(); } // Play TTS: default to Xiaoxiao neural voice with offline fallback if (_notification.Voice) { _ = AudioTtsService.PlayMessageAsync(_notification.Message, "zh-CN-XiaoxiaoNeural"); } StartCountdown(); } private void StartCountdown() { if (_remainingSeconds <= 0) { TxtCountdown.Text = "πŸ“Œ θ―·ε€§ε±ε‰εΈˆη”Ÿη‚Ήε‡»γ€ζˆ‘ηŸ₯ι“δΊ†γ€‘ζΆˆι™€ι€šηŸ₯"; TxtCountdown.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#DC2626")); TxtCountdown.FontWeight = FontWeights.Bold; return; } TxtCountdown.Text = $"ε°†εœ¨ {_remainingSeconds} η§’εŽθ‡ͺεŠ¨ε…³ι—­"; _countdownTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) }; _countdownTimer.Tick += (s, e) => { _remainingSeconds--; if (_remainingSeconds <= 0) { _countdownTimer.Stop(); _onAckCompleted(AckStatus.Timeout); this.Close(); } else { TxtCountdown.Text = $"ε°†εœ¨ {_remainingSeconds} η§’εŽθ‡ͺεŠ¨ε…³ι—­"; } }; _countdownTimer.Start(); } private Storyboard? _activeShakeStoryboard; private void StartStrongShake() { try { if (TryFindResource("StrongShakeStoryboard") is not Storyboard storyboard) return; _activeShakeStoryboard?.Remove(this); _activeShakeStoryboard = storyboard.Clone(); NotificationTranslate.X = 0; NotificationTranslate.Y = 0; NotificationRotate.Angle = 0; _activeShakeStoryboard.Completed += (_, _) => { NotificationTranslate.X = 0; NotificationTranslate.Y = 0; NotificationRotate.Angle = 0; }; _activeShakeStoryboard.Begin(this, true); } catch { } } private void StopShake() { try { _activeShakeStoryboard?.Stop(this); _activeShakeStoryboard?.Remove(this); _activeShakeStoryboard = null; NotificationTranslate.X = 0; NotificationTranslate.Y = 0; NotificationRotate.Angle = 0; } catch { } } private void BtnAcknowledge_Click(object sender, RoutedEventArgs e) { StopShake(); _autoScrollTimer?.Stop(); _countdownTimer?.Stop(); _onAckCompleted(AckStatus.Acknowledged); this.Close(); } public void SimulateAcknowledgeClick() { BtnAcknowledge_Click(BtnAcknowledge, new RoutedEventArgs()); } /// /// Precision Classroom Typography Engine: /// Dynamically applies DisplayProfile for adaptive header/footer proportions, /// and runs NotificationLayoutEngine to guarantee 100% visible, unclipped text /// across all classroom resolutions (800p, 1080p, 4K) with zero manual scrolling required. /// private void ApplyAdaptiveTypography() { if (string.IsNullOrWhiteSpace(TxtMessage.Text)) return; double winW = (!double.IsNaN(this.ActualWidth) && this.ActualWidth > 0) ? this.ActualWidth : (!double.IsNaN(this.Width) && this.Width > 0 ? this.Width : SystemParameters.PrimaryScreenWidth); double winH = (!double.IsNaN(this.ActualHeight) && this.ActualHeight > 0) ? this.ActualHeight : (!double.IsNaN(this.Height) && this.Height > 0 ? this.Height : SystemParameters.PrimaryScreenHeight); if (double.IsNaN(winW) || winW <= 50) winW = 1536; if (double.IsNaN(winH) || winH <= 50) winH = 864; // Apply DisplayProfile for adaptive header/footer sizing double screenW = SystemParameters.PrimaryScreenWidth > 0 ? SystemParameters.PrimaryScreenWidth : winW; double screenH = SystemParameters.PrimaryScreenHeight > 0 ? SystemParameters.PrimaryScreenHeight : winH; var profile = DisplayProfile.GetProfile(screenW, screenH); RowHeader.Height = new GridLength(profile.HeaderHeight); RowFooter.Height = new GridLength(profile.FooterHeight); BtnAcknowledge.Height = profile.ButtonHeight; BtnAcknowledge.Width = profile.ButtonWidth; BtnAcknowledge.FontSize = profile.ButtonFontSize; TxtIcon.FontSize = profile.IconFontSize; TxtTitle.FontSize = profile.TitleFontSize; TxtCountdown.FontSize = profile.CountdownFontSize; BodyGrid.Margin = profile.BodyMargin; TxtMessage.Margin = profile.MessageMargin; // Determine available body canvas dimensions with strict NaN defense double availW = (!double.IsNaN(BodyGrid.ActualWidth) && BodyGrid.ActualWidth > 0) ? Math.Max(280, BodyGrid.ActualWidth - TxtMessage.Margin.Left - TxtMessage.Margin.Right) : Math.Max(280, winW - 140); double availH = (!double.IsNaN(BodyGrid.ActualHeight) && BodyGrid.ActualHeight > 0) ? Math.Max(140, BodyGrid.ActualHeight - TxtMessage.Margin.Top - TxtMessage.Margin.Bottom) : Math.Max(140, winH - profile.HeaderHeight - profile.FooterHeight - 48); var typo = NotificationLayoutEngine.CalculateOptimalTypography( TxtMessage.Text, availW, availH, TxtMessage.FontFamily, TxtMessage.FontWeight, winH ); TxtMessage.FontSize = typo.FontSize; TxtMessage.LineHeight = typo.LineHeight; // Stop any existing auto-scroll timer _autoScrollTimer?.Stop(); _autoScrollTimer = null; MessageScrollViewer.ScrollToTop(); if (typo.NeedsAutoScroll) { // Tier 4: Long text auto-scroll marquee (ChatGPT Brain specification: ~25-30px/s) _autoScrollOffset = 0; _isAutoScrollHolding = false; _autoScrollHoldTicks = 0; _autoScrollTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(40) }; _autoScrollTimer.Tick += (s, e) => { if (_isAutoScrollHolding) { _autoScrollHoldTicks++; if (_autoScrollHoldTicks >= 75) // 3 seconds hold at bottom { _isAutoScrollHolding = false; _autoScrollHoldTicks = 0; _autoScrollOffset = 0; MessageScrollViewer.ScrollToTop(); } return; } _autoScrollOffset += 1.0; MessageScrollViewer.ScrollToVerticalOffset(_autoScrollOffset); if (_autoScrollOffset >= MessageScrollViewer.ScrollableHeight) { _isAutoScrollHolding = true; _autoScrollHoldTicks = 0; } }; _autoScrollTimer.Start(); } } #region Win32 Forceful Topmost Implementation private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); private const uint SWP_NOSIZE = 0x0001; private const uint SWP_NOMOVE = 0x0002; private const uint SWP_SHOWWINDOW = 0x0040; [DllImport("user32.dll", SetLastError = true)] private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); [DllImport("user32.dll")] private static extern bool BringWindowToTop(IntPtr hWnd); [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr lpdwProcessId); [DllImport("user32.dll")] private static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach); [DllImport("kernel32.dll")] private static extern uint GetCurrentThreadId(); /// /// Enterprise Forceful Topmost: /// Overrides full-screen PPT, εΈŒζ²ƒη™½ζΏ (Seewo), full-screen video players, and games. /// Uses Win32 HWND_TOPMOST + BringWindowToTop + AttachThreadInput foreground stealing. /// public void ForceTopmost() { try { this.Topmost = true; var handle = new WindowInteropHelper(this).Handle; if (handle == IntPtr.Zero) return; SetWindowPos(handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); BringWindowToTop(handle); IntPtr foreHandle = GetForegroundWindow(); if (foreHandle != IntPtr.Zero && foreHandle != handle) { uint foreThread = GetWindowThreadProcessId(foreHandle, IntPtr.Zero); uint currentThread = GetCurrentThreadId(); if (foreThread != currentThread) { AttachThreadInput(currentThread, foreThread, true); SetForegroundWindow(handle); AttachThreadInput(currentThread, foreThread, false); } else { SetForegroundWindow(handle); } } } catch { } } private void StartTopmostGuard() { _topmostGuardTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) }; _topmostGuardTimer.Tick += (s, e) => ForceTopmost(); _topmostGuardTimer.Start(); } #endregion protected override void OnClosed(EventArgs e) { base.OnClosed(e); StopShake(); _countdownTimer?.Stop(); _topmostGuardTimer?.Stop(); AudioTtsService.Stop(); } } }