1
0
mirror of https://github.com/mattermost/focalboard.git synced 2025-01-02 14:47:55 +02:00

Update win-wpf app to persist user settings (issue #314)

This commit is contained in:
BaoNguyen 2023-10-28 07:59:06 +09:00
parent 134422df4d
commit 60b2e2a3be
11 changed files with 717 additions and 128 deletions

View File

@ -18,13 +18,19 @@ export function importNativeAppSettings(): void {
const importedKeys = importUserSettingsBlob(NativeApp.settingsBlob) const importedKeys = importUserSettingsBlob(NativeApp.settingsBlob)
const messageType = importedKeys.length ? 'didImportUserSettings' : 'didNotImportUserSettings' const messageType = importedKeys.length ? 'didImportUserSettings' : 'didNotImportUserSettings'
postWebKitMessage({type: messageType, settingsBlob: exportUserSettingsBlob(), keys: importedKeys}) postWebKitMessage({type: messageType, settingsBlob: exportUserSettingsBlob(), keys: importedKeys})
postWebViewMessage({type: messageType, settingsBlob: exportUserSettingsBlob(), keys: importedKeys})
NativeApp.settingsBlob = null NativeApp.settingsBlob = null
} }
export function notifySettingsChanged(key: string): void { export function notifySettingsChanged(key: string): void {
postWebKitMessage({type: 'didChangeUserSettings', settingsBlob: exportUserSettingsBlob(), key}) postWebKitMessage({type: 'didChangeUserSettings', settingsBlob: exportUserSettingsBlob(), key})
postWebViewMessage({type: 'didChangeUserSettings', settingsBlob: exportUserSettingsBlob(), key})
} }
function postWebKitMessage<T>(message: T) { function postWebKitMessage<T>(message: T) {
window.webkit?.messageHandlers.nativeApp?.postMessage(message) window.webkit?.messageHandlers.nativeApp?.postMessage(message)
} }
function postWebViewMessage<T>(message: T) {
window.chrome?.webview?.postMessage(message)
}

View File

@ -13,6 +13,7 @@ export interface IAppWindow extends Window {
openInNewBrowser?: ((href: string) => void) | null openInNewBrowser?: ((href: string) => void) | null
webkit?: {messageHandlers: {nativeApp?: {postMessage: <T>(message: T) => void}}} webkit?: {messageHandlers: {nativeApp?: {postMessage: <T>(message: T) => void}}}
openPricingModal?: () => (telemetry: TelemetryProps) => void openPricingModal?: () => (telemetry: TelemetryProps) => void
chrome?: {webview?: {postMessage: <T>(message: T) => void}}
} }
// SuiteWindow documents all custom properties // SuiteWindow documents all custom properties

484
win-wpf/.gitignore vendored
View File

@ -1,8 +1,482 @@
packages ## Ignore Visual Studio temporary files, build results, and
obj ## 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 msix
temp temp
dist dist
*.msix
*.suo
*.csproj.user

View File

@ -1,7 +1,7 @@
 
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16 # Visual Studio Version 17
VisualStudioVersion = 16.0.30907.101 VisualStudioVersion = 17.7.34221.43
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Focalboard", "Focalboard\Focalboard.csproj", "{7B3F5C74-96AC-4521-9268-28BF2D91FCF4}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Focalboard", "Focalboard\Focalboard.csproj", "{7B3F5C74-96AC-4521-9268-28BF2D91FCF4}"
EndProject EndProject

View File

@ -1,12 +1,12 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<configuration> <configuration>
<configSections> <configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="Focalboard.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false"/> <section name="Focalboard.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup> </sectionGroup>
</configSections> </configSections>
<startup> <startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup> </startup>
<userSettings> <userSettings>
<Focalboard.Properties.Settings> <Focalboard.Properties.Settings>
@ -19,6 +19,17 @@
<setting name="WindowMaximized" serializeAs="String"> <setting name="WindowMaximized" serializeAs="String">
<value>False</value> <value>False</value>
</setting> </setting>
<setting name="WebAppSettingsBlob" serializeAs="String">
<value />
</setting>
</Focalboard.Properties.Settings> </Focalboard.Properties.Settings>
</userSettings> </userSettings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration> </configuration>

View File

