// Coque WebView2 pour SMART CENTRAL : ouvre l'application web locale dans une fenêtre Windows native, avec onglets. // Compilé avec le csc du .NET Framework 4.8 (C# 5) — voir build.ps1. using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.IO; using System.Net; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.Web.WebView2.Core; using Microsoft.Web.WebView2.WinForms; namespace SmartCentral.Desktop { internal static class Program { [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll")] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hWnd); [DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr hWnd); private const int SW_RESTORE = 9; [STAThread] private static void Main(string[] args) { // Une seule instance par session Windows. Si l'appli tourne déjà, on ramène sa fenêtre devant // (restaurée si elle est réduite) et on quitte. bool firstInstance; Mutex mutex = new Mutex(true, @"Local\SmartCentral.WebView2", out firstInstance); if (!firstInstance) { if (ActivateExistingWindow()) return; // Instance précédente sans fenêtre visible : elle est en train de se fermer (déconnexion, // 5 s max). On attend qu'elle libère le verrou puis on démarre normalement. try { if (!mutex.WaitOne(10000)) return; } catch (AbandonedMutexException) { } // instance précédente tuée : le verrou est à nous } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Ordre de priorité : argument en ligne de commande > SmartCentral.exe.config > http://localhost string url = args.Length > 0 ? args[0] : ConfigurationManager.AppSettings["Url"]; if (string.IsNullOrWhiteSpace(url)) url = "http://localhost"; Application.Run(new MainForm(new Uri(url))); GC.KeepAlive(mutex); } private static bool ActivateExistingWindow() { Process current = Process.GetCurrentProcess(); foreach (Process p in Process.GetProcessesByName(current.ProcessName)) { if (p.Id == current.Id) continue; IntPtr h = p.MainWindowHandle; if (h == IntPtr.Zero || !IsWindowVisible(h)) continue; if (IsIconic(h)) ShowWindow(h, SW_RESTORE); SetForegroundWindow(h); return true; } return false; } } // Un onglet = un contrôle WebView2. Tous partagent le même environnement (même profil, mêmes cookies, // donc une seule session Laravel). internal sealed class BrowserTab { public WebView2 View; public string Title = "Nouvel onglet"; public bool Loading; public string RetryUri; // URL à recharger (F5) après la page « Impossible de joindre » } internal sealed class MainForm : Form { private const int MaxTabs = 15; private const string AppTitle = "SMART CENTRAL"; private readonly Uri _startUri; private readonly string _dataDir = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SmartCentral", "WebView2"); private readonly List _tabs = new List(); private readonly Panel _content = new Panel(); private readonly TabStrip _strip; private CoreWebView2Environment _env; private BrowserTab _current; private FormWindowState _stateBeforeFullscreen; private bool _fullscreen; private bool _closing; public MainForm(Uri startUri) { _startUri = startUri; Text = AppTitle; Size = new Size(1400, 900); StartPosition = FormStartPosition.CenterScreen; WindowState = FormWindowState.Maximized; KeyPreview = true; try { Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); } catch { } _strip = new TabStrip(this); _strip.Dock = DockStyle.Top; _content.Dock = DockStyle.Fill; Controls.Add(_content); // Fill d'abord, puis Top : la barre d'onglets est placée au-dessus Controls.Add(_strip); Load += OnLoad; } internal IList Tabs { get { return _tabs; } } internal BrowserTab Current { get { return _current; } } private async void OnLoad(object sender, EventArgs e) { // Profil (cookies, session Laravel, cache) stocké hors du dossier de l'exe. BrowserTab first; try { _env = await CoreWebView2Environment.CreateAsync(null, _dataDir); first = await CreateTabAsync(); } catch (WebView2RuntimeNotFoundException) { MessageBox.Show(this, "Le runtime Microsoft Edge WebView2 n'est pas installé.\n" + "Téléchargez-le sur https://go.microsoft.com/fwlink/p/?LinkId=2124703", AppTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); Close(); return; } // Toujours démarrer déconnecté : une session laissée par un arrêt brutal (plantage, fin de tâche) // reconnecterait automatiquement et, en mode BHP, bloquerait toute autre connexion. await LogoutAsync(); first.View.Source = _startUri; } // ---------------------------------------------------------------- Onglets // Crée un onglet vide (non navigué) et l'affiche. null si le maximum est atteint. private async Task CreateTabAsync() { if (_tabs.Count >= MaxTabs) { MessageBox.Show(this, "Maximum " + MaxTabs + " onglets. Fermez-en un pour en ouvrir un autre.", AppTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); return null; } BrowserTab tab = new BrowserTab(); tab.View = new WebView2(); tab.View.Dock = DockStyle.Fill; tab.View.Visible = false; _content.Controls.Add(tab.View); _tabs.Add(tab); SelectTab(tab); IntPtr forceHandle = tab.View.Handle; // l'initialisation attend que le contrôle ait un handle await tab.View.EnsureCoreWebView2Async(_env); WireTab(tab); return tab; } internal async void NewTab() { BrowserTab tab = await CreateTabAsync(); if (tab != null) tab.View.Source = _startUri; } internal void SelectTab(BrowserTab tab) { if (tab == null || !_tabs.Contains(tab)) return; if (_current != null && _current != tab) _current.View.Visible = false; _current = tab; tab.View.Visible = true; tab.View.Focus(); // Si on change d'onglet depuis un raccourci, l'ancien onglet est en train de traiter la touche et // reprend le focus juste après : on redonne le focus au nouvel onglet une fois la touche traitée. if (IsHandleCreated) BeginInvoke(new Action(delegate { if (_current == tab && !tab.View.IsDisposed) tab.View.Focus(); })); UpdateWindowTitle(); _strip.Invalidate(); } // Le dernier onglet ne se ferme pas : on ferme l'appli avec la croix de la fenêtre. internal void CloseTab(BrowserTab tab) { int idx = _tabs.IndexOf(tab); if (idx < 0 || _tabs.Count <= 1) return; _tabs.RemoveAt(idx); if (tab == _current) SelectTab(_tabs[Math.Min(idx, _tabs.Count - 1)]); _content.Controls.Remove(tab.View); tab.View.Dispose(); _strip.Invalidate(); } private void SelectRelative(int delta) { if (_tabs.Count < 2 || _current == null) return; int idx = (_tabs.IndexOf(_current) + delta + _tabs.Count) % _tabs.Count; SelectTab(_tabs[idx]); } private void UpdateWindowTitle() { Text = _current == null || _current.Title == "Nouvel onglet" ? AppTitle : _current.Title; } private void WireTab(BrowserTab tab) { CoreWebView2 core = tab.View.CoreWebView2; core.Settings.IsStatusBarEnabled = false; tab.View.KeyDown += delegate(object s, KeyEventArgs e) { if (HandleShortcut(e.KeyData)) e.Handled = true; }; core.DocumentTitleChanged += delegate { tab.Title = string.IsNullOrEmpty(core.DocumentTitle) ? AppTitle : core.DocumentTitle; if (tab == _current) UpdateWindowTitle(); _strip.Invalidate(); }; core.NavigationStarting += delegate { tab.Loading = true; _strip.Invalidate(); }; core.NavigationCompleted += delegate(object s, CoreWebView2NavigationCompletedEventArgs e) { tab.Loading = false; _strip.Invalidate(); OnNavigationCompleted(tab, e); }; core.NewWindowRequested += delegate(object s, CoreWebView2NewWindowRequestedEventArgs e) { OnNewWindowRequested(e); }; core.WindowCloseRequested += delegate { CloseTab(tab); }; // window.close() dans la page core.ContainsFullScreenElementChanged += delegate { if (tab == _current) SetFullscreen(core.ContainsFullScreenElement); }; } // Liens target=_blank, window.open(url), clic molette, « Ouvrir dans un nouvel onglet » : // - autre site que l'appli : navigateur par défaut ; // - popup avec taille ou position (window.open(url, '', 'width=…')) : petite fenêtre WebView2 ; // - sinon : nouvel onglet. window.opener est conservé (la page d'origine garde la main sur l'onglet). private async void OnNewWindowRequested(CoreWebView2NewWindowRequestedEventArgs e) { Uri target; if (Uri.TryCreate(e.Uri, UriKind.Absolute, out target) && (target.Scheme == Uri.UriSchemeHttp || target.Scheme == Uri.UriSchemeHttps) && !string.Equals(target.Host, _startUri.Host, StringComparison.OrdinalIgnoreCase)) { e.Handled = true; Process.Start(new ProcessStartInfo(target.AbsoluteUri) { UseShellExecute = true }); return; } if (e.WindowFeatures.HasSize || e.WindowFeatures.HasPosition) return; CoreWebView2Deferral deferral = e.GetDeferral(); try { BrowserTab tab = await CreateTabAsync(); if (tab != null) e.NewWindow = tab.View.CoreWebView2; else e.Handled = true; } finally { deferral.Complete(); } } private void OnNavigationCompleted(BrowserTab tab, CoreWebView2NavigationCompletedEventArgs e) { if (e.IsSuccess) return; CoreWebView2 core = tab.View.CoreWebView2; // Journal des échecs : %LOCALAPPDATA%\SmartCentral\navigation.log try { File.AppendAllText(Path.Combine(Path.GetDirectoryName(_dataDir), "navigation.log"), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + core.Source + " err=" + e.WebErrorStatus + " http=" + e.HttpStatusCode + Environment.NewLine); } catch { } // Page d'erreur uniquement si le serveur est injoignable. Les autres échecs (navigation // interrompue par une autre, window.stop(), réponse 4xx/5xx) laissent la page telle quelle. switch (e.WebErrorStatus) { case CoreWebView2WebErrorStatus.CannotConnect: case CoreWebView2WebErrorStatus.ConnectionAborted: case CoreWebView2WebErrorStatus.ConnectionReset: case CoreWebView2WebErrorStatus.Disconnected: case CoreWebView2WebErrorStatus.HostNameNotResolved: case CoreWebView2WebErrorStatus.ServerUnreachable: case CoreWebView2WebErrorStatus.Timeout: break; default: return; } tab.RetryUri = core.Source; string html = "Serveur injoignable" + "" + "

