Skip to content

Commit

Permalink
Merge pull request #4 from XamDR/ver2
Browse files Browse the repository at this point in the history
Added better exception handling
  • Loading branch information
XamDR authored Jun 25, 2020
2 parents ea0e85d + 167d5d3 commit 1646ae8
Show file tree
Hide file tree
Showing 13 changed files with 111 additions and 75 deletions.
3 changes: 2 additions & 1 deletion ModernNotepad/App.xaml
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
<Application x:Class="ModernNotepad.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="http://schemas.modernwpf.com/2019">
xmlns:ui="http://schemas.modernwpf.com/2019"
DispatcherUnhandledException="Application_DispatcherUnhandledException">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
Expand Down
93 changes: 50 additions & 43 deletions ModernNotepad/App.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,77 +1,84 @@
using ModernNotepadLibrary.Core;
using ModernNotepadLibrary.Services;
using ModernNotepadLibrary.ViewModels;
using ModernNotepadLibrary.ViewModels;
using System;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Threading;

namespace ModernNotepad
{
public partial class App : Application
{
public MainViewModel MainViewModel { get; }

public App() => MainViewModel = (MainViewModel)Program.ServiceResolver.Create<INotifyPropertyChanged>();

protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var mainViewModel = CreateMainViewModel();
var mainWindow = mainViewModel.WindowService.CreateMainView(mainViewModel, typeof(MainViewModel));
mainViewModel.TextEditor.TextArea = mainWindow.TextArea;
base.OnStartup(e);
var mainWindow = MainViewModel.WindowService.CreateMainView(MainViewModel, typeof(MainViewModel));
MainViewModel.TextEditor.TextArea = mainWindow.TextArea;

if (!Directory.Exists(mainViewModel.SettingsManager.SettingsDirectoryPath))
if (!Directory.Exists(MainViewModel.SettingsManager.SettingsDirectoryPath))
{
mainViewModel.SettingsManager.SaveSettings(mainViewModel.SettingsViewModel.UserSettings);
MainViewModel.SettingsManager.SaveSettings(MainViewModel.SettingsViewModel.UserSettings);
}
ApplySettings(mainViewModel);
LoadLocale(mainViewModel);
mainViewModel.Title = mainViewModel.LocaleManager.LoadString("AppTitle");
mainViewModel.FilePath = mainViewModel.LocaleManager.LoadString("NewDocument");
ApplySettings(MainViewModel);
LoadLocale(MainViewModel);
MainViewModel.Title = MainViewModel.LocaleManager.LoadString("AppTitle");
MainViewModel.FilePath = MainViewModel.LocaleManager.LoadString("NewDocument");

if (e.Args.Length > 0)
{
mainViewModel.Title = Path.GetFileName(e.Args[0]);
mainViewModel.FilePath = Path.GetFullPath(e.Args[0]);
mainViewModel.TextEditor.TextArea.Text = File.ReadAllText(e.Args[0], Encoding.Default);
mainViewModel.TextEditor.SavedAsFile = true;
mainViewModel.SaveFileService.FileName = e.Args[0];
MainViewModel.Title = Path.GetFileName(e.Args[0]);
MainViewModel.FilePath = Path.GetFullPath(e.Args[0]);
MainViewModel.TextEditor.TextArea.Text = File.ReadAllText(e.Args[0], Encoding.Default);
MainViewModel.TextEditor.SavedAsFile = true;
MainViewModel.SaveFileService.FileName = e.Args[0];
}
}

private MainViewModel CreateMainViewModel()
{
var mainViewModel = new MainViewModel
{
DialogService = Program.ServiceResolver.Create<IContentDialogService>(),
WindowService = Program.ServiceResolver.Create<IWindowService>(),
OpenFileService = Program.ServiceResolver.Create<IOpenFileService>(),
SaveFileService = Program.ServiceResolver.Create<ISaveFileService>(),
ThemeManager = Program.ServiceResolver.Create<IApplicationThemeManager>(),
SettingsManager = Program.ServiceResolver.Create<ISettingsManager<UserSettings>>(),
LocaleManager = Program.ServiceResolver.Create<ILocaleManager>(),
PrintService = Program.ServiceResolver.Create<IPrintService>(),
};
return mainViewModel;
}

private void ApplySettings(MainViewModel mainViewModel)
private void ApplySettings(MainViewModel MainViewModel)
{
mainViewModel.SettingsViewModel.IsDarkThemeEnabled = mainViewModel.SettingsManager.LoadSettings().IsDarkThemeEnabled;
mainViewModel.SettingsViewModel.IsSpellCheckingEnabled = mainViewModel.SettingsManager.LoadSettings().IsSpellCheckingEnabled;
mainViewModel.SettingsViewModel.IsStatusBarVisible = mainViewModel.SettingsManager.LoadSettings().IsStatusBarVisible;
mainViewModel.SettingsViewModel.IsWordWrapEnabled = mainViewModel.SettingsManager.LoadSettings().IsWordWrapEnabled;
mainViewModel.ThemeManager.ChangeTheme(mainViewModel.SettingsViewModel.IsDarkThemeEnabled);
MainViewModel.SettingsViewModel.IsDarkThemeEnabled = MainViewModel.SettingsManager.LoadSettings().IsDarkThemeEnabled;
MainViewModel.SettingsViewModel.IsSpellCheckingEnabled = MainViewModel.SettingsManager.LoadSettings().IsSpellCheckingEnabled;
MainViewModel.SettingsViewModel.IsStatusBarVisible = MainViewModel.SettingsManager.LoadSettings().IsStatusBarVisible;
MainViewModel.SettingsViewModel.IsWordWrapEnabled = MainViewModel.SettingsManager.LoadSettings().IsWordWrapEnabled;
MainViewModel.ThemeManager.ChangeTheme(MainViewModel.SettingsViewModel.IsDarkThemeEnabled);
}

private void LoadLocale(MainViewModel mainViewModel)
private void LoadLocale(MainViewModel MainViewModel)
{
try
{
mainViewModel.LocaleManager.LoadStringResource(CultureInfo.CurrentUICulture.Name);
MainViewModel.LocaleManager.LoadStringResource(CultureInfo.CurrentUICulture.Name);
}
catch (Exception)
{
mainViewModel.LocaleManager.LoadStringResource("en-US");
MainViewModel.LocaleManager.LoadStringResource("en-US");
}
}

private void Application_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
WriteLogFile(e.Exception.ToString());
const long MB_OK = 0x0L, MB_ERROR = 0x10L;
var message = MainViewModel.LocaleManager.LoadString("ErrorMessage");
MessageBox(IntPtr.Zero, message, "Modern Notepad", (uint)(MB_OK | MB_ERROR));
e.Handled = true;
Current.Shutdown();
}

