Initial integration.

This commit is contained in:
Burak Kaan Köse
2025-12-26 20:46:48 +01:00
parent 10b85ea135
commit 014b5aa671
79 changed files with 4694 additions and 432 deletions
File diff suppressed because one or more lines are too long
@@ -0,0 +1,439 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.WinUI.Controls;
using EmailValidation;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media.Animation;
using Microsoft.UI.Xaml.Navigation;
using MimeKit;
using Windows.ApplicationModel.DataTransfer;
using Windows.Foundation;
using Windows.Storage;
using Windows.UI.Core.Preview;
using Wino.Core.Domain;
using Wino.Core.Domain.Entities.Shared;
using Wino.Core.Domain.Models.Reader;
using Wino.Mail.ViewModels.Data;
using Wino.Mail.WinUI.Extensions;
using Wino.Messaging.Client.Mails;
using Wino.Messaging.Client.Shell;
using Wino.Views.Abstract;
namespace Wino.Views.Mail;
public sealed partial class ComposePage : ComposePageAbstract,
IRecipient<CreateNewComposeMailRequested>,
IRecipient<ApplicationThemeChanged>
{
public WebView2 GetWebView() => WebViewEditor.GetUnderlyingWebView();
private readonly List<IDisposable> _disposables = [];
public ComposePage()
{
InitializeComponent();
}
private async void GlobalFocusManagerGotFocus(object? sender, FocusManagerGotFocusEventArgs e)
{
// In order to delegate cursor to the inner editor for WebView2.
// When the control got focus, we invoke script to focus the editor.
// This is not done on the WebView2 handlers, because somehow it is
// repeatedly focusing itself, even though when it has the focus already.
if (e.NewFocusedElement == WebViewEditor)
{
await WebViewEditor.FocusEditorAsync(true);
}
}
private IDisposable GetSuggestionBoxDisposable(TokenizingTextBox box)
{
return Observable.FromEventPattern<TypedEventHandler<AutoSuggestBox, AutoSuggestBoxTextChangedEventArgs>, AutoSuggestBoxTextChangedEventArgs>(
x => box.TextChanged += x,
x => box.TextChanged -= x)
.Throttle(TimeSpan.FromMilliseconds(120))
.ObserveOn(SynchronizationContext.Current!)
.Subscribe(t =>
{
if (t.EventArgs.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
{
if (t.Sender is AutoSuggestBox senderBox && senderBox.Text.Length >= 2)
{
_ = ViewModel.ContactService.GetAddressInformationAsync(senderBox.Text).ContinueWith(x =>
{
_ = ViewModel.ExecuteUIThread(() =>
{
var addresses = x.Result;
senderBox.ItemsSource = addresses;
});
});
}
}
});
}
private void OnComposeGridDragOver(object sender, DragEventArgs e)
{
ViewModel.IsDraggingOverComposerGrid = true;
}
private void OnComposeGridDragLeave(object sender, DragEventArgs e)
{
ViewModel.IsDraggingOverComposerGrid = false;
}
private void OnFileDropGridDragOver(object sender, DragEventArgs e)
{
ViewModel.IsDraggingOverFilesDropZone = true;
e.AcceptedOperation = DataPackageOperation.Copy;
e.DragUIOverride.Caption = Translator.ComposerAttachmentsDragDropAttach_Message;
e.DragUIOverride.IsCaptionVisible = true;
e.DragUIOverride.IsGlyphVisible = true;
e.DragUIOverride.IsContentVisible = true;
}
private void OnFileDropGridDragLeave(object sender, DragEventArgs e)
{
ViewModel.IsDraggingOverFilesDropZone = false;
}
private async void OnFileDropGridFileDropped(object sender, DragEventArgs e)
{
try
{
if (e.DataView.Contains(StandardDataFormats.StorageItems))
{
var storageItems = await e.DataView.GetStorageItemsAsync();
var files = storageItems.OfType<StorageFile>();
await AttachFiles(files);
}
}
// State should be reset even when an exception occurs, otherwise the UI will be stuck in a dragging state.
finally
{
ViewModel.IsDraggingOverComposerGrid = false;
ViewModel.IsDraggingOverFilesDropZone = false;
}
}
private void OnImageDropGridDragEnter(object sender, DragEventArgs e)
{
bool isValid = false;
if (e.DataView.Contains(StandardDataFormats.StorageItems))
{
// We can't use async/await here because DragUIOverride becomes inaccessible.
// https://github.com/microsoft/microsoft-ui-xaml/issues/9296
var files = e.DataView.GetStorageItemsAsync().GetAwaiter().GetResult().OfType<StorageFile>();
foreach (var file in files)
{
if (IsValidImageFile(file))
{
isValid = true;
}
}
}
e.AcceptedOperation = isValid ? DataPackageOperation.Copy : DataPackageOperation.None;
if (isValid)
{
ViewModel.IsDraggingOverImagesDropZone = true;
e.DragUIOverride.Caption = Translator.ComposerAttachmentsDragDropAttach_Message;
e.DragUIOverride.IsCaptionVisible = true;
e.DragUIOverride.IsGlyphVisible = true;
e.DragUIOverride.IsContentVisible = true;
}
}
private void OnImageDropGridDragLeave(object sender, DragEventArgs e)
{
ViewModel.IsDraggingOverImagesDropZone = false;
}
private async void OnImageDropGridImageDropped(object sender, DragEventArgs e)
{
try
{
if (e.DataView.Contains(StandardDataFormats.StorageItems))
{
var storageItems = await e.DataView.GetStorageItemsAsync();
var files = storageItems.OfType<StorageFile>();
var imagesInformation = new List<ImageInfo>();
foreach (var file in files)
{
if (IsValidImageFile(file))
{
imagesInformation.Add(new ImageInfo
{
Data = await GetDataURL(file),
Name = file.Name
});
}
}
await WebViewEditor.InsertImagesAsync(imagesInformation);
}
}
// State should be reset even when an exception occurs, otherwise the UI will be stuck in a dragging state.
finally
{
ViewModel.IsDraggingOverComposerGrid = false;
ViewModel.IsDraggingOverImagesDropZone = false;
}
static async Task<string> GetDataURL(StorageFile file)
{
return $"data:image/{file.FileType.Replace(".", "")};base64,{Convert.ToBase64String(await file.ToByteArrayAsync())}";
}
}
private async Task AttachFiles(IEnumerable<StorageFile> files)
{
if (files?.Any() != true) return;
// Convert files to MailAttachmentViewModel.
foreach (var file in files)
{
var sharedFile = await file.ToSharedFileAsync();
ViewModel.IncludedAttachments.Add(new MailAttachmentViewModel(sharedFile));
}
}
private static bool IsValidImageFile(StorageFile file)
{
string[] allowedTypes = [".jpg", ".jpeg", ".png"];
var fileType = file.FileType.ToLower();
return allowedTypes.Contains(fileType);
}
private void DisposeDisposables()
{
if (_disposables.Count != 0)
_disposables.ForEach(a => a.Dispose());
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
FocusManager.GotFocus += GlobalFocusManagerGotFocus;
var webView = GetWebView();
if (webView != null)
{
var anim = ConnectedAnimationService.GetForCurrentView().GetAnimation("WebViewConnectedAnimation");
anim?.TryStart(webView);
}
_disposables.Add(GetSuggestionBoxDisposable(ToBox));
_disposables.Add(GetSuggestionBoxDisposable(CCBox));
_disposables.Add(GetSuggestionBoxDisposable(BccBox));
_disposables.Add(WebViewEditor);
ViewModel.GetHTMLBodyFunction = WebViewEditor.GetHtmlBodyAsync;
}
async void IRecipient<CreateNewComposeMailRequested>.Receive(CreateNewComposeMailRequested message)
{
await WebViewEditor.RenderHtmlAsync(message.RenderModel.RenderHtml);
}
private void ShowCCBCCClicked(object sender, RoutedEventArgs e)
{
ViewModel.IsCCBCCVisible = true;
}
private async void TokenItemAdding(TokenizingTextBox sender, TokenItemAddingEventArgs args)
{
// Check is valid email.
if (!EmailValidator.Validate(args.TokenText))
{
args.Cancel = true;
ViewModel.NotifyInvalidEmail(args.TokenText);
return;
}
var deferral = args.GetDeferral();
var addedItem = (sender.Tag?.ToString()) switch
{
"ToBox" => await ViewModel.GetAddressInformationAsync(args.TokenText, ViewModel.ToItems),
"CCBox" => await ViewModel.GetAddressInformationAsync(args.TokenText, ViewModel.CCItems),
"BCCBox" => await ViewModel.GetAddressInformationAsync(args.TokenText, ViewModel.BCCItems),
_ => null
};
if (addedItem == null)
{
args.Cancel = true;
ViewModel.NotifyAddressExists();
}
else
{
args.Item = addedItem;
}
deferral.Complete();
}
void IRecipient<ApplicationThemeChanged>.Receive(ApplicationThemeChanged message)
{
WebViewEditor.IsEditorDarkMode = message.IsUnderlyingThemeDark;
}
private void ImportanceClicked(object sender, RoutedEventArgs e)
{
ImportanceFlyout.Hide();
ImportanceSplitButton.IsChecked = true;
if (sender is Button senderButton && senderButton.Tag is MessageImportance importance)
{
ViewModel.SelectedMessageImportance = importance;
if (ImportanceSplitButton.Content is Viewbox viewbox &&
viewbox.Child is SymbolIcon symbolIcon &&
senderButton.Content is SymbolIcon contentIcon)
{
symbolIcon.Symbol = contentIcon.Symbol;
}
}
}
private async void AddressBoxLostFocus(object sender, RoutedEventArgs e)
{
// Automatically add current text as item if it is valid mail address.
if (sender is TokenizingTextBox tokenizingTextBox)
{
if (tokenizingTextBox.Items.LastOrDefault() is not ITokenStringContainer info) return;
var currentText = info.Text;
if (!string.IsNullOrEmpty(currentText) && EmailValidator.Validate(currentText))
{
var addressCollection = tokenizingTextBox.Tag?.ToString() switch
{
"ToBox" => ViewModel.ToItems,
"CCBox" => ViewModel.CCItems,
"BCCBox" => ViewModel.BCCItems,
_ => null
};
AccountContact? addedItem = null;
if (addressCollection != null)
addedItem = await ViewModel.GetAddressInformationAsync(currentText, addressCollection);
// Item has already been added.
if (addedItem == null)
{
tokenizingTextBox.Text = string.Empty;
}
else if (addressCollection != null)
{
addressCollection.Add(addedItem);
tokenizingTextBox.Text = string.Empty;
}
}
}
}
// Hack: Tokenizing text box losing focus somehow on page Loaded and shifting focus to this element.
// For once we'll switch back to it once CCBBCGotFocus element got focus.
private bool isInitialFocusHandled = false;
private void ComposerLoaded(object sender, RoutedEventArgs e)
{
ToBox.Focus(FocusState.Programmatic);
}
private void CCBBCGotFocus(object sender, RoutedEventArgs e)
{
if (!isInitialFocusHandled)
{
isInitialFocusHandled = true;
ToBox.Focus(FocusState.Programmatic);
}
}
protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
base.OnNavigatingFrom(e);
FocusManager.GotFocus -= GlobalFocusManagerGotFocus;
await ViewModel.UpdateMimeChangesAsync();
DisposeDisposables();
}
private void OpenAttachment_Click(object sender, RoutedEventArgs e)
{
if (sender is MenuFlyoutItem item && item.CommandParameter is MailAttachmentViewModel attachment)
{
ViewModel.OpenAttachmentCommand.Execute(attachment);
}
}
private void SaveAttachment_Click(object sender, RoutedEventArgs e)
{
if (sender is MenuFlyoutItem item && item.CommandParameter is MailAttachmentViewModel attachment)
{
ViewModel.SaveAttachmentCommand.Execute(attachment);
}
}
private void RemoveAttachment_Click(object sender, RoutedEventArgs e)
{
if (sender is Button button && button.CommandParameter is MailAttachmentViewModel attachment)
{
ViewModel.RemoveAttachmentCommand.Execute(attachment);
}
}
protected override void RegisterRecipients()
{
base.RegisterRecipients();
WeakReferenceMessenger.Default.Register<CreateNewComposeMailRequested>(this);
WeakReferenceMessenger.Default.Register<ApplicationThemeChanged>(this);
}
protected override void UnregisterRecipients()
{
base.UnregisterRecipients();
WeakReferenceMessenger.Default.Unregister<CreateNewComposeMailRequested>(this);
WeakReferenceMessenger.Default.Unregister<ApplicationThemeChanged>(this);
}
// TODO: Save mime on closing the app.
private async void OnClose(object sender, SystemNavigationCloseRequestedPreviewEventArgs e)
{
var deferral = e.GetDeferral();
try
{
await ViewModel.UpdateMimeChangesAsync();
}
finally { deferral.Complete(); }
}
}
+15
View File
@@ -0,0 +1,15 @@
<abstract:IdlePageAbstract
x:Class="Wino.Views.Mail.IdlePage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:abstract="using:Wino.Views.Abstract"
xmlns:controls="using:Wino.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:helpers="using:Wino.Helpers"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<!-- Empty page for disposing composer or renderer page. -->
<Grid />
</abstract:IdlePageAbstract>
@@ -0,0 +1,11 @@
using Wino.Views.Abstract;
namespace Wino.Views.Mail;
public sealed partial class IdlePage : IdlePageAbstract
{
public IdlePage()
{
InitializeComponent();
}
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,753 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.WinUI;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media.Animation;
using Microsoft.UI.Xaml.Navigation;
using MoreLinq;
using Windows.Foundation;
using Windows.System;
using Wino.Controls;
using Wino.Core.Domain;
using Wino.Core.Domain.Enums;
using Wino.Core.Domain.Interfaces;
using Wino.Core.Domain.Models.MailItem;
using Wino.Core.Domain.Models.Menus;
using Wino.Core.Domain.Models.Navigation;
using Wino.Mail.ViewModels.Data;
using Wino.Mail.ViewModels.Messages;
using Wino.Mail.WinUI;
using Wino.Mail.WinUI.Controls.ListView;
using Wino.Mail.WinUI.Extensions;
using Wino.MenuFlyouts.Context;
using Wino.Messaging.Client.Mails;
using Wino.Views.Abstract;
namespace Wino.Views.Mail;
public sealed partial class MailListPage : MailListPageAbstract,
IRecipient<ClearMailSelectionsRequested>,
IRecipient<ActiveMailItemChangedEvent>,
IRecipient<SelectMailItemContainerEvent>,
IRecipient<DisposeRenderingFrameRequested>
{
private const double RENDERING_COLUMN_MIN_WIDTH = 375;
private IStatePersistanceService StatePersistenceService { get; } = WinoApplication.Current.Services.GetService<IStatePersistanceService>() ?? throw new Exception($"Can't resolve {nameof(KeyPressService)}");
private IKeyPressService KeyPressService { get; } = WinoApplication.Current.Services.GetService<IKeyPressService>() ?? throw new Exception($"Can't resolve {nameof(KeyPressService)}");
private IKeyboardShortcutService KeyboardShortcutService { get; } = WinoApplication.Current.Services.GetService<IKeyboardShortcutService>() ?? throw new Exception($"Can't resolve {nameof(IKeyboardShortcutService)}");
public MailListPage()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
Bindings.Update();
ViewModel.MailCollection.ItemSelectionChanged += WinoMailCollectionSelectionChanged;
UpdateSelectAllButtonStatus();
UpdateAdaptiveness();
// Delegate to ViewModel.
if (e.Parameter is NavigateMailFolderEventArgs folderNavigationArgs)
{
WeakReferenceMessenger.Default.Send(new ActiveMailFolderChangedEvent(folderNavigationArgs.BaseFolderMenuItem, folderNavigationArgs.FolderInitLoadAwaitTask));
}
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
this.Bindings.StopTracking();
ViewModel.MailCollection.ItemSelectionChanged -= WinoMailCollectionSelectionChanged;
SelectAllCheckbox.Checked -= SelectAllCheckboxChecked;
SelectAllCheckbox.Unchecked -= SelectAllCheckboxUnchecked;
MailListView.Cleanup();
RenderingFrame.Navigate(typeof(IdlePage));
GC.Collect();
}
private void UpdateSelectAllButtonStatus()
{
// Check all checkbox if all is selected.
// Unhook events to prevent selection overriding.
DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Low, () =>
{
SelectAllCheckbox.Checked -= SelectAllCheckboxChecked;
SelectAllCheckbox.Unchecked -= SelectAllCheckboxUnchecked;
SelectAllCheckbox.IsChecked = ViewModel.MailCollection.IsAllItemsSelected;
SelectAllCheckbox.Checked += SelectAllCheckboxChecked;
SelectAllCheckbox.Unchecked += SelectAllCheckboxUnchecked;
});
}
private void SelectionModeToggleChecked(object sender, RoutedEventArgs e) => ChangeSelectionMode(ListViewSelectionMode.Multiple);
private void MailItemDisplayInformationControl_HoverActionExecuted(object sender, MailOperationPreperationRequest e)
{
ViewModel.ExecuteHoverActionCommand.Execute(e);
}
private void FolderPivotChanged(object sender, SelectionChangedEventArgs e)
{
foreach (var addedItem in e.AddedItems)
{
if (addedItem is FolderPivotViewModel pivotItem)
{
pivotItem.IsSelected = true;
}
}
foreach (var removedItem in e.RemovedItems)
{
if (removedItem is FolderPivotViewModel pivotItem)
{
pivotItem.IsSelected = false;
}
}
SelectAllCheckbox.IsChecked = false;
SelectionModeToggle.IsChecked = false;
UpdateSelectAllButtonStatus();
ViewModel.SelectedPivotChangedCommand.Execute(null);
}
private void ChangeSelectionMode(ListViewSelectionMode mode)
{
MailListView.ChangeSelectionMode(mode);
if (ViewModel?.PivotFolders != null)
{
ViewModel.PivotFolders.ForEach(a => a.IsExtendedMode = mode == ListViewSelectionMode.Extended);
}
}
private void SelectionModeToggleUnchecked(object sender, RoutedEventArgs e)
{
ChangeSelectionMode(ListViewSelectionMode.Extended);
}
private async void SelectAllCheckboxChecked(object sender, RoutedEventArgs e)
{
await ViewModel.MailCollection.SelectAllAsync();
}
private async void SelectAllCheckboxUnchecked(object sender, RoutedEventArgs e)
{
await ViewModel.MailCollection.UnselectAllAsync();
}
private void WinoListViewChoosingItemContainer(ListViewBase sender, ChoosingItemContainerEventArgs args)
{
if (args.Item is ThreadMailItemViewModel && args.ItemContainer is not WinoThreadMailItemViewModelListViewItem)
{
args.ItemContainer = new WinoThreadMailItemViewModelListViewItem()
{
Item = args.Item as ThreadMailItemViewModel
};
}
else if (args.Item is MailItemViewModel && args.ItemContainer is not WinoMailItemViewModelListViewItem)
{
args.ItemContainer = new WinoMailItemViewModelListViewItem()
{
Item = args.Item as MailItemViewModel
};
}
}
private async void MailItemContextRequested(UIElement sender, ContextRequestedEventArgs args)
{
// Context is requested from a single mail point, but we might have multiple selected items.
// This menu should be calculated based on all selected items by providers.
if (sender is MailItemDisplayInformationControl control && args.TryGetPosition(sender, out Point p))
{
IEnumerable<MailItemViewModel> targetItems;
if (!ViewModel.MailCollection.SelectedItems.Contains(control.ActionItem))
{
// Right clicked item is not selected. Select.
await WinoClickItemInternalAsync(control.ActionItem, true);
}
// Default to all selected items.
targetItems = ViewModel.MailCollection.SelectedItems;
var availableActions = ViewModel.GetAvailableMailActions(targetItems);
if (availableActions == null || !availableActions.Any()) return;
var clickedOperation = await GetMailOperationFromFlyoutAsync(availableActions, control, p.X, p.Y);
if (clickedOperation == null) return;
var prepRequest = new MailOperationPreperationRequest(clickedOperation.Operation, targetItems.Select(a => a.MailCopy));
await ViewModel.ExecuteMailOperationAsync(prepRequest);
}
}
private async Task<MailOperationMenuItem> GetMailOperationFromFlyoutAsync(IEnumerable<MailOperationMenuItem> availableActions,
UIElement showAtElement,
double x,
double y)
{
var source = new TaskCompletionSource<MailOperationMenuItem>();
var flyout = new MailOperationFlyout(availableActions, source);
flyout.ShowAt(showAtElement, new FlyoutShowOptions()
{
ShowMode = FlyoutShowMode.Standard,
Position = new Point(x + 30, y - 20)
});
return await source.Task;
}
async void IRecipient<ClearMailSelectionsRequested>.Receive(ClearMailSelectionsRequested message)
{
await ViewModel.MailCollection.UnselectAllAsync();
}
void IRecipient<ActiveMailItemChangedEvent>.Receive(ActiveMailItemChangedEvent message)
{
// No active mail item. Go to empty page.
if (message.SelectedMailItemViewModel == null)
{
WeakReferenceMessenger.Default.Send(new CancelRenderingContentRequested());
}
else
{
// Navigate to composing page.
if (message.SelectedMailItemViewModel.IsDraft)
{
NavigationTransitionType composerPageTransition = NavigationTransitionType.None;
// Dispose active rendering if there is any and go to composer.
if (IsRenderingPageActive())
{
// Prepare WebView2 animation from Rendering to Composing page.
PrepareRenderingPageWebViewTransition();
// Dispose existing HTML content from rendering page webview.
WeakReferenceMessenger.Default.Send(new CancelRenderingContentRequested());
}
else if (IsComposingPageActive())
{
// Composer is already active. Prepare composer WebView2 animation.
PrepareComposePageWebViewTransition();
}
else
composerPageTransition = NavigationTransitionType.DrillIn;
ViewModel.NavigationService.Navigate(WinoPage.ComposePage, message.SelectedMailItemViewModel, NavigationReferenceFrame.RenderingFrame, composerPageTransition);
}
else
{
// Find the MIME and go to rendering page.
if (message.SelectedMailItemViewModel == null) return;
if (IsComposingPageActive())
{
PrepareComposePageWebViewTransition();
}
ViewModel.NavigationService.Navigate(WinoPage.MailRenderingPage, message.SelectedMailItemViewModel, NavigationReferenceFrame.RenderingFrame);
}
}
UpdateAdaptiveness();
}
private bool IsRenderingPageActive() => RenderingFrame.Content is MailRenderingPage;
private bool IsComposingPageActive() => RenderingFrame.Content is ComposePage;
private void PrepareComposePageWebViewTransition()
{
var webView = GetComposerPageWebView();
if (webView != null)
{
var animation = ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("WebViewConnectedAnimation", webView);
animation.Configuration = new BasicConnectedAnimationConfiguration();
}
}
private void PrepareRenderingPageWebViewTransition()
{
var webView = GetRenderingPageWebView();
if (webView != null)
{
var animation = ConnectedAnimationService.GetForCurrentView().PrepareToAnimate("WebViewConnectedAnimation", webView);
animation.Configuration = new BasicConnectedAnimationConfiguration();
}
}
#region Connected Animation Helpers
private WebView2? GetRenderingPageWebView()
{
if (RenderingFrame.Content is MailRenderingPage renderingPage)
return renderingPage.GetWebView();
return null;
}
private WebView2? GetComposerPageWebView()
{
if (RenderingFrame.Content is ComposePage composePage)
return composePage.GetWebView();
return null;
}
#endregion
public async void Receive(SelectMailItemContainerEvent message)
{
if (message.MailUniqueId == Guid.Empty) return;
// Find the item from the collection.
// Folder should be initialized already.
var item = ViewModel.MailCollection.Find(message.MailUniqueId);
if (item == null) return;
await DispatcherQueue.EnqueueAsync(async () =>
{
var collectionContainer = await MailListView.GetItemContainersAsync(item);
if (collectionContainer.Item1 == null && collectionContainer.Item2 == null) return;
// Automatically scroll to the selected item.
// This is useful when creating draft.
if (message.ScrollToItem)
{
// Scroll to thread if available.
// Find the item index on the UI. This is different than ListView.
int scrollIndex = -1;
if (collectionContainer.Item2 != null)
{
scrollIndex = ViewModel.MailCollection.IndexOf(collectionContainer.Item2.Item);
}
else if (collectionContainer.Item1 != null)
{
scrollIndex = ViewModel.MailCollection.IndexOf(collectionContainer.Item1.Item);
}
if (scrollIndex >= 0)
{
await MailListView.SmoothScrollIntoViewWithIndexAsync(scrollIndex);
}
}
await WinoClickItemInternalAsync(item, true);
});
}
private void SearchBoxFocused(object sender, RoutedEventArgs e)
{
SearchBar.PlaceholderText = string.Empty;
}
private void SearchBarUnfocused(object sender, RoutedEventArgs e)
{
SearchBar.PlaceholderText = Translator.SearchBarPlaceholder;
}
/// <summary>
/// Thread header is mail info display control and it can be dragged spearately out of ListView.
/// We need to prepare a drag package for it from the items inside.
/// </summary>
private void ThreadHeaderDragStart(UIElement sender, DragStartingEventArgs args)
{
//if (sender is MailItemDisplayInformationControl control
// && control.ConnectedExpander?.Content is WinoListView contentListView)
//{
// var allItems = contentListView.Items.Where(a => a is MailCopy);
// // Highlight all items.
// allItems.Cast<MailItemViewModel>().ForEach(a => a.IsCustomFocused = true);
// // Set native drag arg properties.
// args.AllowedOperations = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Move;
// var dragPackage = new MailDragPackage(allItems.Cast<MailCopy>());
// args.Data.Properties.Add(nameof(MailDragPackage), dragPackage);
// args.DragUI.SetContentFromDataPackage();
// control.ConnectedExpander.IsExpanded = true;
//}
}
private void ThreadHeaderDragFinished(UIElement sender, DropCompletedEventArgs args)
{
}
private async void LeftSwipeItemInvoked(Microsoft.UI.Xaml.Controls.SwipeItem sender, Microsoft.UI.Xaml.Controls.SwipeItemInvokedEventArgs args)
{
// Delete item for now.
var swipeControl = args.SwipeControl;
swipeControl.Close();
if (swipeControl.Tag is MailItemViewModel mailItemViewModel)
{
var package = new MailOperationPreperationRequest(MailOperation.SoftDelete, mailItemViewModel.MailCopy);
await ViewModel.ExecuteMailOperationAsync(package);
}
else if (swipeControl.Tag is ThreadMailItemViewModel threadMailItemViewModel)
{
var package = new MailOperationPreperationRequest(MailOperation.SoftDelete, threadMailItemViewModel.ThreadEmails.Select(a => a.MailCopy));
await ViewModel.ExecuteMailOperationAsync(package);
}
}
private async void RightSwipeItemInvoked(Microsoft.UI.Xaml.Controls.SwipeItem sender, Microsoft.UI.Xaml.Controls.SwipeItemInvokedEventArgs args)
{
// Toggle status only for now.
var swipeControl = args.SwipeControl;
swipeControl.Close();
if (swipeControl.Tag is MailItemViewModel mailItemViewModel)
{
var operation = mailItemViewModel.IsRead ? MailOperation.MarkAsUnread : MailOperation.MarkAsRead;
var package = new MailOperationPreperationRequest(operation, mailItemViewModel.MailCopy);
await ViewModel.ExecuteMailOperationAsync(package);
}
else if (swipeControl.Tag is ThreadMailItemViewModel threadMailItemViewModel)
{
bool isAllRead = threadMailItemViewModel.ThreadEmails.All(a => a.IsRead);
var operation = isAllRead ? MailOperation.MarkAsUnread : MailOperation.MarkAsRead;
var package = new MailOperationPreperationRequest(operation, threadMailItemViewModel.ThreadEmails.Select(a => a.MailCopy));
await ViewModel.ExecuteMailOperationAsync(package);
}
}
private async void SearchBar_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
// User clicked 'x' button to clearout the search text.
if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput && string.IsNullOrWhiteSpace(sender.Text))
{
ViewModel.IsOnlineSearchButtonVisible = false;
await ViewModel.PerformSearchAsync();
}
}
public void Receive(DisposeRenderingFrameRequested message)
{
ViewModel.NavigationService.Navigate(WinoPage.IdlePage, null, NavigationReferenceFrame.RenderingFrame, NavigationTransitionType.DrillIn);
UpdateAdaptiveness();
}
protected override void RegisterRecipients()
{
WeakReferenceMessenger.Default.Register<ClearMailSelectionsRequested>(this);
WeakReferenceMessenger.Default.Register<ActiveMailItemChangedEvent>(this);
WeakReferenceMessenger.Default.Register<SelectMailItemContainerEvent>(this);
WeakReferenceMessenger.Default.Register<DisposeRenderingFrameRequested>(this);
}
protected override void UnregisterRecipients()
{
WeakReferenceMessenger.Default.Unregister<ClearMailSelectionsRequested>(this);
WeakReferenceMessenger.Default.Unregister<ActiveMailItemChangedEvent>(this);
WeakReferenceMessenger.Default.Unregister<SelectMailItemContainerEvent>(this);
WeakReferenceMessenger.Default.Unregister<DisposeRenderingFrameRequested>(this);
}
private void PageSizeChanged(object sender, SizeChangedEventArgs e)
{
ViewModel.MaxMailListLength = e.NewSize.Width - RENDERING_COLUMN_MIN_WIDTH;
StatePersistenceService.IsReaderNarrowed = e.NewSize.Width < StatePersistenceService.MailListPaneLength + RENDERING_COLUMN_MIN_WIDTH;
UpdateAdaptiveness();
}
private void MailListSizerManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
{
StatePersistenceService.MailListPaneLength = ViewModel.MailListLength;
}
private void UpdateAdaptiveness()
{
bool isMultiSelectionEnabled = ViewModel.IsMultiSelectionModeEnabled;
if (StatePersistenceService.IsReaderNarrowed)
{
if (ViewModel.MailCollection.HasSingleItemSelected && !isMultiSelectionEnabled)
{
VisualStateManager.GoToState(this, "NarrowRenderer", true);
}
else
{
VisualStateManager.GoToState(this, "NarrowMailList", true);
}
}
else
{
if (ViewModel.MailCollection.HasSingleItemSelected && !isMultiSelectionEnabled)
{
VisualStateManager.GoToState(this, "BothPanelsMailSelected", true);
}
else
{
VisualStateManager.GoToState(this, "BothPanelsNoMailSelected", true);
}
}
}
private void WinoMailCollectionSelectionChanged(object? sender, EventArgs args)
{
UpdateSelectAllButtonStatus();
UpdateAdaptiveness();
}
private async void WinoListViewProcessKeyboardAccelerators(UIElement sender, ProcessKeyboardAcceleratorEventArgs args)
{
args.Handled = true;
if (args.Key == VirtualKey.Delete)
{
ViewModel.ExecuteMailOperationCommand.Execute(MailOperation.SoftDelete);
}
else if (args.Key == VirtualKey.A && args.Modifiers.HasFlag(VirtualKeyModifiers.Control))
{
await ViewModel.MailCollection.ToggleSelectAllAsync();
}
else
{
// Check keyboard shortcuts from service.
ModifierKeys modifiers = args.Modifiers.ToDomainModifierKeys();
var operation = await KeyboardShortcutService.GetMailOperationForKeyAsync(args.Key.ToString(), modifiers);
if (operation != null)
{
ViewModel.ExecuteMailOperationCommand.Execute(operation);
}
else
{
args.Handled = false;
}
}
}
private async Task WinoClickItemInternalAsync(object? clickedItem, bool selectExpandThread = false)
{
if (clickedItem == null) return;
// Requirements (summary):
// CTRL pressed -> multi-select behaviour
// * Clicking single item toggles only that item.
// * Clicking thread header toggles selection of thread AND all its children (all on or all off).
// * Clicking an item inside a thread toggles only that child item.
// CTRL NOT pressed -> single-select (exclusive) with toggle support (can leave zero selected)
// * Clicking thread header: unselect everything else, collapse all other threads, select only the thread + first child.
// If already in that state (thread selected and first child selected), clicking again unselects all (nothing selected).
// * Clicking a single (non-thread) item OR a child item: collapse & unselect all others then toggle that item's selection.
// If it was selected, result is nothing selected.
bool isCtrlPressed = KeyPressService.IsCtrlKeyPressed();
// Helper local to collapse all other threads (we always collapse ALL then possibly re-expand the active thread per rules)
async Task CollapseAllThreadsExceptAsync(ThreadMailItemViewModel? except)
{
bool wasExpanded = except != null && except.IsThreadExpanded;
await ViewModel.MailCollection.CollapseAllThreadsAsync();
if (except != null && wasExpanded)
{
// We'll expand explicitly when required by logic below.
except.IsThreadExpanded = true;
}
}
if (isCtrlPressed)
{
switch (clickedItem)
{
case ThreadMailItemViewModel thread:
{
// Determine if thread + all children currently selected
bool allSelected = thread.IsSelected && thread.ThreadEmails.All(e => e.IsSelected);
if (allSelected)
{
// Unselect thread & all children
thread.IsSelected = false;
foreach (var child in thread.ThreadEmails)
child.IsSelected = false;
}
else
{
// Select thread & all children (do NOT disturb other selections in CTRL mode)
thread.IsSelected = true;
foreach (var child in thread.ThreadEmails)
child.IsSelected = true;
// Keep it expanded so user can see items
thread.IsThreadExpanded = true;
}
break;
}
case MailItemViewModel mail:
{
// Toggle just this item; no collapse/unselect of others in multi-select mode.
mail.IsSelected = !mail.IsSelected;
break;
}
}
return; // Multi-select path ends here.
}
// SINGLE-SELECTION (exclusive) MODE WITH TOGGLE SUPPORT
if (clickedItem is ThreadMailItemViewModel clickedThread)
{
bool wasThreadSelected = clickedThread.IsSelected;
bool wasThreadExpanded = clickedThread.IsThreadExpanded;
// Check if any child in this thread is already selected (e.g., from notification click)
var alreadySelectedChild = clickedThread.ThreadEmails.FirstOrDefault(e => e.IsSelected);
// Reset everything first (exclusive selection scenario)
await ViewModel.MailCollection.UnselectAllAsync();
await CollapseAllThreadsExceptAsync(clickedThread);
if (wasThreadSelected && wasThreadExpanded)
{
// Toggle off -> leave nothing selected (all unselected, thread collapsed)
clickedThread.IsThreadExpanded = false;
return;
}
// Select thread header
clickedThread.IsSelected = true;
// If a child was already selected (e.g., from notification), keep that selection
// Otherwise, select the first child
if (alreadySelectedChild != null)
{
alreadySelectedChild.IsSelected = true;
}
else
{
var firstChild = clickedThread.ThreadEmails.FirstOrDefault();
if (firstChild != null)
{
firstChild.IsSelected = true;
}
}
clickedThread.IsThreadExpanded = true; // Show contents of active thread
}
else if (clickedItem is MailItemViewModel clickedMail)
{
bool wasSelected = clickedMail.IsSelected;
// Determine if this mail belongs to an already selected & expanded thread.
// If so, we only want to switch the selection inside that thread without collapsing or unselecting the thread header.
ThreadMailItemViewModel? parentThread = null;
foreach (var group in ViewModel.MailCollection.MailItems)
{
foreach (var item in group)
{
if (item is ThreadMailItemViewModel thread && thread.ThreadEmails.Contains(clickedMail))
{
parentThread = thread;
break;
}
}
if (parentThread != null) break;
}
bool isInSelectedExpandedThread = parentThread != null && parentThread.IsSelected && parentThread.IsThreadExpanded;
if (isInSelectedExpandedThread)
{
// Switch selection within the thread: unselect previously selected children, select the clicked one.
if (parentThread?.ThreadEmails != null)
{
foreach (var child in parentThread.ThreadEmails)
{
child.IsSelected = child == clickedMail && !wasSelected; // If clicking an already selected child -> toggle off (none selected in thread except header)
}
}
if (wasSelected && parentThread != null)
{
// Clicking the already selected child should leave the thread header selected (canonical state: thread + first child previously).
// Decide whether to keep a child selected; spec wants toggle off allowed, so leave no child selected.
// Ensure parent thread stays selected & expanded.
parentThread.IsSelected = true;
parentThread.IsThreadExpanded = true;
}
return; // Done.
}
// Normal single-item (non-thread or entering a thread via child) behavior.
await ViewModel.MailCollection.UnselectAllAsync();
await ViewModel.MailCollection.CollapseAllThreadsAsync();
if (parentThread != null && selectExpandThread)
{
// We're clicking an item inside a thread; select & expand the thread header as well.
parentThread.IsSelected = true;
parentThread.IsThreadExpanded = true;
}
if (!wasSelected)
{
clickedMail.IsSelected = true; // Toggle on
}
}
}
private async void WinoListViewItemClicked(object sender, ItemClickEventArgs e)
{
if (sender is not WinoListView listView) return;
await WinoClickItemInternalAsync(e.ClickedItem);
}
private void SearchbarQuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
{
if (ViewModel.PerformSearchCommand.CanExecute(null))
ViewModel.PerformSearchCommand.Execute(null);
}
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,345 @@
using System;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media.Animation;
using Microsoft.UI.Xaml.Navigation;
using Microsoft.Web.WebView2.Core;
using Windows.System;
using Wino.Core.Domain;
using Wino.Core.Domain.Enums;
using Wino.Core.Domain.Interfaces;
using Wino.Core.Domain.Models.Printing;
using Wino.Mail.ViewModels.Data;
using Wino.Mail.WinUI;
using Wino.Mail.WinUI.Extensions;
using Wino.Messaging.Client.Mails;
using Wino.Messaging.Client.Shell;
using Wino.Views.Abstract;
namespace Wino.Views.Mail;
public sealed partial class MailRenderingPage : MailRenderingPageAbstract,
IRecipient<HtmlRenderingRequested>,
IRecipient<CancelRenderingContentRequested>,
IRecipient<ApplicationThemeChanged>
{
private readonly IPreferencesService _preferencesService = App.Current.Services.GetService<IPreferencesService>()!;
private readonly IMailDialogService _dialogService = App.Current.Services.GetService<IMailDialogService>()!;
private bool isRenderingInProgress = false;
private TaskCompletionSource<bool> DOMLoadedTask = new TaskCompletionSource<bool>();
private bool isChromiumDisposed = false;
public WebView2 GetWebView() => Chromium;
public MailRenderingPage()
{
InitializeComponent();
Environment.SetEnvironmentVariable("WEBVIEW2_DEFAULT_BACKGROUND_COLOR", "00FFFFFF");
Environment.SetEnvironmentVariable("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS", "--enable-features=OverlayScrollbar,msOverlayScrollbarWinStyle,msOverlayScrollbarWinStyleAnimation,msWebView2CodeCache");
ViewModel.DirectPrintFuncAsync = DirectPrintAsync;
ViewModel.SaveHTMLasPDFFunc = new Func<string, Task<bool>>((path) =>
{
return Chromium.CoreWebView2.PrintToPdfAsync(path, null).AsTask();
});
}
private async Task<PrintingResult> DirectPrintAsync(WebView2PrintSettingsModel settings)
{
if (Chromium.CoreWebView2 == null) return PrintingResult.Failed;
try
{
var nativeSettings = settings.ToCoreWebView2PrintSettings(Chromium.CoreWebView2.Environment);
var res = await Chromium.CoreWebView2.PrintAsync(nativeSettings);
return res switch
{
CoreWebView2PrintStatus.Succeeded => PrintingResult.Submitted,
_ => PrintingResult.Failed,
};
}
catch (Exception)
{
return PrintingResult.Failed;
}
}
public override async void OnEditorThemeChanged()
{
base.OnEditorThemeChanged();
await UpdateEditorThemeAsync();
}
private async Task<string> InvokeScriptSafeAsync(string function)
{
try
{
return await Chromium.ExecuteScriptAsync(function);
}
catch (Exception) { }
return string.Empty;
}
private async Task RenderInternalAsync(string htmlBody)
{
isRenderingInProgress = true;
await DOMLoadedTask.Task;
await UpdateEditorThemeAsync();
await UpdateReaderFontPropertiesAsync();
if (string.IsNullOrEmpty(htmlBody))
{
await Chromium.ExecuteScriptFunctionAsync("RenderHTML", isChromiumDisposed, JsonSerializer.Serialize(" ", BasicTypesJsonContext.Default.String));
}
else
{
var shouldLinkifyText = ViewModel.CurrentRenderModel?.MailRenderingOptions?.RenderPlaintextLinks ?? true;
await Chromium.ExecuteScriptFunctionAsync("RenderHTML", isChromiumDisposed,
JsonSerializer.Serialize(htmlBody, BasicTypesJsonContext.Default.String),
JsonSerializer.Serialize(shouldLinkifyText, BasicTypesJsonContext.Default.Boolean));
}
isRenderingInProgress = false;
}
private async void WindowRequested(CoreWebView2 sender, CoreWebView2NewWindowRequestedEventArgs args)
{
args.Handled = true;
try
{
await Launcher.LaunchUriAsync(new Uri(args.Uri));
}
catch (Exception) { }
}
private void DOMContentLoaded(CoreWebView2 sender, CoreWebView2DOMContentLoadedEventArgs args) => DOMLoadedTask.TrySetResult(true);
async void IRecipient<HtmlRenderingRequested>.Receive(HtmlRenderingRequested message)
{
if (message == null || string.IsNullOrEmpty(message.HtmlBody))
{
await RenderInternalAsync(string.Empty);
return;
}
await Chromium.EnsureCoreWebView2Async();
await RenderInternalAsync(message.HtmlBody);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
// Disposing the page.
// Make sure the WebView2 is disposed properly.
ViewModel.SaveHTMLasPDFFunc = null;
ViewModel.DirectPrintFuncAsync = null;
DisposeWebView2();
}
private void DisposeWebView2()
{
if (Chromium == null) return;
Chromium.CoreWebView2Initialized -= CoreWebViewInitialized;
Chromium.NavigationStarting -= WebViewNavigationStarting;
if (Chromium.CoreWebView2 != null)
{
Chromium.CoreWebView2.DOMContentLoaded -= DOMContentLoaded;
Chromium.CoreWebView2.NewWindowRequested -= WindowRequested;
}
isChromiumDisposed = true;
Chromium.Close();
GC.Collect();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
var anim = ConnectedAnimationService.GetForCurrentView().GetAnimation("WebViewConnectedAnimation");
anim?.TryStart(Chromium);
Chromium.CoreWebView2Initialized -= CoreWebViewInitialized;
Chromium.CoreWebView2Initialized += CoreWebViewInitialized;
_ = Chromium.EnsureCoreWebView2Async();
// We don't have shell initialized here. It's only standalone EML viewing.
// Shift command bar from top to adjust the design.
if (ViewModel.StatePersistenceService.ShouldShiftMailRenderingDesign)
RendererGridFrame.Margin = new Thickness(0, 24, 0, 0);
else
RendererGridFrame.Margin = new Thickness(0, 0, 0, 0);
}
private async void CoreWebViewInitialized(WebView2 sender, CoreWebView2InitializedEventArgs args)
{
if (Chromium.CoreWebView2 == null) return;
var editorBundlePath = (await ViewModel.NativeAppService.GetEditorBundlePathAsync()).Replace("editor.html", string.Empty);
Chromium.CoreWebView2.SetVirtualHostNameToFolderMapping("wino.mail", editorBundlePath, CoreWebView2HostResourceAccessKind.Allow);
Chromium.CoreWebView2.DOMContentLoaded -= DOMContentLoaded;
Chromium.CoreWebView2.DOMContentLoaded += DOMContentLoaded;
Chromium.CoreWebView2.NewWindowRequested -= WindowRequested;
Chromium.CoreWebView2.NewWindowRequested += WindowRequested;
Chromium.Source = new Uri("https://wino.mail/reader.html");
}
async void IRecipient<CancelRenderingContentRequested>.Receive(CancelRenderingContentRequested message)
{
await Chromium.EnsureCoreWebView2Async();
if (!isRenderingInProgress)
{
await RenderInternalAsync(string.Empty);
}
}
private async void WebViewNavigationStarting(WebView2 sender, CoreWebView2NavigationStartingEventArgs args)
{
// This is our reader.
if (args.Uri == "https://wino.mail/reader.html")
return;
// Cancel all external navigations since it's navigating to different address inside the WebView2.
args.Cancel = !args.Uri.StartsWith("data:text/html");
// TODO: Check external link navigation setting is enabled.
// Open all external urls in launcher.
if (args.Cancel && Uri.TryCreate(args.Uri, UriKind.Absolute, out Uri? newUri) && newUri != null)
{
await Launcher.LaunchUriAsync(newUri);
}
}
private void AttachmentClicked(object sender, ItemClickEventArgs e)
{
if (e.ClickedItem is MailAttachmentViewModel attachmentViewModel)
{
ViewModel?.OpenAttachmentCommand.Execute(attachmentViewModel);
}
}
private void BarDynamicOverflowChanging(CommandBar sender, DynamicOverflowItemsChangingEventArgs args)
{
if (args.Action == CommandBarDynamicOverflowAction.AddingToOverflow || sender.SecondaryCommands.Any())
sender.OverflowButtonVisibility = CommandBarOverflowButtonVisibility.Visible;
else
sender.OverflowButtonVisibility = CommandBarOverflowButtonVisibility.Collapsed;
}
private async Task UpdateEditorThemeAsync()
{
await DOMLoadedTask.Task;
if (ViewModel.IsDarkWebviewRenderer)
{
Chromium.CoreWebView2.Profile.PreferredColorScheme = CoreWebView2PreferredColorScheme.Dark;
await InvokeScriptSafeAsync("SetDarkEditor();");
}
else
{
Chromium.CoreWebView2.Profile.PreferredColorScheme = CoreWebView2PreferredColorScheme.Light;
await InvokeScriptSafeAsync("SetLightEditor();");
}
}
private async Task UpdateReaderFontPropertiesAsync()
{
await Chromium.ExecuteScriptFunctionAsync("ChangeFontSize", isChromiumDisposed, JsonSerializer.Serialize(_preferencesService.ReaderFontSize, BasicTypesJsonContext.Default.Int32));
// Prepare font family name with fallback to sans-serif by default.
var fontName = _preferencesService.ReaderFont;
// If font family name is not supported by the browser, fallback to sans-serif.
fontName += ", sans-serif";
await Chromium.ExecuteScriptFunctionAsync("ChangeFontFamily", isChromiumDisposed, JsonSerializer.Serialize(fontName, BasicTypesJsonContext.Default.String));
}
void IRecipient<ApplicationThemeChanged>.Receive(ApplicationThemeChanged message)
{
ViewModel.IsDarkWebviewRenderer = message.IsUnderlyingThemeDark;
}
private void InternetAddressClicked(object sender, RoutedEventArgs e)
{
if (sender is HyperlinkButton hyperlinkButton)
{
hyperlinkButton.ContextFlyout.ShowAt(hyperlinkButton);
}
}
private void CopyAddress_Click(object sender, RoutedEventArgs e)
{
if (sender is HyperlinkButton button && button.CommandParameter is string address)
{
ViewModel.CopyClipboardCommand.Execute(address);
}
}
private void OpenAttachment_Click(object sender, RoutedEventArgs e)
{
if (sender is MenuFlyoutItem item && item.CommandParameter is MailAttachmentViewModel attachment)
{
ViewModel.OpenAttachmentCommand.Execute(attachment);
}
}
private void SaveAttachment_Click(object sender, RoutedEventArgs e)
{
if (sender is MenuFlyoutItem item && item.CommandParameter is MailAttachmentViewModel attachment)
{
ViewModel.SaveAttachmentCommand.Execute(attachment);
}
}
protected override void RegisterRecipients()
{
base.RegisterRecipients();
WeakReferenceMessenger.Default.Register<HtmlRenderingRequested>(this);
WeakReferenceMessenger.Default.Register<CancelRenderingContentRequested>(this);
WeakReferenceMessenger.Default.Register<ApplicationThemeChanged>(this);
}
protected override void UnregisterRecipients()
{
base.UnregisterRecipients();
WeakReferenceMessenger.Default.Unregister<HtmlRenderingRequested>(this);
WeakReferenceMessenger.Default.Unregister<CancelRenderingContentRequested>(this);
WeakReferenceMessenger.Default.Unregister<ApplicationThemeChanged>(this);
}
}