@ -16,6 +16,8 @@
<Deterministic>true</Deterministic> <Deterministic>true</Deterministic>
<NuGetPackageImportStamp> <NuGetPackageImportStamp>
</NuGetPackageImportStamp> </NuGetPackageImportStamp>
<IsWebBootstrapper>false</IsWebBootstrapper>
<TargetFrameworkProfile />
<PublishUrl>publish\</PublishUrl> <PublishUrl>publish\</PublishUrl>
<Install>true</Install> <Install>true</Install>
<InstallFrom>Disk</InstallFrom> <InstallFrom>Disk</InstallFrom>
@ -28,10 +30,8 @@
<MapFileExtensions>true</MapFileExtensions> <MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision> <ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion> <ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust> <UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled> <BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkProfile />
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
@ -79,6 +79,9 @@
<ApplicationIcon>focalboard.ico</ApplicationIcon> <ApplicationIcon>focalboard.ico</ApplicationIcon>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="Microsoft.Bcl.AsyncInterfaces, Version=7.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Bcl.AsyncInterfaces.7.0.0\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Web.WebView2.Core, Version=1.0.705.50, Culture=neutral, PublicKeyToken=2a8ab48044d2601e, processorArchitecture=MSIL"> <Reference Include="Microsoft.Web.WebView2.Core, Version=1.0.705.50, Culture=neutral, PublicKeyToken=2a8ab48044d2601e, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Web.WebView2.1.0.705.50\lib\net45\Microsoft.Web.WebView2.Core.dll</HintPath> <HintPath>..\packages\Microsoft.Web.WebView2.1.0.705.50\lib\net45\Microsoft.Web.WebView2.Core.dll</HintPath>
</Reference> </Reference>
@ -89,13 +92,38 @@
<HintPath>..\packages\Microsoft.Web.WebView2.1.0.705.50\lib\net45\Microsoft.Web.WebView2.Wpf.dll</HintPath> <HintPath>..\packages\Microsoft.Web.WebView2.1.0.705.50\lib\net45\Microsoft.Web.WebView2.Wpf.dll</HintPath>
</Reference> </Reference>
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.Data" /> <Reference Include="System.Data" />
<Reference Include="System.Drawing" /> <Reference Include="System.Drawing" />
<Reference Include="System.Memory, Version=4.0.1.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Memory.4.5.5\lib\net461\System.Memory.dll</HintPath>
</Reference>
<Reference Include="System.Numerics" />
<Reference Include="System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.WindowsRuntime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL"> <Reference Include="System.Runtime.WindowsRuntime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion> <SpecificVersion>False</SpecificVersion>
<HintPath>$(MSBuildProgramFiles32)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll</HintPath> <HintPath>$(MSBuildProgramFiles32)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll</HintPath>
<Private>False</Private> <Private>False</Private>
</Reference> </Reference>
<Reference Include="System.Text.Encodings.Web, Version=7.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Text.Encodings.Web.7.0.0\lib\net462\System.Text.Encodings.Web.dll</HintPath>
</Reference>
<Reference Include="System.Text.Json, Version=7.0.0.3, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Text.Json.7.0.3\lib\net462\System.Text.Json.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks.Extensions, Version=4.2.0.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.ValueTuple.4.5.0\lib\net47\System.ValueTuple.dll</HintPath>
</Reference>
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
<Reference Include="Microsoft.CSharp" /> <Reference Include="Microsoft.CSharp" />
<Reference Include="System.Core" /> <Reference Include="System.Core" />
@ -119,6 +147,7 @@
<SubType>Designer</SubType> <SubType>Designer</SubType>
</ApplicationDefinition> </ApplicationDefinition>
<Compile Include="Utils.cs" /> <Compile Include="Utils.cs" />
<Compile Include="WebMessage.cs" />
<Compile Include="Webview2Installer.cs" /> <Compile Include="Webview2Installer.cs" />
<Page Include="MainWindow.xaml"> <Page Include="MainWindow.xaml">
<Generator>MSBuild:Compile</Generator> <Generator>MSBuild:Compile</Generator>

View File