private void WriteLogFile(string message)
{
var logPath = @$"{Directory.GetCurrentDirectory()}\error.log";
File.WriteAllText(logPath, message);
}

[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int MessageBox(IntPtr hWnd, string lpText, string lpCaption, uint uType);
}
}
4 changes: 2 additions & 2 deletions ModernNotepad/Behaviors/PasteContentBehavior.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ protected override void OnDetaching()

private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
var viewModel = Application.Current.MainWindow.DataContext as MainViewModel;

var viewModel = Application.Current.MainWindow.DataContext as MainViewModel;
if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.V)
{
viewModel.Title = $"*{viewModel.Title.Replace("*", "")}";
Expand Down
10 changes: 7 additions & 3 deletions ModernNotepad/CustomControls/TextContextMenuEx.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using ModernWpf.Controls;
using ModernWpf.Controls.Primitives;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
Expand Down Expand Up @@ -76,8 +77,8 @@ public TextContextMenuEx()
{
Command = ApplicationCommands.SelectAll,
Icon = new SymbolIcon(Symbol.SelectAll),
InputGestureText = "Ctrl+A"
});
InputGestureText = GetDisplayStringForSelectAll()
});
}

#region UsingTextContextMenu
Expand Down Expand Up @@ -159,7 +160,7 @@ private static void OnSelectAllPreviewCanExecute(object sender, CanExecuteRouted

private static void OnDeletePreviewCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (sender is TextBox textBox && string.IsNullOrEmpty(textBox.SelectedText))
if (sender is TextBox textBox && string.IsNullOrEmpty(textBox.Text))
{
e.CanExecute = false;
e.Handled = true;
Expand Down Expand Up @@ -296,5 +297,8 @@ private void UpdateItems(Control target)
}
}
}

