using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
namespace Luminary;
///
/// The whole app window: WebView2 filling the client area, the Luminary icon in
/// the title bar and taskbar, and an explicit message when the WebView2 runtime
/// is missing instead of a silent exit.
///
internal sealed class MainForm : Form
{
private const string RuntimeDownload = "https://go.microsoft.com/fwlink/p/?LinkId=2124703";
private readonly string _url;
private readonly WebView2 _web = new() { Dock = DockStyle.Fill };
public MainForm(string url)
{
_url = url;
Text = "Luminary";
Width = 1500;
Height = 950;
MinimumSize = new Size(900, 600);
StartPosition = FormStartPosition.CenterScreen;
Icon = LoadIcon();
Controls.Add(_web);
Load += async (_, _) => await InitializeAsync();
}
/// The exe carries the icon; extracting it avoids shipping a second file.
private static Icon? LoadIcon()
{
try
{
var exe = Environment.ProcessPath;
if (!string.IsNullOrEmpty(exe))
{
var icon = Icon.ExtractAssociatedIcon(exe);
if (icon != null) return icon;
}
}
catch
{
// A missing icon must never stop the window from opening.
}
return null;
}
private async Task InitializeAsync()
{
try
{
// Its own profile, next to the catalog, so the app never shares
// cookies or storage with the user's normal browsing. LUMINARY_DATA
// wins, the same precedence the server and launcher use.
var dataRoot = Environment.GetEnvironmentVariable("LUMINARY_DATA");
if (string.IsNullOrWhiteSpace(dataRoot))
{
dataRoot = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Luminary", "data");
}
var dataDir = Path.Combine(dataRoot, "webview2");
Directory.CreateDirectory(dataDir);
var environment = await CoreWebView2Environment.CreateAsync(null, dataDir);
await _web.EnsureCoreWebView2Async(environment);
var settings = _web.CoreWebView2.Settings;
settings.AreDevToolsEnabled = false;
settings.IsStatusBarEnabled = false;
settings.AreDefaultContextMenusEnabled = true;
_web.CoreWebView2.Navigate(_url);
}
catch (WebView2RuntimeNotFoundException)
{
Fail(
"The Microsoft Edge WebView2 runtime is missing.\n\n" +
"Install it from " + RuntimeDownload + " and start Luminary again.",
close: true);
}
catch (Exception error)
{
Fail("Luminary could not open its window.\n\n" + error.Message, close: true);
}
}
private void Fail(string message, bool close)
{
MessageBox.Show(this, message, "Luminary", MessageBoxButtons.OK, MessageBoxIcon.Error);
if (close) Close();
}
}