@ -3,151 +3,182 @@
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Text.Json;
using System.Windows; using System.Windows;
using System.Windows.Input; using System.Windows.Input;
using Microsoft.Web.WebView2.Core; using Microsoft.Web.WebView2.Core;
namespace Focalboard { namespace Focalboard {
/// <summary> /// <summary>
/// Interaction logic for MainWindow.xaml /// Interaction logic for MainWindow.xaml
/// </summary> /// </summary>
public partial class MainWindow : Window { public partial class MainWindow : Window {
private int port { private int port {
get { return ((App)Application.Current).port; } get { return ((App)Application.Current).port; }
} }
private string sessionToken { private string sessionToken {
get { return ((App)Application.Current).sessionToken; } get { return ((App)Application.Current).sessionToken; }
} }
public MainWindow() { public MainWindow() {
Debug.WriteLine($"MainWindow()"); Debug.WriteLine($"MainWindow()");
InitializeComponent(); InitializeComponent();
RestoreWindowsState(); RestoreWindowsState();
this.Loaded += MainWindow_Loaded; this.Loaded += MainWindow_Loaded;
this.Closing += MainWindow_Closing; this.Closing += MainWindow_Closing;
webView.WebMessageReceived += WebView_WebMessageReceived;
InitializeWebView(); InitializeWebView();
} }
private void MainWindow_Loaded(object sender, RoutedEventArgs e) { private void WebView_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e) {
Activate(); var message = e.WebMessageAsJson;
} SaveWebAppSettingsBlob(message);
}
private void PromptToInstallWebview2() { private static void SaveWebAppSettingsBlob(string message) {
var dialogResult = MessageBox.Show( WebMessage webMessage;
"Focalboard requires the WebView2 runtime to be downloaded and installed. Install now?", try {
"Focalboard", webMessage = JsonSerializer.Deserialize<WebMessage>(message);
MessageBoxButton.YesNo, } catch (Exception) {
MessageBoxImage.Information, return;
MessageBoxResult.OK, }
MessageBoxOptions.DefaultDesktopOnly); 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) { private void MainWindow_Loaded(object sender, RoutedEventArgs e) {
installingLabel.Visibility = Visibility.Visible; Activate();
webView.Visibility = Visibility.Collapsed; }
var installer = new Webview2Installer(); private void PromptToInstallWebview2() {
installer.InstallProgress += Installer_InstallProgress; var dialogResult = MessageBox.Show(
installer.InstallCompleted += Installer_InstallCompleted; "Focalboard requires the WebView2 runtime to be downloaded and installed. Install now?",
installer.DownloadAndInstall(); "Focalboard",
} MessageBoxButton.YesNo,
} MessageBoxImage.Information,
MessageBoxResult.OK,
MessageBoxOptions.DefaultDesktopOnly);
private void Installer_InstallProgress(Webview2Installer sender, EventArgs e) { if (dialogResult == MessageBoxResult.Yes) {
Application.Current.Dispatcher.Invoke(() => { installingLabel.Visibility = Visibility.Visible;
if (sender.downloadProgress < 100) { webView.Visibility = Visibility.Collapsed;
installingLabel.Content = $"Downloading Webview2: {sender.downloadProgress}%";
} else {
installingLabel.Content = "Installing Webview2...";
}
});
}
private void Installer_InstallCompleted(Webview2Installer sender, EventArgs e) { var installer = new Webview2Installer();
Application.Current.Dispatcher.Invoke(() => { installer.InstallProgress += Installer_InstallProgress;
installingLabel.Content = "Webview2 install completed"; installer.InstallCompleted += Installer_InstallCompleted;
Activate(); installer.DownloadAndInstall();
}
}
if (sender.exitCode != 0) { private void Installer_InstallProgress(Webview2Installer sender, EventArgs e) {
var message = $"Webview2 install FAILED with code {sender.exitCode}. Try again."; Application.Current.Dispatcher.Invoke(() => {
MessageBox.Show(message, "Install failed"); if (sender.downloadProgress < 100) {
} installingLabel.Content = $"Downloading Webview2: {sender.downloadProgress}%";
} else {
installingLabel.Content = "Installing Webview2...";
}
});
}
// Reopen window private void Installer_InstallCompleted(Webview2Installer sender, EventArgs e) {
var window = new MainWindow(); Application.Current.Dispatcher.Invoke(() => {
window.Show(); installingLabel.Content = "Webview2 install completed";
Close(); Activate();
});
}
private void SaveWindowState() { if (sender.exitCode != 0) {
try { var message = $"Webview2 install FAILED with code {sender.exitCode}. Try again.";
Properties.Settings.Default.WindowPosition = new System.Drawing.Point( MessageBox.Show(message, "Install failed");
Convert.ToInt32(RestoreBounds.Location.X), }
Convert.ToInt32(RestoreBounds.Location.Y));
Properties.Settings.Default.WindowSize = new System.Drawing.Size( // Reopen window
Convert.ToInt32(RestoreBounds.Size.Width), var window = new MainWindow();
Convert.ToInt32(RestoreBounds.Size.Height)); window.Show();
Close();
});
}
Properties.Settings.Default.WindowMaximized = (WindowState == WindowState.Maximized); private void SaveWindowState() {
Properties.Settings.Default.Save(); try {
} catch { Properties.Settings.Default.WindowPosition = new System.Drawing.Point(
// Ignore errors, e.g. overflow Convert.ToInt32(RestoreBounds.Location.X),
} Convert.ToInt32(RestoreBounds.Location.Y));
}
private void RestoreWindowsState() { Properties.Settings.Default.WindowSize = new System.Drawing.Size(
this.Left = Properties.Settings.Default.WindowPosition.X; Convert.ToInt32(RestoreBounds.Size.Width),
this.Top = Properties.Settings.Default.WindowPosition.Y; Convert.ToInt32(RestoreBounds.Size.Height));
this.Width = Math.Max(300, Properties.Settings.Default.WindowSize.Width);
this.Height = Math.Max(200, Properties.Settings.Default.WindowSize.Height);
if (Properties.Settings.Default.WindowMaximized) { Properties.Settings.Default.WindowMaximized = (WindowState == WindowState.Maximized);
WindowState = WindowState.Maximized; Properties.Settings.Default.Save();
} } catch {
} // Ignore errors, e.g. overflow
}
}
private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) { private void RestoreWindowsState() {
SaveWindowState(); 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() { if (Properties.Settings.Default.WindowMaximized) {
string version = GetWebView2Version(); WindowState = WindowState.Maximized;
var isAltKeyPressed = (Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt)); }
if (version == "" || isAltKeyPressed) { }
PromptToInstallWebview2();
return;
}
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 async void InitializeWebView() {
var env = await CoreWebView2Environment.CreateAsync( string version = GetWebView2Version();
userDataFolder: Path.Combine(Path.GetTempPath(), "Focalboard") var isAltKeyPressed = (Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt));
); if (version == "" || isAltKeyPressed) {
await webView.EnsureCoreWebView2Async(env); PromptToInstallWebview2();
return;
}
webView.ContentLoading += WebView_ContentLoading; this.Title = $"Focalboard (port {port} WebView {version})";
var url = String.Format("http://localhost:{0}", port); // must create a data folder if running out of a secured folder that can't write like Program Files
webView.Source = new Uri(url); var env = await CoreWebView2Environment.CreateAsync(
} userDataFolder: Path.Combine(Path.GetTempPath(), "Focalboard")
);
await webView.EnsureCoreWebView2Async(env);
private static string GetWebView2Version() { webView.ContentLoading += WebView_ContentLoading;
try {
return CoreWebView2Environment.GetAvailableBrowserVersionString();
} catch (Exception) { return ""; }
}
private void WebView_ContentLoading(object sender, CoreWebView2ContentLoadingEventArgs e) { var url = String.Format("http://localhost:{0}", port);
// Set focalboardSessionId webView.Source = new Uri(url);
string script = $"localStorage.setItem('focalboardSessionId', '{sessionToken}');"; }
webView.ExecuteScriptAsync(script);
} 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);
}
}
} }