private string GetDisplayStringForSelectAll() => CultureInfo.CurrentUICulture.Name == "es-ES"
? "Ctrl+A" : ApplicationCommands.SelectAll.InputGestures.Cast<KeyGesture>().First().DisplayString;
}
}
Binary file added ModernNotepad/Fonts/SegMDL2.ttf
Binary file not shown.
2 changes: 2 additions & 0 deletions ModernNotepad/Locales/LocaleRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public LocaleRepository()
{ "AppDescription", EnglishDescription },
{ "AppTitle", "Untitled" },
{ "NewDocument", "New Document.txt" },
{ "ErrorMessage", "Error executing the program. Please send a copy of the file \"error\" to the email: [email protected]"},
};
SpanishDictionary = new Dictionary<string, string>
{
Expand All @@ -33,6 +34,7 @@ public LocaleRepository()
{ "AppDescription", SpanishDescription },
{ "AppTitle", "Sín título" },
{ "NewDocument", "Nuevo documento.txt" },
{ "ErrorMessage", "Error al ejecutar el programa. Por favor envíe una copia del archivo \"error\" al correo: [email protected]"},
};
Dictionaries = new Dictionary<string, Dictionary<string, string>>
{
Expand Down
2 changes: 1 addition & 1 deletion ModernNotepad/Locales/Strings_en-US.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -114,5 +114,5 @@
<sys:String x:Key="Proofing">Proofing</sys:String>
<sys:String x:Key="Ignore">Ignore</sys:String>
<!--#endregion-->

</ResourceDictionary>
2 changes: 1 addition & 1 deletion ModernNotepad/Locales/Strings_es-ES.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -113,5 +113,5 @@
<sys:String x:Key="Proofing">Revisión</sys:String>
<sys:String x:Key="Ignore">Omitir</sys:String>
<!--#endregion-->

</ResourceDictionary>
4 changes: 3 additions & 1 deletion ModernNotepad/ModernNotepad.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@
<Description>Modern Notepad is a modern and minimalist notepad application. It was developed using WPF on .Net Core 3.1.</Description>
<Product>Modern Notepad</Product>
<Platforms>AnyCPU;x64;x86</Platforms>
<Version>1.1.0</Version>
<Version>1.1.1</Version>
<ApplicationIcon>ModernNotepad.ico</ApplicationIcon>
<ApplicationManifest>app.manifest</ApplicationManifest>
<AssemblyName>Modern Notepad</AssemblyName>
</PropertyGroup>

<ItemGroup>
<None Remove="Fonts\SegMDL2.ttf" />
<None Remove="Images\SplashScreen.png" />
</ItemGroup>

Expand All @@ -35,6 +36,7 @@
</ItemGroup>

<ItemGroup>
<Resource Include="Fonts\SegMDL2.ttf" />
<Resource Include="Images\SplashScreen.png" />
<Resource Include="Locales\Strings_en-US.xaml">
<Generator>MSBuild:Compile</Generator>
Expand Down
11 changes: 7 additions & 4 deletions ModernNotepad/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
using ModernNotepadLibrary.Core;
using ModernNotepadLibrary.Helpers;
using ModernNotepadLibrary.Services;
using ModernNotepadLibrary.ViewModels;
using System;
using System.ComponentModel;
using System.Windows;

namespace ModernNotepad
Expand All @@ -15,11 +17,11 @@ class Program
[STAThread]
public static void Main()
{
ShowSplashScreen();
ShowSplashScreen();
RegisterServices();
var app = new App();
app.InitializeComponent();
RegisterServices();
app.Run();
app.Run();
}

private static void ShowSplashScreen()
Expand All @@ -38,7 +40,8 @@ private static void RegisterServices()
ServiceResolver.Register<IPrintService, PrintService>();
ServiceResolver.Register<ISaveFileService, SaveFileDialogService>();
ServiceResolver.Register<ISettingsManager<UserSettings>, SettingsManager>();
ServiceResolver.Register<IWindowService, WindowService>();
ServiceResolver.Register<IWindowService, WindowService>();
ServiceResolver.Register<INotifyPropertyChanged, MainViewModel>();
}
}
}
8 changes: 4 additions & 4 deletions ModernNotepad/Views/FindReplaceWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,16 @@

