From 60b2e2a3bef777c9b6559b2f4967ea7464d57373 Mon Sep 17 00:00:00 2001 From: BaoNguyen Date: Sat, 28 Oct 2023 07:59:06 +0900 Subject: [PATCH] Update win-wpf app to persist user settings (issue #314) --- webapp/src/nativeApp.ts | 6 + webapp/src/types/index.d.ts | 1 + win-wpf/.gitignore | 484 +++++++++++++++++- win-wpf/Focalboard.sln | 4 +- win-wpf/Focalboard/App.config | 17 +- win-wpf/Focalboard/Focalboard.csproj | 33 +- win-wpf/Focalboard/MainWindow.xaml.cs | 261 +++++----- .../Properties/Settings.Designer.cs | 14 +- .../Focalboard/Properties/Settings.settings | 3 + win-wpf/Focalboard/WebMessage.cs | 13 + win-wpf/Focalboard/packages.config | 9 + 11 files changed, 717 insertions(+), 128 deletions(-) create mode 100644 win-wpf/Focalboard/WebMessage.cs diff --git a/webapp/src/nativeApp.ts b/webapp/src/nativeApp.ts index 354412851..d071b910d 100644 --- a/webapp/src/nativeApp.ts +++ b/webapp/src/nativeApp.ts @@ -18,13 +18,19 @@ export function importNativeAppSettings(): void { const importedKeys = importUserSettingsBlob(NativeApp.settingsBlob) const messageType = importedKeys.length ? 'didImportUserSettings' : 'didNotImportUserSettings' postWebKitMessage({type: messageType, settingsBlob: exportUserSettingsBlob(), keys: importedKeys}) + postWebViewMessage({type: messageType, settingsBlob: exportUserSettingsBlob(), keys: importedKeys}) NativeApp.settingsBlob = null } export function notifySettingsChanged(key: string): void { postWebKitMessage({type: 'didChangeUserSettings', settingsBlob: exportUserSettingsBlob(), key}) + postWebViewMessage({type: 'didChangeUserSettings', settingsBlob: exportUserSettingsBlob(), key}) } function postWebKitMessage(message: T) { window.webkit?.messageHandlers.nativeApp?.postMessage(message) } + +function postWebViewMessage(message: T) { + window.chrome?.webview?.postMessage(message) +} diff --git a/webapp/src/types/index.d.ts b/webapp/src/types/index.d.ts index a30f46e4c..0434ff73d 100644 --- a/webapp/src/types/index.d.ts +++ b/webapp/src/types/index.d.ts @@ -13,6 +13,7 @@ export interface IAppWindow extends Window { openInNewBrowser?: ((href: string) => void) | null webkit?: {messageHandlers: {nativeApp?: {postMessage: (message: T) => void}}} openPricingModal?: () => (telemetry: TelemetryProps) => void + chrome?: {webview?: {postMessage: (message: T) => void}} } // SuiteWindow documents all custom properties diff --git a/win-wpf/.gitignore b/win-wpf/.gitignore index c491e5093..d587254d1 100644 --- a/win-wpf/.gitignore +++ b/win-wpf/.gitignore @@ -1,8 +1,482 @@ -packages -obj +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Focalboard defaults msix temp dist -*.msix -*.suo -*.csproj.user diff --git a/win-wpf/Focalboard.sln b/win-wpf/Focalboard.sln index 58bc104e1..b93be94ce 100644 --- a/win-wpf/Focalboard.sln +++ b/win-wpf/Focalboard.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.30907.101 +# Visual Studio Version 17 +VisualStudioVersion = 17.7.34221.43 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Focalboard", "Focalboard\Focalboard.csproj", "{7B3F5C74-96AC-4521-9268-28BF2D91FCF4}" EndProject diff --git a/win-wpf/Focalboard/App.config b/win-wpf/Focalboard/App.config index c1fb6c757..3dc842e3a 100644 --- a/win-wpf/Focalboard/App.config +++ b/win-wpf/Focalboard/App.config @@ -1,12 +1,12 @@ - + -
+
- + @@ -19,6 +19,17 @@ False + + + + + + + + + + + diff --git a/win-wpf/Focalboard/Focalboard.csproj b/win-wpf/Focalboard/Focalboard.csproj index 56f2f9e47..ce225d300 100644 --- a/win-wpf/Focalboard/Focalboard.csproj +++ b/win-wpf/Focalboard/Focalboard.csproj @@ -16,6 +16,8 @@ true + false + publish\ true Disk @@ -28,10 +30,8 @@ true 0 1.0.0.%2a - false false true - AnyCPU @@ -79,6 +79,9 @@ focalboard.ico + + ..\packages\Microsoft.Bcl.AsyncInterfaces.7.0.0\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll + ..\packages\Microsoft.Web.WebView2.1.0.705.50\lib\net45\Microsoft.Web.WebView2.Core.dll @@ -89,13 +92,38 @@ ..\packages\Microsoft.Web.WebView2.1.0.705.50\lib\net45\Microsoft.Web.WebView2.Wpf.dll + + ..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll + + + ..\packages\System.Memory.4.5.5\lib\net461\System.Memory.dll + + + + ..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + False $(MSBuildProgramFiles32)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll False + + ..\packages\System.Text.Encodings.Web.7.0.0\lib\net462\System.Text.Encodings.Web.dll + + + ..\packages\System.Text.Json.7.0.3\lib\net462\System.Text.Json.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + + ..\packages\System.ValueTuple.4.5.0\lib\net47\System.ValueTuple.dll + @@ -119,6 +147,7 @@ Designer + MSBuild:Compile diff --git a/win-wpf/Focalboard/MainWindow.xaml.cs b/win-wpf/Focalboard/MainWindow.xaml.cs index cd3e4f158..19d473576 100644 --- a/win-wpf/Focalboard/MainWindow.xaml.cs +++ b/win-wpf/Focalboard/MainWindow.xaml.cs @@ -3,151 +3,182 @@ using System; using System.Diagnostics; using System.IO; +using System.Text.Json; using System.Windows; using System.Windows.Input; using Microsoft.Web.WebView2.Core; namespace Focalboard { - /// - /// Interaction logic for MainWindow.xaml - /// - public partial class MainWindow : Window { - private int port { - get { return ((App)Application.Current).port; } - } + /// + /// Interaction logic for MainWindow.xaml + /// + public partial class MainWindow : Window { + private int port { + get { return ((App)Application.Current).port; } + } - private string sessionToken { - get { return ((App)Application.Current).sessionToken; } - } + private string sessionToken { + get { return ((App)Application.Current).sessionToken; } + } - public MainWindow() { - Debug.WriteLine($"MainWindow()"); + public MainWindow() { + Debug.WriteLine($"MainWindow()"); - InitializeComponent(); + InitializeComponent(); - RestoreWindowsState(); + RestoreWindowsState(); - this.Loaded += MainWindow_Loaded; - this.Closing += MainWindow_Closing; + this.Loaded += MainWindow_Loaded; + this.Closing += MainWindow_Closing; + webView.WebMessageReceived += WebView_WebMessageReceived; - InitializeWebView(); - } + InitializeWebView(); + } - private void MainWindow_Loaded(object sender, RoutedEventArgs e) { - Activate(); - } + private void WebView_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e) { + var message = e.WebMessageAsJson; + SaveWebAppSettingsBlob(message); + } - private void PromptToInstallWebview2() { - var dialogResult = MessageBox.Show( - "Focalboard requires the WebView2 runtime to be downloaded and installed. Install now?", - "Focalboard", - MessageBoxButton.YesNo, - MessageBoxImage.Information, - MessageBoxResult.OK, - MessageBoxOptions.DefaultDesktopOnly); + private static void SaveWebAppSettingsBlob(string message) { + WebMessage webMessage; + try { + webMessage = JsonSerializer.Deserialize(message); + } catch (Exception) { + return; + } + switch (webMessage.type) { + case "didChangeUserSettings": + Properties.Settings.Default.WebAppSettingsBlob = webMessage.settingsBlob; + Properties.Settings.Default.Save(); + break; + case "didImportUserSettings": + case "didNotImportUserSettings": + default: + break; + } + } - if (dialogResult == MessageBoxResult.Yes) { - installingLabel.Visibility = Visibility.Visible; - webView.Visibility = Visibility.Collapsed; + private void MainWindow_Loaded(object sender, RoutedEventArgs e) { + Activate(); + } - var installer = new Webview2Installer(); - installer.InstallProgress += Installer_InstallProgress; - installer.InstallCompleted += Installer_InstallCompleted; - installer.DownloadAndInstall(); - } - } + private void PromptToInstallWebview2() { + var dialogResult = MessageBox.Show( + "Focalboard requires the WebView2 runtime to be downloaded and installed. Install now?", + "Focalboard", + MessageBoxButton.YesNo, + MessageBoxImage.Information, + MessageBoxResult.OK, + MessageBoxOptions.DefaultDesktopOnly); - private void Installer_InstallProgress(Webview2Installer sender, EventArgs e) { - Application.Current.Dispatcher.Invoke(() => { - if (sender.downloadProgress < 100) { - installingLabel.Content = $"Downloading Webview2: {sender.downloadProgress}%"; - } else { - installingLabel.Content = "Installing Webview2..."; - } - }); - } + if (dialogResult == MessageBoxResult.Yes) { + installingLabel.Visibility = Visibility.Visible; + webView.Visibility = Visibility.Collapsed; - private void Installer_InstallCompleted(Webview2Installer sender, EventArgs e) { - Application.Current.Dispatcher.Invoke(() => { - installingLabel.Content = "Webview2 install completed"; - Activate(); + var installer = new Webview2Installer(); + installer.InstallProgress += Installer_InstallProgress; + installer.InstallCompleted += Installer_InstallCompleted; + installer.DownloadAndInstall(); + } + } - if (sender.exitCode != 0) { - var message = $"Webview2 install FAILED with code {sender.exitCode}. Try again."; - MessageBox.Show(message, "Install failed"); - } + private void Installer_InstallProgress(Webview2Installer sender, EventArgs e) { + Application.Current.Dispatcher.Invoke(() => { + if (sender.downloadProgress < 100) { + installingLabel.Content = $"Downloading Webview2: {sender.downloadProgress}%"; + } else { + installingLabel.Content = "Installing Webview2..."; + } + }); + } - // Reopen window - var window = new MainWindow(); - window.Show(); - Close(); - }); - } + private void Installer_InstallCompleted(Webview2Installer sender, EventArgs e) { + Application.Current.Dispatcher.Invoke(() => { + installingLabel.Content = "Webview2 install completed"; + Activate(); - private void SaveWindowState() { - try { - Properties.Settings.Default.WindowPosition = new System.Drawing.Point( - Convert.ToInt32(RestoreBounds.Location.X), - Convert.ToInt32(RestoreBounds.Location.Y)); + if (sender.exitCode != 0) { + var message = $"Webview2 install FAILED with code {sender.exitCode}. Try again."; + MessageBox.Show(message, "Install failed"); + } - Properties.Settings.Default.WindowSize = new System.Drawing.Size( - Convert.ToInt32(RestoreBounds.Size.Width), - Convert.ToInt32(RestoreBounds.Size.Height)); + // Reopen window + var window = new MainWindow(); + window.Show(); + Close(); + }); + } - Properties.Settings.Default.WindowMaximized = (WindowState == WindowState.Maximized); - Properties.Settings.Default.Save(); - } catch { - // Ignore errors, e.g. overflow - } - } + private void SaveWindowState() { + try { + Properties.Settings.Default.WindowPosition = new System.Drawing.Point( + Convert.ToInt32(RestoreBounds.Location.X), + Convert.ToInt32(RestoreBounds.Location.Y)); - private void RestoreWindowsState() { - this.Left = Properties.Settings.Default.WindowPosition.X; - this.Top = Properties.Settings.Default.WindowPosition.Y; - this.Width = Math.Max(300, Properties.Settings.Default.WindowSize.Width); - this.Height = Math.Max(200, Properties.Settings.Default.WindowSize.Height); + Properties.Settings.Default.WindowSize = new System.Drawing.Size( + Convert.ToInt32(RestoreBounds.Size.Width), + Convert.ToInt32(RestoreBounds.Size.Height)); - if (Properties.Settings.Default.WindowMaximized) { - WindowState = WindowState.Maximized; - } - } + Properties.Settings.Default.WindowMaximized = (WindowState == WindowState.Maximized); + Properties.Settings.Default.Save(); + } catch { + // Ignore errors, e.g. overflow + } + } - private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) { - SaveWindowState(); - } + private void RestoreWindowsState() { + this.Left = Properties.Settings.Default.WindowPosition.X; + this.Top = Properties.Settings.Default.WindowPosition.Y; + this.Width = Math.Max(300, Properties.Settings.Default.WindowSize.Width); + this.Height = Math.Max(200, Properties.Settings.Default.WindowSize.Height); - async void InitializeWebView() { - string version = GetWebView2Version(); - var isAltKeyPressed = (Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt)); - if (version == "" || isAltKeyPressed) { - PromptToInstallWebview2(); - return; - } + if (Properties.Settings.Default.WindowMaximized) { + WindowState = WindowState.Maximized; + } + } - this.Title = $"Focalboard (port {port} WebView {version})"; + private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) { + SaveWindowState(); + } - // must create a data folder if running out of a secured folder that can't write like Program Files - var env = await CoreWebView2Environment.CreateAsync( - userDataFolder: Path.Combine(Path.GetTempPath(), "Focalboard") - ); - await webView.EnsureCoreWebView2Async(env); + async void InitializeWebView() { + string version = GetWebView2Version(); + var isAltKeyPressed = (Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt)); + if (version == "" || isAltKeyPressed) { + PromptToInstallWebview2(); + return; + } - webView.ContentLoading += WebView_ContentLoading; + this.Title = $"Focalboard (port {port} WebView {version})"; - var url = String.Format("http://localhost:{0}", port); - webView.Source = new Uri(url); - } + // must create a data folder if running out of a secured folder that can't write like Program Files + var env = await CoreWebView2Environment.CreateAsync( + userDataFolder: Path.Combine(Path.GetTempPath(), "Focalboard") + ); + await webView.EnsureCoreWebView2Async(env); - private static string GetWebView2Version() { - try { - return CoreWebView2Environment.GetAvailableBrowserVersionString(); - } catch (Exception) { return ""; } - } + webView.ContentLoading += WebView_ContentLoading; - private void WebView_ContentLoading(object sender, CoreWebView2ContentLoadingEventArgs e) { - // Set focalboardSessionId - string script = $"localStorage.setItem('focalboardSessionId', '{sessionToken}');"; - webView.ExecuteScriptAsync(script); - } - } + var url = String.Format("http://localhost:{0}", port); + webView.Source = new Uri(url); + } + + private static string GetWebView2Version() { + try { + return CoreWebView2Environment.GetAvailableBrowserVersionString(); + } catch (Exception) { return ""; } + } + + private void WebView_ContentLoading(object sender, CoreWebView2ContentLoadingEventArgs e) { + // Set focalboardSessionId + string script = $"localStorage.setItem('focalboardSessionId', '{sessionToken}');"; + webView.ExecuteScriptAsync(script); + + // Set settings blob + string settingsBlob = Properties.Settings.Default.WebAppSettingsBlob; + script = $"const NativeApp = {{ settingsBlob: \"{settingsBlob}\" }}"; + webView.ExecuteScriptAsync(script); + } + } } diff --git a/win-wpf/Focalboard/Properties/Settings.Designer.cs b/win-wpf/Focalboard/Properties/Settings.Designer.cs index 96e863c80..6a16cfa9a 100644 --- a/win-wpf/Focalboard/Properties/Settings.Designer.cs +++ b/win-wpf/Focalboard/Properties/Settings.Designer.cs @@ -12,7 +12,7 @@ namespace Focalboard.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.8.1.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.7.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); @@ -58,5 +58,17 @@ namespace Focalboard.Properties { this["WindowMaximized"] = value; } } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("")] + public string WebAppSettingsBlob { + get { + return ((string)(this["WebAppSettingsBlob"])); + } + set { + this["WebAppSettingsBlob"] = value; + } + } } } diff --git a/win-wpf/Focalboard/Properties/Settings.settings b/win-wpf/Focalboard/Properties/Settings.settings index 3ae816362..4c2d3a079 100644 --- a/win-wpf/Focalboard/Properties/Settings.settings +++ b/win-wpf/Focalboard/Properties/Settings.settings @@ -11,5 +11,8 @@ False + + + \ No newline at end of file diff --git a/win-wpf/Focalboard/WebMessage.cs b/win-wpf/Focalboard/WebMessage.cs new file mode 100644 index 000000000..b17222255 --- /dev/null +++ b/win-wpf/Focalboard/WebMessage.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Focalboard { + internal class WebMessage { + public string type { get; set; } + public string settingsBlob { get; set; } + public string key { get; set; } + } +} diff --git a/win-wpf/Focalboard/packages.config b/win-wpf/Focalboard/packages.config index 84941d6ba..c91cbcaa0 100644 --- a/win-wpf/Focalboard/packages.config +++ b/win-wpf/Focalboard/packages.config @@ -1,4 +1,13 @@  + + + + + + + + + \ No newline at end of file