Files
Wino-Mail/Wino.Mail/Views/ComposePage.xaml.cs

391 lines
13 KiB
C#
Raw Normal View History

2024-04-18 01:44:37 +02:00
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.Controls;
using MimeKit;
2024-05-22 02:10:14 +02:00
using Windows.ApplicationModel.DataTransfer;
2024-04-18 01:44:37 +02:00
using Windows.Foundation;
2024-05-22 02:10:14 +02:00
using Windows.Storage;
using Windows.UI.Core.Preview;
2024-04-18 01:44:37 +02:00
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
2024-04-18 01:44:37 +02:00
using Windows.UI.Xaml.Navigation;
2024-05-22 02:10:14 +02:00
using Wino.Core.Domain;
using Wino.Core.Domain.Entities.Shared;
Full trust Wino Server implementation. (#295) * Separation of messages. Introducing Wino.Messages library. * Wino.Server and Wino.Packaging projects. Enabling full trust for UWP and app service connection manager basics. * Remove debug code. * Enable generating assembly info to deal with unsupported os platform warnings. * Fix server-client connection. * UIMessage communication. Single instancing for server and re-connection mechanism on suspension. * Removed IWinoSynchronizerFactory from UWP project. * Removal of background task service from core. * Delegating changes to UI and triggering new background synchronization. * Fix build error. * Moved core lib messages to Messaging project. * Better client-server communication. Handling of requests in the server. New synchronizer factory in the server. * WAM broker and MSAL token caching for OutlookAuthenticator. Handling account creation for Outlook. * WinoServerResponse basics. * Delegating protocol activation for Gmail authenticator. * Adding margin to searchbox to match action bar width. * Move libraries into lib folder. * Storing base64 encoded mime on draft creation instead of MimeMessage object. Fixes serialization/deserialization issue with S.T.Json * Scrollbar adjustments * WınoExpander for thread expander layout ıssue. * Handling synchronizer state changes. * Double init on background activation. * FIxing packaging issues and new Wino Mail launcher protocol for activation from full thrust process. * Remove debug deserialization. * Remove debug code. * Making sure the server connection is established when the app is launched. * Thrust -> Trust string replacement... * Rename package to Wino Mail * Enable translated values in the server. * Fixed an issue where toast activation can't find the clicked mail after the folder is initialized. * Revert debug code. * Change server background sync to every 3 minute and Inbox only synchronization. * Revert google auth changes. * App preferences page. * Changing tray icon visibility on preference change. * Start the server with invisible tray icon if set to invisible. * Reconnect button on the title bar. * Handling of toast actions. * Enable x86 build for server during packaging. * Get rid of old background tasks and v180 migration. * Terminate client when Exit clicked in server. * Introducing SynchronizationSource to prevent notifying UI after server tick synchronization. * Remove confirmAppClose restricted capability and unused debug code in manifest. * Closing the reconnect info popup when reconnect is clicked. * Custom RetryHandler for OutlookSynchronizer and separating client/server logs. * Running server on Windows startup. * Fix startup exe. * Fix for expander list view item paddings. * Force full sync on app launch instead of Inbox. * Fix draft creation. * Fix an issue with custom folder sync logic. * Reporting back account sync progress from server. * Fix sending drafts and missing notifications for imap. * Changing imap folder sync requirements. * Retain file count is set to 3. * Disabled swipe gestures temporarily due to native crash with SwipeControl * Save all attachments implementation. * Localization for save all attachments button. * Fix logging dates for logs. * Fixing ARM64 build. * Add ARM64 build config to packaging project. * Comment out OutOfProcPDB for ARM64. * Hnadling GONE response for Outlook folder synchronization.
2024-08-05 00:36:26 +02:00
using Wino.Core.Domain.Models.Reader;
using Wino.Core.UWP.Extensions;
2024-04-18 01:44:37 +02:00
using Wino.Mail.ViewModels.Data;
Full trust Wino Server implementation. (#295) * Separation of messages. Introducing Wino.Messages library. * Wino.Server and Wino.Packaging projects. Enabling full trust for UWP and app service connection manager basics. * Remove debug code. * Enable generating assembly info to deal with unsupported os platform warnings. * Fix server-client connection. * UIMessage communication. Single instancing for server and re-connection mechanism on suspension. * Removed IWinoSynchronizerFactory from UWP project. * Removal of background task service from core. * Delegating changes to UI and triggering new background synchronization. * Fix build error. * Moved core lib messages to Messaging project. * Better client-server communication. Handling of requests in the server. New synchronizer factory in the server. * WAM broker and MSAL token caching for OutlookAuthenticator. Handling account creation for Outlook. * WinoServerResponse basics. * Delegating protocol activation for Gmail authenticator. * Adding margin to searchbox to match action bar width. * Move libraries into lib folder. * Storing base64 encoded mime on draft creation instead of MimeMessage object. Fixes serialization/deserialization issue with S.T.Json * Scrollbar adjustments * WınoExpander for thread expander layout ıssue. * Handling synchronizer state changes. * Double init on background activation. * FIxing packaging issues and new Wino Mail launcher protocol for activation from full thrust process. * Remove debug deserialization. * Remove debug code. * Making sure the server connection is established when the app is launched. * Thrust -> Trust string replacement... * Rename package to Wino Mail * Enable translated values in the server. * Fixed an issue where toast activation can't find the clicked mail after the folder is initialized. * Revert debug code. * Change server background sync to every 3 minute and Inbox only synchronization. * Revert google auth changes. * App preferences page. * Changing tray icon visibility on preference change. * Start the server with invisible tray icon if set to invisible. * Reconnect button on the title bar. * Handling of toast actions. * Enable x86 build for server during packaging. * Get rid of old background tasks and v180 migration. * Terminate client when Exit clicked in server. * Introducing SynchronizationSource to prevent notifying UI after server tick synchronization. * Remove confirmAppClose restricted capability and unused debug code in manifest. * Closing the reconnect info popup when reconnect is clicked. * Custom RetryHandler for OutlookSynchronizer and separating client/server logs. * Running server on Windows startup. * Fix startup exe. * Fix for expander list view item paddings. * Force full sync on app launch instead of Inbox. * Fix draft creation. * Fix an issue with custom folder sync logic. * Reporting back account sync progress from server. * Fix sending drafts and missing notifications for imap. * Changing imap folder sync requirements. * Retain file count is set to 3. * Disabled swipe gestures temporarily due to native crash with SwipeControl * Save all attachments implementation. * Localization for save all attachments button. * Fix logging dates for logs. * Fixing ARM64 build. * Add ARM64 build config to packaging project. * Comment out OutOfProcPDB for ARM64. * Hnadling GONE response for Outlook folder synchronization.
2024-08-05 00:36:26 +02:00
using Wino.Messaging.Client.Mails;
using Wino.Messaging.Client.Shell;
2024-04-18 01:44:37 +02:00
using Wino.Views.Abstract;
2025-02-16 11:54:23 +01:00
namespace Wino.Views;
public sealed partial class ComposePage : ComposePageAbstract,
IRecipient<CreateNewComposeMailRequested>,
IRecipient<ApplicationThemeChanged>
2024-04-18 01:44:37 +02:00
{
public WebView2 GetWebView() => WebViewEditor.GetUnderlyingWebView();
2024-04-18 01:44:37 +02:00
private readonly List<IDisposable> _disposables = [];
2025-02-16 11:54:23 +01:00
private readonly SystemNavigationManagerPreview _navManagerPreview = SystemNavigationManagerPreview.GetForCurrentView();
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
public ComposePage()
{
InitializeComponent();
_navManagerPreview.CloseRequested += OnClose;
}
2025-02-16 11:54:23 +01:00
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)
2024-04-18 01:44:37 +02:00
{
await WebViewEditor.FocusEditorAsync(true);
2024-04-18 01:44:37 +02:00
}
2025-02-16 11:54:23 +01:00
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
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)
2024-04-18 01:44:37 +02:00
{
if (t.Sender is AutoSuggestBox senderBox && senderBox.Text.Length >= 2)
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
_ = ViewModel.ContactService.GetAddressInformationAsync(senderBox.Text).ContinueWith(x =>
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
_ = ViewModel.ExecuteUIThread(() =>
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
var addresses = x.Result;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
senderBox.ItemsSource = addresses;
2024-04-18 01:44:37 +02:00
});
2025-02-16 11:54:23 +01:00
});
2024-04-18 01:44:37 +02:00
}
2025-02-16 11:54:23 +01:00
}
});
}
2025-02-16 11:35:43 +01:00
2025-02-16 11:54:23 +01:00
private void OnComposeGridDragOver(object sender, DragEventArgs e)
{
ViewModel.IsDraggingOverComposerGrid = true;
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
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;
}
2025-02-16 11:35:43 +01:00
2025-02-16 11:54:23 +01:00
private void OnFileDropGridDragLeave(object sender, DragEventArgs e)
{
ViewModel.IsDraggingOverFilesDropZone = false;
}
private async void OnFileDropGridFileDropped(object sender, DragEventArgs e)
{
try
2024-05-22 02:10:14 +02:00
{
2025-02-16 11:54:23 +01:00
if (e.DataView.Contains(StandardDataFormats.StorageItems))
{
var storageItems = await e.DataView.GetStorageItemsAsync();
var files = storageItems.OfType<StorageFile>();
2024-05-22 02:10:14 +02:00
2025-02-16 11:54:23 +01:00
await AttachFiles(files);
}
2024-05-22 02:10:14 +02:00
}
2025-02-16 11:54:23 +01:00
// State should be reset even when an exception occurs, otherwise the UI will be stuck in a dragging state.
finally
2024-05-22 02:10:14 +02:00
{
2025-02-16 11:54:23 +01:00
ViewModel.IsDraggingOverComposerGrid = false;
ViewModel.IsDraggingOverFilesDropZone = false;
2024-05-22 02:10:14 +02:00
}
2025-02-16 11:54:23 +01:00
}
2024-05-22 02:10:14 +02:00
2025-02-16 11:54:23 +01:00
private void OnImageDropGridDragEnter(object sender, DragEventArgs e)
{
bool isValid = false;
if (e.DataView.Contains(StandardDataFormats.StorageItems))
2024-05-22 02:10:14 +02:00
{
2025-02-16 11:54:23 +01:00
// 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)
{
2025-02-16 11:54:23 +01:00
if (IsValidImageFile(file))
{
2025-02-16 11:54:23 +01:00
isValid = true;
}
}
}
2025-02-16 11:54:23 +01:00
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
{
2024-05-22 02:10:14 +02:00
if (e.DataView.Contains(StandardDataFormats.StorageItems))
{
2025-02-16 11:54:23 +01:00
var storageItems = await e.DataView.GetStorageItemsAsync();
var files = storageItems.OfType<StorageFile>();
var imagesInformation = new List<ImageInfo>();
2024-05-22 02:10:14 +02:00
foreach (var file in files)
{
if (IsValidImageFile(file))
{
2025-02-16 11:54:23 +01:00
imagesInformation.Add(new ImageInfo
{
Data = await GetDataURL(file),
Name = file.Name
});
}
}
await WebViewEditor.InsertImagesAsync(imagesInformation);
}
}
2025-02-16 11:54:23 +01:00
// State should be reset even when an exception occurs, otherwise the UI will be stuck in a dragging state.
finally
{
2025-02-16 11:54:23 +01:00
ViewModel.IsDraggingOverComposerGrid = false;
ViewModel.IsDraggingOverImagesDropZone = false;
2025-02-16 11:35:43 +01:00
}
2025-02-16 11:54:23 +01:00
static async Task<string> GetDataURL(StorageFile file)
2025-02-16 11:35:43 +01:00
{
2025-02-16 11:54:23 +01:00
return $"data:image/{file.FileType.Replace(".", "")};base64,{Convert.ToBase64String(await file.ToByteArrayAsync())}";
}
}
2024-05-22 02:10:14 +02:00
2025-02-16 11:54:23 +01:00
private async Task AttachFiles(IEnumerable<StorageFile> files)
{
if (files?.Any() != true) return;
2024-05-22 02:10:14 +02:00
2025-02-16 11:54:23 +01:00
// Convert files to MailAttachmentViewModel.
foreach (var file in files)
{
var sharedFile = await file.ToSharedFileAsync();
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
ViewModel.IncludedAttachments.Add(new MailAttachmentViewModel(sharedFile));
}
2025-02-16 11:54:23 +01:00
}
2024-04-18 01:44:37 +02:00
private static bool IsValidImageFile(StorageFile file)
2025-02-16 11:54:23 +01:00
{
string[] allowedTypes = [".jpg", ".jpeg", ".png"];
2025-02-16 11:54:23 +01:00
var fileType = file.FileType.ToLower();
2025-02-16 11:54:23 +01:00
return allowedTypes.Contains(fileType);
}
2025-02-16 11:54:23 +01:00
private void DisposeDisposables()
{
if (_disposables.Count != 0)
2025-02-16 11:54:23 +01:00
_disposables.ForEach(a => a.Dispose());
}
2024-04-18 01:44:37 +02:00
protected override void OnNavigatedTo(NavigationEventArgs e)
2025-02-16 11:54:23 +01:00
{
base.OnNavigatedTo(e);
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
FocusManager.GotFocus += GlobalFocusManagerGotFocus;
2024-04-18 01:44:37 +02:00
// TODO: disabled animation for now, since it's still not working properly.
//var anim = ConnectedAnimationService.GetForCurrentView().GetAnimation("WebViewConnectedAnimation");
//anim?.TryStart(GetWebView());
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
_disposables.Add(GetSuggestionBoxDisposable(ToBox));
_disposables.Add(GetSuggestionBoxDisposable(CCBox));
_disposables.Add(GetSuggestionBoxDisposable(BccBox));
_disposables.Add(WebViewEditor);
2024-04-18 01:44:37 +02:00
ViewModel.GetHTMLBodyFunction = WebViewEditor.GetHtmlBodyAsync;
2025-02-16 11:54:23 +01:00
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
async void IRecipient<CreateNewComposeMailRequested>.Receive(CreateNewComposeMailRequested message)
{
await WebViewEditor.RenderHtmlAsync(message.RenderModel.RenderHtml);
2025-02-16 11:54:23 +01:00
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
private void ShowCCBCCClicked(object sender, RoutedEventArgs e)
{
ViewModel.IsCCBCCVisible = true;
}
2025-02-16 11:35:43 +01:00
2025-02-16 11:54:23 +01:00
private async void TokenItemAdding(TokenizingTextBox sender, TokenItemAddingEventArgs args)
{
// Check is valid email.
if (!EmailValidator.Validate(args.TokenText))
{
args.Cancel = true;
ViewModel.NotifyInvalidEmail(args.TokenText);
2025-02-16 11:35:43 +01:00
2025-02-16 11:54:23 +01:00
return;
}
2025-02-16 11:35:43 +01:00
var deferral = args.GetDeferral();
2025-02-16 11:54:23 +01:00
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
};
2025-02-16 11:54:23 +01:00
if (addedItem == null)
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
args.Cancel = true;
ViewModel.NotifyAddressExists();
2024-04-18 01:44:37 +02:00
}
2025-02-16 11:54:23 +01:00
else
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
args.Item = addedItem;
2024-04-18 01:44:37 +02:00
}
deferral.Complete();
2025-02-16 11:54:23 +01:00
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
void IRecipient<ApplicationThemeChanged>.Receive(ApplicationThemeChanged message)
{
WebViewEditor.IsEditorDarkMode = message.IsUnderlyingThemeDark;
2025-02-16 11:54:23 +01:00
}
private void ImportanceClicked(object sender, RoutedEventArgs e)
{
ImportanceFlyout.Hide();
ImportanceSplitButton.IsChecked = true;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
if (sender is Button senderButton)
2025-02-16 11:35:43 +01:00
{
ViewModel.SelectedMessageImportance = (MessageImportance)senderButton.Tag;
2025-02-16 11:54:23 +01:00
((ImportanceSplitButton.Content as Viewbox).Child as SymbolIcon).Symbol = (senderButton.Content as SymbolIcon).Symbol;
}
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
private async void AddressBoxLostFocus(object sender, RoutedEventArgs e)
{
// Automatically add current text as item if it is valid mail address.
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
if (sender is TokenizingTextBox tokenizingTextBox)
{
if (tokenizingTextBox.Items.LastOrDefault() is not ITokenStringContainer info) return;
2025-02-16 11:35:43 +01:00
2025-02-16 11:54:23 +01:00
var currentText = info.Text;
2025-02-16 11:35:43 +01:00
2025-02-16 11:54:23 +01:00
if (!string.IsNullOrEmpty(currentText) && EmailValidator.Validate(currentText))
{
var addressCollection = tokenizingTextBox.Tag?.ToString() switch
{
"ToBox" => ViewModel.ToItems,
"CCBox" => ViewModel.CCItems,
"BCCBox" => ViewModel.BCCItems,
_ => null
};
2025-02-16 11:54:23 +01:00
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;
2024-04-18 01:44:37 +02:00
}
}
}
2025-02-16 11:54:23 +01:00
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
// 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.
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
private bool isInitialFocusHandled = false;
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
private void ComposerLoaded(object sender, RoutedEventArgs e)
{
ToBox.Focus(FocusState.Programmatic);
}
private void CCBBCGotFocus(object sender, RoutedEventArgs e)
{
if (!isInitialFocusHandled)
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
isInitialFocusHandled = true;
2024-04-18 01:44:37 +02:00
ToBox.Focus(FocusState.Programmatic);
}
2025-02-16 11:54:23 +01:00
}
2024-04-18 01:44:37 +02:00
2025-02-16 11:54:23 +01:00
protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
base.OnNavigatingFrom(e);
2024-08-18 22:45:23 +02:00
2025-02-16 11:54:23 +01:00
FocusManager.GotFocus -= GlobalFocusManagerGotFocus;
_navManagerPreview.CloseRequested -= OnClose;
await ViewModel.UpdateMimeChangesAsync();
2025-02-16 11:54:23 +01:00
DisposeDisposables();
}
private async void OnClose(object sender, SystemNavigationCloseRequestedPreviewEventArgs e)
{
var deferral = e.GetDeferral();
2025-02-16 11:54:23 +01:00
try
{
2025-02-16 11:54:23 +01:00
await ViewModel.UpdateMimeChangesAsync();
}
2025-02-16 11:54:23 +01:00
finally { deferral.Complete(); }
2024-04-18 01:44:37 +02:00
}
}