Impossible de joindre " + WebUtility.HtmlEncode(_startUri.AbsoluteUri) + "

" + "

Vérifiez que WAMP (Apache) est démarré, puis appuyez sur F5.

" + "

Erreur : " + e.WebErrorStatus + "

"; core.NavigateToString(html); } // ---------------------------------------------------------------- Fermeture / déconnexion // Fermeture : déconnexion de l'utilisateur avant de quitter (la fenêtre est masquée pendant l'appel). protected override async void OnFormClosing(FormClosingEventArgs e) { if (_closing || AnyCore() == null) { base.OnFormClosing(e); return; } e.Cancel = true; _closing = true; Hide(); await LogoutAsync(); Close(); } private CoreWebView2 AnyCore() { foreach (BrowserTab t in _tabs) if (t.View.CoreWebView2 != null) return t.View.CoreWebView2; return null; } // Appelle GET /logout (route Fortify) avec les cookies du profil, sans naviguer : pas de // « Quitter la page ? » ni d'écran de connexion visible. La session est détruite côté serveur // (ligne supprimée de la table sessions), puis tous les cookies du profil sont effacés. private async Task LogoutAsync() { CoreWebView2 core = AnyCore(); if (core == null) return; try { List cookies = await core.CookieManager.GetCookiesAsync(_startUri.AbsoluteUri); if (cookies.Count > 0) { StringBuilder header = new StringBuilder(); foreach (CoreWebView2Cookie c in cookies) { if (header.Length > 0) header.Append("; "); header.Append(c.Name).Append('=').Append(c.Value); } HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri(_startUri, "logout")); req.Method = "GET"; req.AllowAutoRedirect = false; req.Timeout = 5000; req.Headers[HttpRequestHeader.Cookie] = header.ToString(); Task call = req.GetResponseAsync(); if (await Task.WhenAny(call, Task.Delay(5000)) == call) using (WebResponse resp = await call) { } else req.Abort(); } } catch { } // serveur arrêté : les cookies sont tout de même effacés ci-dessous finally { core.CookieManager.DeleteAllCookies(); } } // ---------------------------------------------------------------- Clavier / plein écran // Focus hors de la page (barre d'onglets…). Focus dans la page : le contrôle WebView2 ne passe pas // par ProcessCmdKey mais lève KeyDown sur lui-même, d'où le branchement dans WireTab(). protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { return HandleShortcut(keyData) || base.ProcessCmdKey(ref msg, keyData); } private bool HandleShortcut(Keys keyData) { BrowserTab tab = _current; CoreWebView2 core = tab == null ? null : tab.View.CoreWebView2; if (core == null) return false; switch (keyData) { case Keys.Control | Keys.T: NewTab(); return true; case Keys.Control | Keys.W: case Keys.Control | Keys.F4: CloseTab(tab); return true; case Keys.Control | Keys.Tab: case Keys.Control | Keys.PageDown: SelectRelative(1); return true; case Keys.Control | Keys.Shift | Keys.Tab: case Keys.Control | Keys.PageUp: SelectRelative(-1); return true; case Keys.F5: // Après la page d'erreur, recharger la page qui a échoué plutôt que la page d'erreur. if (tab.RetryUri != null && (core.Source.StartsWith("data:", StringComparison.OrdinalIgnoreCase) || core.Source == "about:blank")) core.Navigate(tab.RetryUri); else core.Reload(); return true; case Keys.F11: SetFullscreen(!_fullscreen); return true; case Keys.F12: core.OpenDevToolsWindow(); return true; case Keys.Alt | Keys.Home: tab.View.Source = _startUri; return true; } return false; } private void SetFullscreen(bool on) { if (on == _fullscreen) return; _fullscreen = on; _strip.Visible = !on; if (on) { _stateBeforeFullscreen = WindowState; FormBorderStyle = FormBorderStyle.None; WindowState = FormWindowState.Normal; // nécessaire pour couvrir la barre des tâches WindowState = FormWindowState.Maximized; } else { FormBorderStyle = FormBorderStyle.Sizable; WindowState = _stateBeforeFullscreen; } } } // Barre d'onglets dessinée à la main : onglet actif en blanc avec un liseré vert, × pour fermer // (au survol ou sur l'onglet actif), + pour en ouvrir un. Clic molette = fermer, double-clic // sur le vide = nouvel onglet. internal sealed class TabStrip : Control { private static readonly Color BackColorStrip = Color.FromArgb(226, 230, 235); private static readonly Color HoverColor = Color.FromArgb(240, 242, 245); private static readonly Color ActiveColor = Color.White; private static readonly Color AccentColor = Color.FromArgb(122, 185, 41); private static readonly Color TextColor = Color.FromArgb(40, 44, 52); private static readonly Color MutedColor = Color.FromArgb(110, 116, 126); private static readonly Color LoadingColor = Color.FromArgb(240, 150, 30); private readonly MainForm _owner; private readonly ToolTip _tip = new ToolTip(); private int _hoverTab = -1; private bool _hoverClose; private bool _hoverPlus; private string _tipText; public TabStrip(MainForm owner) { _owner = owner; SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true); Font = new Font("Segoe UI", 9f); Height = S(36); } private int S(int px) { return (int)Math.Round(px * DeviceDpi / 96f); } private Rectangle TabRect(int i, int count) { int left = S(6), top = S(6), plus = S(36); int width = (Width - left - plus - S(8)) / Math.Max(count, 1); width = Math.Max(S(70), Math.Min(S(230), width)); return new Rectangle(left + i * width, top, width, Height - top); } private Rectangle CloseRect(Rectangle tab) { int size = S(18); return new Rectangle(tab.Right - size - S(8), tab.Top + (tab.Height - size) / 2, size, size); } private Rectangle PlusRect(int count) { Rectangle last = TabRect(count - 1, count); int size = S(26); return new Rectangle(last.Right + S(6), last.Top + (last.Height - size) / 2, size, size); } private bool ShowClose(int i, int count) { return count > 1 && (i == _hoverTab || _owner.Tabs[i] == _owner.Current); } protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; g.SmoothingMode = SmoothingMode.AntiAlias; g.Clear(BackColorStrip); IList tabs = _owner.Tabs; int n = tabs.Count; for (int i = 0; i < n; i++) { BrowserTab tab = tabs[i]; Rectangle r = TabRect(i, n); bool active = tab == _owner.Current; if (active || i == _hoverTab) { using (GraphicsPath path = TopRounded(r, S(7))) using (SolidBrush b = new SolidBrush(active ? ActiveColor : HoverColor)) g.FillPath(b, path); } if (active) { using (SolidBrush b = new SolidBrush(AccentColor)) g.FillRectangle(b, r.Left + S(7), r.Top, r.Width - S(14), S(2)); } else if (i + 1 < n && tabs[i + 1] != _owner.Current && i != _hoverTab && i + 1 != _hoverTab) { using (Pen p = new Pen(Color.FromArgb(200, 205, 212))) g.DrawLine(p, r.Right - 1, r.Top + S(8), r.Right - 1, r.Bottom - S(8)); } int textLeft = r.Left + S(12); if (tab.Loading) { int d = S(7); using (SolidBrush b = new SolidBrush(LoadingColor)) g.FillEllipse(b, textLeft, r.Top + (r.Height - d) / 2, d, d); textLeft += d + S(6); } bool close = ShowClose(i, n); int textRight = close ? CloseRect(r).Left - S(4) : r.Right - S(10); Rectangle textRect = new Rectangle(textLeft, r.Top, Math.Max(0, textRight - textLeft), r.Height); TextRenderer.DrawText(g, ShortTitle(tab.Title), Font, textRect, active ? TextColor : MutedColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Left | TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix | TextFormatFlags.SingleLine); if (close) { Rectangle c = CloseRect(r); if (i == _hoverTab && _hoverClose) using (SolidBrush b = new SolidBrush(Color.FromArgb(215, 219, 225))) g.FillEllipse(b, c); int m = S(5); using (Pen p = new Pen(MutedColor, Math.Max(1f, DeviceDpi / 96f * 1.3f))) { g.DrawLine(p, c.Left + m, c.Top + m, c.Right - m, c.Bottom - m); g.DrawLine(p, c.Right - m, c.Top + m, c.Left + m, c.Bottom - m); } } } if (n > 0) { Rectangle pr = PlusRect(n); if (_hoverPlus) using (SolidBrush b = new SolidBrush(HoverColor)) g.FillEllipse(b, pr); int m = S(8); using (Pen p = new Pen(MutedColor, Math.Max(1f, DeviceDpi / 96f * 1.5f))) { int cx = pr.Left + pr.Width / 2, cy = pr.Top + pr.Height / 2; g.DrawLine(p, pr.Left + m, cy, pr.Right - m, cy); g.DrawLine(p, cx, pr.Top + m, cx, pr.Bottom - m); } } } // « CLIENT - SMART CENTRAL » -> « CLIENT » : le nom de l'appli est déjà dans la barre de titre. private static string ShortTitle(string title) { const string suffix = " - SMART CENTRAL"; if (title.Length > suffix.Length && title.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)) return title.Substring(0, title.Length - suffix.Length); return title; } private static GraphicsPath TopRounded(Rectangle r, int radius) { int d = radius * 2; GraphicsPath path = new GraphicsPath(); path.AddArc(r.Left, r.Top, d, d, 180, 90); path.AddArc(r.Right - d, r.Top, d, d, 270, 90); path.AddLine(r.Right, r.Bottom, r.Left, r.Bottom); path.CloseFigure(); return path; } private int HitTab(Point p) { int n = _owner.Tabs.Count; for (int i = 0; i < n; i++) if (TabRect(i, n).Contains(p)) return i; return -1; } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); int n = _owner.Tabs.Count; int hover = HitTab(e.Location); bool hoverClose = hover >= 0 && n > 1 && CloseRect(TabRect(hover, n)).Contains(e.Location); bool hoverPlus = n > 0 && PlusRect(n).Contains(e.Location); if (hover != _hoverTab || hoverClose != _hoverClose || hoverPlus != _hoverPlus) { _hoverTab = hover; _hoverClose = hoverClose; _hoverPlus = hoverPlus; Invalidate(); } string tip = hoverPlus ? "Nouvel onglet (Ctrl+T)" : hoverClose ? "Fermer l'onglet (Ctrl+W)" : hover >= 0 ? _owner.Tabs[hover].Title : null; if (tip != _tipText) { _tipText = tip; _tip.SetToolTip(this, tip); } } protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); _hoverTab = -1; _hoverClose = _hoverPlus = false; Invalidate(); } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); int n = _owner.Tabs.Count; int i = HitTab(e.Location); if (e.Button == MouseButtons.Middle) { if (i >= 0) _owner.CloseTab(_owner.Tabs[i]); return; } if (e.Button != MouseButtons.Left) return; if (n > 0 && PlusRect(n).Contains(e.Location)) { _owner.NewTab(); return; } if (i < 0) return; BrowserTab tab = _owner.Tabs[i]; if (n > 1 && CloseRect(TabRect(i, n)).Contains(e.Location)) _owner.CloseTab(tab); else _owner.SelectTab(tab); } protected override void OnMouseDoubleClick(MouseEventArgs e) { base.OnMouseDoubleClick(e); int n = _owner.Tabs.Count; if (e.Button == MouseButtons.Left && HitTab(e.Location) < 0 && !(n > 0 && PlusRect(n).Contains(e.Location))) _owner.NewTab(); } } }