View File

@ -12,7 +12,7 @@ namespace Focalboard.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [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 { internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
@ -58,5 +58,17 @@ namespace Focalboard.Properties {
this["WindowMaximized"] = value; 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;
}
}
} }
} }

View File

@ -11,5 +11,8 @@
<Setting Name="WindowMaximized" Type="System.Boolean" Scope="User"> <Setting Name="WindowMaximized" Type="System.Boolean" Scope="User">
<Value Profile="(Default)">False</Value> <Value Profile="(Default)">False</Value>
</Setting> </Setting>
<Setting Name="WebAppSettingsBlob" Type="System.String" Scope="User">
<Value Profile="(Default)" />
</Setting>
</Settings> </Settings>
</SettingsFile> </SettingsFile>

View File

@ -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; }
}
}

View File

@ -1,4 +1,13 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="Microsoft.Bcl.AsyncInterfaces" version="7.0.0" targetFramework="net48" />
<package id="Microsoft.Web.WebView2" version="1.0.705.50" targetFramework="net472" /> <package id="Microsoft.Web.WebView2" version="1.0.705.50" targetFramework="net472" />
<package id="System.Buffers" version="4.5.1" targetFramework="net48" />
<package id="System.Memory" version="4.5.5" targetFramework="net48" />
<package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net48" />
<package id="System.Runtime.CompilerServices.Unsafe" version="6.0.0" targetFramework="net48" />
<package id="System.Text.Encodings.Web" version="7.0.0" targetFramework="net48" />
<package id="System.Text.Json" version="7.0.3" targetFramework="net48" />
<package id="System.Threading.Tasks.Extensions" version="4.5.4" targetFramework="net48" />
<package id="System.ValueTuple" version="4.5.0" targetFramework="net48" />
</packages> </packages>