<TextBox Grid.Column="0" Grid.Row="0" Name="searchBox" Margin="10,5,10,5" MinWidth="200" MaxHeight="20"
ui:ControlHelper.PlaceholderText="{DynamicResource OriginalText}" Text="{Binding TextToFind}"/>
<Button Grid.Column="1" Grid.Row="0" Content="&#xE112;" FontFamily="Segoe MDL2 Assets"
<Button Grid.Column="1" Grid.Row="0" Content="&#xE112;" FontFamily="pack://application:,,,/Fonts/#SegoeDynamic"
Margin="5,0" ToolTip="{DynamicResource FindPreviousButtonTooltip}" Command="{Binding FindPreviousCommand}"/>
<Button Grid.Column="2" Grid.Row="0" Content="&#xE111;" FontFamily="Segoe MDL2 Assets"
<Button Grid.Column="2" Grid.Row="0" Content="&#xE111;" FontFamily="pack://application:,,,/Fonts/#SegoeDynamic"
ToolTip="{DynamicResource FindNextButtonTooltip}" Command="{Binding FindNextCommand}"/>

<TextBox Grid.Column="0" Grid.Row="1" Margin="10,5,10,5" MinWidth="200" MaxHeight="20"
ui:ControlHelper.PlaceholderText="{DynamicResource ReplaceWith}" Text="{Binding TextToReplace}"/>
<Button Grid.Column="1" Grid.Row="1" Content="&#xE8AB;" FontFamily="Segoe MDL2 Assets"
<Button Grid.Column="1" Grid.Row="1" Content="&#xE8AB;" FontFamily="pack://application:,,,/Fonts/#SegoeDynamic"
ToolTip="{DynamicResource ReplaceButtonTooltip}" Margin="5,0" Command="{Binding ReplaceTextCommand}"/>
<Button Grid.Column="2" Grid.Row="1" Content="&#xE7FD;" FontFamily="Segoe MDL2 Assets"
<Button Grid.Column="2" Grid.Row="1" Content="&#xE7FD;" FontFamily="pack://application:,,,/Fonts/#SegoeDynamic"
ToolTip="{DynamicResource ReplaceAllButtonTooltip}" Command="{Binding ReplaceAllTextCommand}"/>

<CheckBox Grid.Column="0" Grid.Row="2" Margin="10,0,0,0" Grid.ColumnSpan="2" Content="{DynamicResource MatchCase}"
Expand Down
6 changes: 3 additions & 3 deletions ModernNotepad/Views/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
<ui:CommandBar.Content>
<ui:AppBarButton Command="{Binding OpenNewWindowCommand}" ToolTip="{DynamicResource NewWindowToolTip}">
<ui:AppBarButton.Icon>
<ui:FontIcon FontFamily="Segoe MDL2 Assets" Glyph="&#xE109;"/>
<ui:FontIcon FontFamily="pack://application:,,,/Fonts/#SegoeDynamic" Glyph="&#xE109;"/>
</ui:AppBarButton.Icon>
</ui:AppBarButton>
</ui:CommandBar.Content>
Expand All @@ -70,7 +70,7 @@
<ui:AppBarButton Label="{DynamicResource SaveAs}" Command="{Binding TextEditor.SaveFileAsCommand}"
ToolTip="{DynamicResource SaveAsToolTip}" ToolTipService.Placement="Left">
<ui:AppBarButton.Icon>
<ui:FontIcon FontFamily="Segoe MDL2 Assets" Glyph="&#xE792;"/>
<ui:FontIcon FontFamily="pack://application:,,,/Fonts/#SegoeDynamic" Glyph="&#xE792;"/>
</ui:AppBarButton.Icon>
</ui:AppBarButton>
<ui:AppBarButton Label="{DynamicResource PrintPreview}" ToolTip="{DynamicResource PrintPreviewToolTip}"
Expand All @@ -86,7 +86,7 @@
<ui:AppBarButton Label="{DynamicResource AboutModernNotepad}" Command="{Binding ShowAboutWindowCommand}"
ToolTip="{DynamicResource AboutToolTip}" ToolTipService.Placement="Left">
<ui:AppBarButton.Icon>
<ui:FontIcon FontFamily="Segoe MDL2 Assets" Glyph="&#xE946;"/>
<ui:FontIcon FontFamily="pack://application:,,,/Fonts/#SegoeDynamic" Glyph="&#xE946;"/>
</ui:AppBarButton.Icon>
</ui:AppBarButton>
<ui:AppBarSeparator/>
Expand Down
41 changes: 29 additions & 12 deletions ModernNotepadLibrary/ViewModels/MainViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using ModernNotepadLibrary.Core;
using ModernNotepadLibrary.Helpers;
using ModernNotepadLibrary.Services;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Input;
Expand All @@ -12,8 +11,26 @@ public class MainViewModel : BaseViewModel
{
private bool closing = false; //we need to use this variable because ContentDialog.ShowAsync() is an async method.

public MainViewModel()
public MainViewModel
(
IContentDialogService dialogService,
ILocaleManager localeManager,
IOpenFileService openFileService,
IPrintService printService,
ISaveFileService saveFileService,
ISettingsManager<UserSettings> settingsManager,
IWindowService windowService,
IApplicationThemeManager themeManager
)
{
DialogService = dialogService;
LocaleManager = localeManager;
OpenFileService = openFileService;
PrintService = printService;
SaveFileService = saveFileService;
SettingsManager = settingsManager;
WindowService = windowService;
ThemeManager = themeManager;
TextEditor = new TextEditor(this);
AboutViewModel = new AboutViewModel(this);
FindReplaceViewModel = new FindReplaceViewModel(this);
Expand All @@ -31,17 +48,21 @@ public MainViewModel()

public TextEditor TextEditor { get; }

public IContentDialogService DialogService { get; set; }
public IContentDialogService DialogService { get; }

public ILocaleManager LocaleManager { get; set; }
public ILocaleManager LocaleManager { get; }

public IOpenFileService OpenFileService { get; set; }
public IOpenFileService OpenFileService { get; }

public IPrintService PrintService { get; set; }
public IPrintService PrintService { get; }

public ISaveFileService SaveFileService { get; set; }
public ISaveFileService SaveFileService { get; }

public ISettingsManager<UserSettings> SettingsManager { get; set; }
public ISettingsManager<UserSettings> SettingsManager { get; }

public IApplicationThemeManager ThemeManager { get; }

public IWindowService WindowService { get; }

public string filePath;

Expand Down Expand Up @@ -83,10 +104,6 @@ public string Title
set => Set(ref title, value);
}

public IWindowService WindowService { get; set; }

public IApplicationThemeManager ThemeManager { get; set; }

public ICommand ClosingWindowCommand => new DelegateCommand<CancelEventArgs>(CloseWindow);

public ICommand CloseWindowCommand => new DelegateCommand(CloseWindow);
Expand Down

0 comments on commit 1646ae8

Please sign in to comment.