diff --git a/.gitignore b/.gitignore index b61ddc5..9491a2f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,363 @@ -################################################################################ -# This .gitignore file was automatically created by Microsoft(R) Visual Studio. -################################################################################ - -/Fastedit/AppPackages -/Fastedit/BundleArtifacts -/Fastedit/obj/x64/Release -*.xml -/.vs/Fastedit -/Fastedit/Fastedit.csproj.user -/TabGroups.txt -/Fastedit/bin/x64/Release +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/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/ +[Oo]ut/ +[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 Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# 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 +*.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 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/ + +# 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 \ No newline at end of file diff --git a/Fastedit.sln b/Fastedit.sln index 8d9d785..7f4ef86 100644 --- a/Fastedit.sln +++ b/Fastedit.sln @@ -1,9 +1,9 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 -VisualStudioVersion = 17.0.32014.148 +VisualStudioVersion = 17.3.32929.385 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Fastedit", "Fastedit\Fastedit.csproj", "{EFBC8478-DC04-4052-9C14-B98673911134}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Fastedit", "Fastedit\Fastedit.csproj", "{14A97288-EEEA-4786-8D35-704B6244C05A}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -17,35 +17,35 @@ Global Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {EFBC8478-DC04-4052-9C14-B98673911134}.Debug|ARM.ActiveCfg = Debug|ARM - {EFBC8478-DC04-4052-9C14-B98673911134}.Debug|ARM.Build.0 = Debug|ARM - {EFBC8478-DC04-4052-9C14-B98673911134}.Debug|ARM.Deploy.0 = Debug|ARM - {EFBC8478-DC04-4052-9C14-B98673911134}.Debug|ARM64.ActiveCfg = Debug|ARM64 - {EFBC8478-DC04-4052-9C14-B98673911134}.Debug|ARM64.Build.0 = Debug|ARM64 - {EFBC8478-DC04-4052-9C14-B98673911134}.Debug|ARM64.Deploy.0 = Debug|ARM64 - {EFBC8478-DC04-4052-9C14-B98673911134}.Debug|x64.ActiveCfg = Debug|x64 - {EFBC8478-DC04-4052-9C14-B98673911134}.Debug|x64.Build.0 = Debug|x64 - {EFBC8478-DC04-4052-9C14-B98673911134}.Debug|x64.Deploy.0 = Debug|x64 - {EFBC8478-DC04-4052-9C14-B98673911134}.Debug|x86.ActiveCfg = Debug|x86 - {EFBC8478-DC04-4052-9C14-B98673911134}.Debug|x86.Build.0 = Debug|x86 - {EFBC8478-DC04-4052-9C14-B98673911134}.Debug|x86.Deploy.0 = Debug|x86 - {EFBC8478-DC04-4052-9C14-B98673911134}.Release|ARM.ActiveCfg = Release|ARM - {EFBC8478-DC04-4052-9C14-B98673911134}.Release|ARM.Build.0 = Release|ARM - {EFBC8478-DC04-4052-9C14-B98673911134}.Release|ARM.Deploy.0 = Release|ARM - {EFBC8478-DC04-4052-9C14-B98673911134}.Release|ARM64.ActiveCfg = Release|ARM64 - {EFBC8478-DC04-4052-9C14-B98673911134}.Release|ARM64.Build.0 = Release|ARM64 - {EFBC8478-DC04-4052-9C14-B98673911134}.Release|ARM64.Deploy.0 = Release|ARM64 - {EFBC8478-DC04-4052-9C14-B98673911134}.Release|x64.ActiveCfg = Release|x64 - {EFBC8478-DC04-4052-9C14-B98673911134}.Release|x64.Build.0 = Release|x64 - {EFBC8478-DC04-4052-9C14-B98673911134}.Release|x64.Deploy.0 = Release|x64 - {EFBC8478-DC04-4052-9C14-B98673911134}.Release|x86.ActiveCfg = Release|x86 - {EFBC8478-DC04-4052-9C14-B98673911134}.Release|x86.Build.0 = Release|x86 - {EFBC8478-DC04-4052-9C14-B98673911134}.Release|x86.Deploy.0 = Release|x86 + {14A97288-EEEA-4786-8D35-704B6244C05A}.Debug|ARM.ActiveCfg = Debug|ARM + {14A97288-EEEA-4786-8D35-704B6244C05A}.Debug|ARM.Build.0 = Debug|ARM + {14A97288-EEEA-4786-8D35-704B6244C05A}.Debug|ARM.Deploy.0 = Debug|ARM + {14A97288-EEEA-4786-8D35-704B6244C05A}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {14A97288-EEEA-4786-8D35-704B6244C05A}.Debug|ARM64.Build.0 = Debug|ARM64 + {14A97288-EEEA-4786-8D35-704B6244C05A}.Debug|ARM64.Deploy.0 = Debug|ARM64 + {14A97288-EEEA-4786-8D35-704B6244C05A}.Debug|x64.ActiveCfg = Debug|x64 + {14A97288-EEEA-4786-8D35-704B6244C05A}.Debug|x64.Build.0 = Debug|x64 + {14A97288-EEEA-4786-8D35-704B6244C05A}.Debug|x64.Deploy.0 = Debug|x64 + {14A97288-EEEA-4786-8D35-704B6244C05A}.Debug|x86.ActiveCfg = Debug|x86 + {14A97288-EEEA-4786-8D35-704B6244C05A}.Debug|x86.Build.0 = Debug|x86 + {14A97288-EEEA-4786-8D35-704B6244C05A}.Debug|x86.Deploy.0 = Debug|x86 + {14A97288-EEEA-4786-8D35-704B6244C05A}.Release|ARM.ActiveCfg = Release|ARM + {14A97288-EEEA-4786-8D35-704B6244C05A}.Release|ARM.Build.0 = Release|ARM + {14A97288-EEEA-4786-8D35-704B6244C05A}.Release|ARM.Deploy.0 = Release|ARM + {14A97288-EEEA-4786-8D35-704B6244C05A}.Release|ARM64.ActiveCfg = Release|ARM64 + {14A97288-EEEA-4786-8D35-704B6244C05A}.Release|ARM64.Build.0 = Release|ARM64 + {14A97288-EEEA-4786-8D35-704B6244C05A}.Release|ARM64.Deploy.0 = Release|ARM64 + {14A97288-EEEA-4786-8D35-704B6244C05A}.Release|x64.ActiveCfg = Release|x64 + {14A97288-EEEA-4786-8D35-704B6244C05A}.Release|x64.Build.0 = Release|x64 + {14A97288-EEEA-4786-8D35-704B6244C05A}.Release|x64.Deploy.0 = Release|x64 + {14A97288-EEEA-4786-8D35-704B6244C05A}.Release|x86.ActiveCfg = Release|x86 + {14A97288-EEEA-4786-8D35-704B6244C05A}.Release|x86.Build.0 = Release|x86 + {14A97288-EEEA-4786-8D35-704B6244C05A}.Release|x86.Deploy.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {AE7B0B6B-D9CC-473E-97A2-C60BC5F2A8C8} + SolutionGuid = {F36371CE-391D-4E29-8968-2668811F1D78} EndGlobalSection EndGlobal diff --git a/Fastedit/App.xaml b/Fastedit/App.xaml index 0f5adc9..16c3b94 100644 --- a/Fastedit/App.xaml +++ b/Fastedit/App.xaml @@ -2,14 +2,260 @@ x:Class="Fastedit.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" - xmlns:muxc="using:Microsoft.UI.Xaml.Controls"> + xmlns:local="using:Fastedit" + xmlns:controls="using:Microsoft.UI.Xaml.Controls"> - - - - + + + + + + + + - - - diff --git a/Fastedit/App.xaml.cs b/Fastedit/App.xaml.cs index 3964a4c..32ec959 100644 --- a/Fastedit/App.xaml.cs +++ b/Fastedit/App.xaml.cs @@ -1,31 +1,28 @@ -using Fastedit.Core.Tab; -using System; +using System; using Windows.ApplicationModel.Activation; -using Windows.UI.Popups; -using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace Fastedit { + /// + /// Provides application-specific behavior to supplement the default Application class. + /// sealed partial class App : Application { + /// + /// Initializes the singleton application object. This is the first line of authored code + /// executed, and as such is the logical equivalent of main() or WinMain(). + /// public App() { this.InitializeComponent(); - + this.Suspending += OnSuspending; SetSystemGroupAsync(); - Suspending += App_Suspending; - //this.UnhandledException += (sender, e) => - //{ - // e.Handled = true; - // System.Diagnostics.Debug.WriteLine(e.Exception); - //}; } - public int MainViewId = -1; - + //Enable recent files in the taskbar rightclick menu private async void SetSystemGroupAsync() { var jumpList = await Windows.UI.StartScreen.JumpList.LoadCurrentAsync(); @@ -44,52 +41,25 @@ private Frame CreateRootFrame() rootFrame.NavigationFailed += OnNavigationFailed; // Place the frame in the current Window Window.Current.Content = rootFrame; - MainViewId = ApplicationView.GetForCurrentView().Id; } return rootFrame; } - private void App_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e) - { - var deferral = e.SuspendingOperation.GetDeferral(); - deferral.Complete(); - } - protected override void OnActivated(IActivatedEventArgs args) { - Frame rootFrame = CreateRootFrame(); - - if (args.Kind == ActivationKind.CommandLineLaunch) - { - if (args is CommandLineActivatedEventArgs commandLine) - { - rootFrame.Navigate(typeof(MainPage), new CommandLineLaunchNavigationParameter - { - Arguments = commandLine.Operation.Arguments, - CurrentDirectoryPath = commandLine.Operation.CurrentDirectoryPath - }); - } - else - { - rootFrame.Navigate(typeof(MainPage)); - } - } - + CreateRootFrame().Navigate(typeof(MainPage), args); Window.Current.Activate(); } + protected override void OnFileActivated(FileActivatedEventArgs args) { - Frame rootFrame = CreateRootFrame(); - - rootFrame.Navigate(typeof(MainPage), args); + CreateRootFrame().Navigate(typeof(MainPage), args); Window.Current.Activate(); base.OnFileActivated(args); } protected override void OnLaunched(LaunchActivatedEventArgs args) { - AppSettings appsettings = new AppSettings(); - Frame rootFrame = CreateRootFrame(); - rootFrame.Navigate(typeof(MainPage)); + CreateRootFrame().Navigate(typeof(MainPage)); Window.Current.Activate(); } @@ -97,5 +67,10 @@ void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } + private void OnSuspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e) + { + var deferral = e.SuspendingOperation.GetDeferral(); + deferral.Complete(); + } } } diff --git a/Fastedit/Assets/App_Icon/App_Icon.svg b/Fastedit/Assets/AppIcon/App_Icon.svg similarity index 100% rename from Fastedit/Assets/App_Icon/App_Icon.svg rename to Fastedit/Assets/AppIcon/App_Icon.svg diff --git a/Fastedit/Assets/AppIcon/Generated/BadgeLogo.scale-100.png b/Fastedit/Assets/AppIcon/Generated/BadgeLogo.scale-100.png new file mode 100644 index 0000000..b4783d3 Binary files /dev/null and b/Fastedit/Assets/AppIcon/Generated/BadgeLogo.scale-100.png differ diff --git a/Fastedit/Assets/AppIcon/Generated/BadgeLogo.scale-125.png b/Fastedit/Assets/AppIcon/Generated/BadgeLogo.scale-125.png new file mode 100644 index 0000000..85ca11e Binary files /dev/null and b/Fastedit/Assets/AppIcon/Generated/BadgeLogo.scale-125.png differ diff --git a/Fastedit/Assets/AppIcon/Generated/BadgeLogo.scale-150.png b/Fastedit/Assets/AppIcon/Generated/BadgeLogo.scale-150.png new file mode 100644 index 0000000..81b62fa Binary files /dev/null and b/Fastedit/Assets/AppIcon/Generated/BadgeLogo.scale-150.png differ diff --git a/Fastedit/Assets/AppIcon/Generated/BadgeLogo.scale-200.png b/Fastedit/Assets/AppIcon/Generated/BadgeLogo.scale-200.png new file mode 100644 index 0000000..cb71889 Binary files /dev/null and b/Fastedit/Assets/AppIcon/Generated/BadgeLogo.scale-200.png differ diff --git a/Fastedit/Assets/AppIcon/Generated/BadgeLogo.scale-400.png b/Fastedit/Assets/AppIcon/Generated/BadgeLogo.scale-400.png new file mode 100644 index 0000000..b05e613 Binary files /dev/null and b/Fastedit/Assets/AppIcon/Generated/BadgeLogo.scale-400.png differ diff --git a/Fastedit/Assets/App_Icon/Generated/LargeTile.scale-100.png b/Fastedit/Assets/AppIcon/Generated/LargeTile.scale-100.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/LargeTile.scale-100.png rename to Fastedit/Assets/AppIcon/Generated/LargeTile.scale-100.png diff --git a/Fastedit/Assets/App_Icon/Generated/LargeTile.scale-125.png b/Fastedit/Assets/AppIcon/Generated/LargeTile.scale-125.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/LargeTile.scale-125.png rename to Fastedit/Assets/AppIcon/Generated/LargeTile.scale-125.png diff --git a/Fastedit/Assets/App_Icon/Generated/LargeTile.scale-150.png b/Fastedit/Assets/AppIcon/Generated/LargeTile.scale-150.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/LargeTile.scale-150.png rename to Fastedit/Assets/AppIcon/Generated/LargeTile.scale-150.png diff --git a/Fastedit/Assets/App_Icon/Generated/LargeTile.scale-200.png b/Fastedit/Assets/AppIcon/Generated/LargeTile.scale-200.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/LargeTile.scale-200.png rename to Fastedit/Assets/AppIcon/Generated/LargeTile.scale-200.png diff --git a/Fastedit/Assets/App_Icon/Generated/LargeTile.scale-400.png b/Fastedit/Assets/AppIcon/Generated/LargeTile.scale-400.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/LargeTile.scale-400.png rename to Fastedit/Assets/AppIcon/Generated/LargeTile.scale-400.png diff --git a/Fastedit/Assets/App_Icon/Generated/SmallTile.scale-100.png b/Fastedit/Assets/AppIcon/Generated/SmallTile.scale-100.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/SmallTile.scale-100.png rename to Fastedit/Assets/AppIcon/Generated/SmallTile.scale-100.png diff --git a/Fastedit/Assets/App_Icon/Generated/SmallTile.scale-125.png b/Fastedit/Assets/AppIcon/Generated/SmallTile.scale-125.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/SmallTile.scale-125.png rename to Fastedit/Assets/AppIcon/Generated/SmallTile.scale-125.png diff --git a/Fastedit/Assets/App_Icon/Generated/SmallTile.scale-150.png b/Fastedit/Assets/AppIcon/Generated/SmallTile.scale-150.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/SmallTile.scale-150.png rename to Fastedit/Assets/AppIcon/Generated/SmallTile.scale-150.png diff --git a/Fastedit/Assets/App_Icon/Generated/SmallTile.scale-200.png b/Fastedit/Assets/AppIcon/Generated/SmallTile.scale-200.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/SmallTile.scale-200.png rename to Fastedit/Assets/AppIcon/Generated/SmallTile.scale-200.png diff --git a/Fastedit/Assets/App_Icon/Generated/SmallTile.scale-400.png b/Fastedit/Assets/AppIcon/Generated/SmallTile.scale-400.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/SmallTile.scale-400.png rename to Fastedit/Assets/AppIcon/Generated/SmallTile.scale-400.png diff --git a/Fastedit/Assets/App_Icon/Generated/SplashScreen.scale-100.png b/Fastedit/Assets/AppIcon/Generated/SplashScreen.scale-100.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/SplashScreen.scale-100.png rename to Fastedit/Assets/AppIcon/Generated/SplashScreen.scale-100.png diff --git a/Fastedit/Assets/App_Icon/Generated/SplashScreen.scale-125.png b/Fastedit/Assets/AppIcon/Generated/SplashScreen.scale-125.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/SplashScreen.scale-125.png rename to Fastedit/Assets/AppIcon/Generated/SplashScreen.scale-125.png diff --git a/Fastedit/Assets/App_Icon/Generated/SplashScreen.scale-150.png b/Fastedit/Assets/AppIcon/Generated/SplashScreen.scale-150.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/SplashScreen.scale-150.png rename to Fastedit/Assets/AppIcon/Generated/SplashScreen.scale-150.png diff --git a/Fastedit/Assets/App_Icon/Generated/SplashScreen.scale-200.png b/Fastedit/Assets/AppIcon/Generated/SplashScreen.scale-200.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/SplashScreen.scale-200.png rename to Fastedit/Assets/AppIcon/Generated/SplashScreen.scale-200.png diff --git a/Fastedit/Assets/App_Icon/Generated/SplashScreen.scale-400.png b/Fastedit/Assets/AppIcon/Generated/SplashScreen.scale-400.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/SplashScreen.scale-400.png rename to Fastedit/Assets/AppIcon/Generated/SplashScreen.scale-400.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square150x150Logo.scale-100.png b/Fastedit/Assets/AppIcon/Generated/Square150x150Logo.scale-100.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square150x150Logo.scale-100.png rename to Fastedit/Assets/AppIcon/Generated/Square150x150Logo.scale-100.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square150x150Logo.scale-125.png b/Fastedit/Assets/AppIcon/Generated/Square150x150Logo.scale-125.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square150x150Logo.scale-125.png rename to Fastedit/Assets/AppIcon/Generated/Square150x150Logo.scale-125.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square150x150Logo.scale-150.png b/Fastedit/Assets/AppIcon/Generated/Square150x150Logo.scale-150.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square150x150Logo.scale-150.png rename to Fastedit/Assets/AppIcon/Generated/Square150x150Logo.scale-150.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square150x150Logo.scale-200.png b/Fastedit/Assets/AppIcon/Generated/Square150x150Logo.scale-200.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square150x150Logo.scale-200.png rename to Fastedit/Assets/AppIcon/Generated/Square150x150Logo.scale-200.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square150x150Logo.scale-400.png b/Fastedit/Assets/AppIcon/Generated/Square150x150Logo.scale-400.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square150x150Logo.scale-400.png rename to Fastedit/Assets/AppIcon/Generated/Square150x150Logo.scale-400.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-lightunplated_targetsize-16.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-lightunplated_targetsize-16.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-lightunplated_targetsize-16.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-lightunplated_targetsize-16.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-lightunplated_targetsize-24.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-lightunplated_targetsize-24.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-lightunplated_targetsize-24.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-lightunplated_targetsize-24.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-lightunplated_targetsize-256.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-lightunplated_targetsize-256.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-lightunplated_targetsize-256.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-lightunplated_targetsize-256.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-lightunplated_targetsize-32.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-lightunplated_targetsize-32.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-lightunplated_targetsize-32.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-lightunplated_targetsize-32.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-lightunplated_targetsize-48.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-lightunplated_targetsize-48.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-lightunplated_targetsize-48.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-lightunplated_targetsize-48.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-unplated_targetsize-16.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-unplated_targetsize-16.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-unplated_targetsize-16.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-unplated_targetsize-16.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-unplated_targetsize-24.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-unplated_targetsize-24.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-unplated_targetsize-24.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-unplated_targetsize-24.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-unplated_targetsize-256.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-unplated_targetsize-256.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-unplated_targetsize-256.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-unplated_targetsize-256.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-unplated_targetsize-32.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-unplated_targetsize-32.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-unplated_targetsize-32.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-unplated_targetsize-32.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-unplated_targetsize-48.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-unplated_targetsize-48.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.altform-unplated_targetsize-48.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.altform-unplated_targetsize-48.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.scale-100.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.scale-100.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.scale-100.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.scale-100.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.scale-125.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.scale-125.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.scale-125.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.scale-125.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.scale-150.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.scale-150.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.scale-150.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.scale-150.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.scale-200.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.scale-200.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.scale-200.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.scale-200.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.scale-400.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.scale-400.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.scale-400.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.scale-400.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.targetsize-16.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.targetsize-16.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.targetsize-16.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.targetsize-16.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.targetsize-24.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.targetsize-24.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.targetsize-24.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.targetsize-24.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.targetsize-256.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.targetsize-256.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.targetsize-256.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.targetsize-256.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.targetsize-32.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.targetsize-32.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.targetsize-32.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.targetsize-32.png diff --git a/Fastedit/Assets/App_Icon/Generated/Square44x44Logo.targetsize-48.png b/Fastedit/Assets/AppIcon/Generated/Square44x44Logo.targetsize-48.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Square44x44Logo.targetsize-48.png rename to Fastedit/Assets/AppIcon/Generated/Square44x44Logo.targetsize-48.png diff --git a/Fastedit/Assets/App_Icon/Generated/StoreLogo.scale-100.png b/Fastedit/Assets/AppIcon/Generated/StoreLogo.scale-100.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/StoreLogo.scale-100.png rename to Fastedit/Assets/AppIcon/Generated/StoreLogo.scale-100.png diff --git a/Fastedit/Assets/App_Icon/Generated/StoreLogo.scale-125.png b/Fastedit/Assets/AppIcon/Generated/StoreLogo.scale-125.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/StoreLogo.scale-125.png rename to Fastedit/Assets/AppIcon/Generated/StoreLogo.scale-125.png diff --git a/Fastedit/Assets/App_Icon/Generated/StoreLogo.scale-150.png b/Fastedit/Assets/AppIcon/Generated/StoreLogo.scale-150.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/StoreLogo.scale-150.png rename to Fastedit/Assets/AppIcon/Generated/StoreLogo.scale-150.png diff --git a/Fastedit/Assets/App_Icon/Generated/StoreLogo.scale-200.png b/Fastedit/Assets/AppIcon/Generated/StoreLogo.scale-200.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/StoreLogo.scale-200.png rename to Fastedit/Assets/AppIcon/Generated/StoreLogo.scale-200.png diff --git a/Fastedit/Assets/App_Icon/Generated/StoreLogo.scale-400.png b/Fastedit/Assets/AppIcon/Generated/StoreLogo.scale-400.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/StoreLogo.scale-400.png rename to Fastedit/Assets/AppIcon/Generated/StoreLogo.scale-400.png diff --git a/Fastedit/Assets/App_Icon/Generated/Wide310x150Logo.scale-100.png b/Fastedit/Assets/AppIcon/Generated/Wide310x150Logo.scale-100.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Wide310x150Logo.scale-100.png rename to Fastedit/Assets/AppIcon/Generated/Wide310x150Logo.scale-100.png diff --git a/Fastedit/Assets/App_Icon/Generated/Wide310x150Logo.scale-125.png b/Fastedit/Assets/AppIcon/Generated/Wide310x150Logo.scale-125.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Wide310x150Logo.scale-125.png rename to Fastedit/Assets/AppIcon/Generated/Wide310x150Logo.scale-125.png diff --git a/Fastedit/Assets/App_Icon/Generated/Wide310x150Logo.scale-150.png b/Fastedit/Assets/AppIcon/Generated/Wide310x150Logo.scale-150.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Wide310x150Logo.scale-150.png rename to Fastedit/Assets/AppIcon/Generated/Wide310x150Logo.scale-150.png diff --git a/Fastedit/Assets/App_Icon/Generated/Wide310x150Logo.scale-200.png b/Fastedit/Assets/AppIcon/Generated/Wide310x150Logo.scale-200.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Wide310x150Logo.scale-200.png rename to Fastedit/Assets/AppIcon/Generated/Wide310x150Logo.scale-200.png diff --git a/Fastedit/Assets/App_Icon/Generated/Wide310x150Logo.scale-400.png b/Fastedit/Assets/AppIcon/Generated/Wide310x150Logo.scale-400.png similarity index 100% rename from Fastedit/Assets/App_Icon/Generated/Wide310x150Logo.scale-400.png rename to Fastedit/Assets/AppIcon/Generated/Wide310x150Logo.scale-400.png diff --git a/Fastedit/Assets/App_Icon/Icon.png b/Fastedit/Assets/AppIcon/Icon.png similarity index 100% rename from Fastedit/Assets/App_Icon/Icon.png rename to Fastedit/Assets/AppIcon/Icon.png diff --git a/Fastedit/Assets/Designs/Acrylic-Blue.fasteditdesign b/Fastedit/Assets/Designs/Acrylic-Blue.fasteditdesign deleted file mode 100644 index 6dac12b..0000000 --- a/Fastedit/Assets/Designs/Acrylic-Blue.fasteditdesign +++ /dev/null @@ -1,31 +0,0 @@ -ThemeIndex=0 -TextSelectionColorIndex=2 -TextColorIndex=2 -TextBackgroundColorIndex=1 -TextColor=#FF004BFF -TextBackgroundColor=#00FFFFFF -TextSelectionColor=#FF004BFF -LineNumberBackgroundColorIndex=1 -LineNumberBackgroundColor=#00FFFFFF -LineNumberForegroundColorIndex=2 -LineNumberForegroundColor=#FF004BFF -AppBackgroundColorIndex=2 -AppBackgroundColor=#66002580 -TitleBarBackgroundColor=#330031A6 -TitleBarBackgroundColorIndex=2 -TabColorNotFocusedIndex=1 -TabColorFocusedIndex=2 -TabColorFocused=#FF0031A6 -TabColorNotFocused=#00FFFFFF -DialogBackgroundColor=#EE001A59 -DialogBackgroundColorIndex=2 -StatusbarForegroundColorIndex=2 -StatusbarBackgroundColorIndex=1 -StatusbarForegroundColor=#FF004BFF -StatusbarBackgroundColor=#00FFFFFF -UseMica=False -AcrylicEnabled=True -LineHighlighterBackground=#00000000 -LineHighlighterForeground=#FF0035B3 -LineHighlighterForegroundIndex=2 -LineHighlighterBackgroundIndex=2 diff --git a/Fastedit/Assets/Designs/Acrylic-Dark.fasteditdesign b/Fastedit/Assets/Designs/Acrylic-Dark.fasteditdesign deleted file mode 100644 index 3ff8939..0000000 --- a/Fastedit/Assets/Designs/Acrylic-Dark.fasteditdesign +++ /dev/null @@ -1,31 +0,0 @@ -ThemeIndex=2 -TextSelectionColorIndex=2 -TextColorIndex=2 -TextBackgroundColorIndex=1 -TextColor=#FFFFFFFF -TextBackgroundColor=#00FFFFFF -TextSelectionColor=#FFC4C4C4 -LineNumberBackgroundColorIndex=1 -LineNumberBackgroundColor=#00FFFFFF -LineNumberForegroundColorIndex=2 -LineNumberForegroundColor=#FFFFFFFF -AppBackgroundColorIndex=2 -AppBackgroundColor=#401A1A1A -TitleBarBackgroundColor=#4D3B3B3B -TitleBarBackgroundColorIndex=2 -TabColorNotFocusedIndex=1 -TabColorFocusedIndex=2 -TabColorFocused=#CC1A1A1A -TabColorNotFocused=#00FFFFFF -DialogBackgroundColor=#EE262626 -DialogBackgroundColorIndex=2 -StatusbarForegroundColorIndex=2 -StatusbarBackgroundColorIndex=1 -StatusbarForegroundColor=#FFFFFFFF -StatusbarBackgroundColor=#00FFFFFF -UseMica=False -AcrylicEnabled=True -LineHighlighterBackground=#26999999 -LineHighlighterForeground=#80D9D9D9 -LineHighlighterForegroundIndex=2 -LineHighlighterBackgroundIndex=2 diff --git a/Fastedit/Assets/Designs/Acrylic-Gray.fasteditdesign b/Fastedit/Assets/Designs/Acrylic-Gray.fasteditdesign deleted file mode 100644 index 65b82a3..0000000 --- a/Fastedit/Assets/Designs/Acrylic-Gray.fasteditdesign +++ /dev/null @@ -1,31 +0,0 @@ -ThemeIndex=2 -TextSelectionColorIndex=2 -TextColorIndex=2 -TextBackgroundColorIndex=1 -TextColor=#FFFFFFFF -TextBackgroundColor=#00FFFFFF -TextSelectionColor=#FFC4C4C4 -LineNumberBackgroundColorIndex=1 -LineNumberBackgroundColor=#00FFFFFF -LineNumberForegroundColorIndex=2 -LineNumberForegroundColor=#FFFFFFFF -AppBackgroundColorIndex=2 -AppBackgroundColor=#404D4D4D -TitleBarBackgroundColor=#4D3B3B3B -TitleBarBackgroundColorIndex=2 -TabColorNotFocusedIndex=1 -TabColorFocusedIndex=2 -TabColorFocused=#471A1A1A -TabColorNotFocused=#00FFFFFF -DialogBackgroundColor=#EE262626 -DialogBackgroundColorIndex=2 -StatusbarForegroundColorIndex=2 -StatusbarBackgroundColorIndex=1 -StatusbarForegroundColor=#FFFFFFFF -StatusbarBackgroundColor=#00FFFFFF -UseMica=False -AcrylicEnabled=True -LineHighlighterBackground=#26999999 -LineHighlighterForeground=#80D9D9D9 -LineHighlighterForegroundIndex=2 -LineHighlighterBackgroundIndex=2 diff --git a/Fastedit/Assets/Designs/Acrylic-Green.fasteditdesign b/Fastedit/Assets/Designs/Acrylic-Green.fasteditdesign deleted file mode 100644 index 2992037..0000000 --- a/Fastedit/Assets/Designs/Acrylic-Green.fasteditdesign +++ /dev/null @@ -1,31 +0,0 @@ -ThemeIndex=0 -TextSelectionColorIndex=2 -TextColorIndex=2 -TextBackgroundColorIndex=1 -TextColor=#FF00FF07 -TextBackgroundColor=#00FFFFFF -TextSelectionColor=#FF00B305 -LineNumberBackgroundColorIndex=1 -LineNumberBackgroundColor=#00FFFFFF -LineNumberForegroundColorIndex=2 -LineNumberForegroundColor=#FF00FF07 -AppBackgroundColorIndex=2 -AppBackgroundColor=#66008003 -TitleBarBackgroundColor=#33008003 -TitleBarBackgroundColorIndex=2 -TabColorNotFocusedIndex=1 -TabColorFocusedIndex=2 -TabColorFocused=#FF00A605 -TabColorNotFocused=#00FFFFFF -DialogBackgroundColor=#EE005402 -DialogBackgroundColorIndex=2 -StatusbarForegroundColorIndex=2 -StatusbarBackgroundColorIndex=1 -StatusbarForegroundColor=#FF00FF07 -StatusbarBackgroundColor=#00FFFFFF -UseMica=False -AcrylicEnabled=True -LineHighlighterBackground=#00000000 -LineHighlighterForeground=#FF00B305 -LineHighlighterForegroundIndex=2 -LineHighlighterBackgroundIndex=2 diff --git a/Fastedit/Assets/Designs/Acrylic-Red.fasteditdesign b/Fastedit/Assets/Designs/Acrylic-Red.fasteditdesign deleted file mode 100644 index 392857c..0000000 --- a/Fastedit/Assets/Designs/Acrylic-Red.fasteditdesign +++ /dev/null @@ -1,31 +0,0 @@ -ThemeIndex=0 -TextSelectionColorIndex=2 -TextColorIndex=2 -TextBackgroundColorIndex=1 -TextColor=#FFFF3C00 -TextBackgroundColor=#00FFFFFF -TextSelectionColor=#FF992400 -LineNumberBackgroundColorIndex=1 -LineNumberBackgroundColor=#00FFFFFF -LineNumberForegroundColorIndex=2 -LineNumberForegroundColor=#FFFF3C00 -AppBackgroundColorIndex=2 -AppBackgroundColor=#66FF0000 -TitleBarBackgroundColor=#4DFF0000 -TitleBarBackgroundColorIndex=2 -TabColorNotFocusedIndex=1 -TabColorFocusedIndex=2 -TabColorFocused=#FFFF0000 -TabColorNotFocused=#00FFFFFF -DialogBackgroundColor=#EE800105 -DialogBackgroundColorIndex=2 -StatusbarForegroundColorIndex=2 -StatusbarBackgroundColorIndex=1 -StatusbarForegroundColor=#FFFF3C00 -StatusbarBackgroundColor=#00FFFFFF -UseMica=False -AcrylicEnabled=True -LineHighlighterBackground=#00000000 -LineHighlighterForeground=#FFFF3C00 -LineHighlighterForegroundIndex=2 -LineHighlighterBackgroundIndex=2 diff --git a/Fastedit/Assets/Designs/Mica-Accentcolor.fasteditdesign b/Fastedit/Assets/Designs/Mica-Accentcolor.fasteditdesign deleted file mode 100644 index 1ea3038..0000000 --- a/Fastedit/Assets/Designs/Mica-Accentcolor.fasteditdesign +++ /dev/null @@ -1,31 +0,0 @@ -ThemeIndex=0 -TextSelectionColorIndex=0 -TextColorIndex=0 -TextBackgroundColorIndex=1 -TextColor=1 -TextBackgroundColor=#00FFFFFF -TextSelectionColor=4 -LineNumberBackgroundColorIndex=1 -LineNumberBackgroundColor=#00FFFFFF -LineNumberForegroundColorIndex=0 -LineNumberForegroundColor=1 -AppBackgroundColorIndex=2 -AppBackgroundColor=#FF0078D4 -TitleBarBackgroundColor=2 -TitleBarBackgroundColorIndex=0 -TabColorNotFocusedIndex=1 -TabColorFocusedIndex=0 -TabColorFocused=2 -TabColorNotFocused=#00FFFFFF -DialogBackgroundColor=#EE474747 -DialogBackgroundColorIndex=2 -StatusbarForegroundColorIndex=0 -StatusbarBackgroundColorIndex=1 -StatusbarForegroundColor=2 -StatusbarBackgroundColor=#00FFFFFF -UseMica=True -AcrylicEnabled=False -LineHighlighterBackground=#00000000 -LineHighlighterForeground=4 -LineHighlighterForegroundIndex=0 -LineHighlighterBackgroundIndex=2 diff --git a/Fastedit/Assets/Designs/Mica-BlackWhite.fasteditdesign b/Fastedit/Assets/Designs/Mica-BlackWhite.fasteditdesign deleted file mode 100644 index 1d2222a..0000000 --- a/Fastedit/Assets/Designs/Mica-BlackWhite.fasteditdesign +++ /dev/null @@ -1,31 +0,0 @@ -ThemeIndex=2 -TextSelectionColorIndex=2 -TextColorIndex=2 -TextBackgroundColorIndex=1 -TextColor=#FFFFFFFF -TextBackgroundColor=#00FFFFFF -TextSelectionColor=#FFC4C4C4 -LineNumberBackgroundColorIndex=1 -LineNumberBackgroundColor=#00FFFFFF -LineNumberForegroundColorIndex=2 -LineNumberForegroundColor=#FFFFFFFF -AppBackgroundColorIndex=2 -AppBackgroundColor=#00000000 -TitleBarBackgroundColor=#AB3B3B3B -TitleBarBackgroundColorIndex=2 -TabColorNotFocusedIndex=1 -TabColorFocusedIndex=2 -TabColorFocused=#A64D4D4D -TabColorNotFocused=#00FFFFFF -DialogBackgroundColor=#EE262626 -DialogBackgroundColorIndex=2 -StatusbarForegroundColorIndex=2 -StatusbarBackgroundColorIndex=1 -StatusbarForegroundColor=#FFFFFFFF -StatusbarBackgroundColor=#00FFFFFF -UseMica=True -AcrylicEnabled=False -LineHighlighterBackground=#26999999 -LineHighlighterForeground=#80D9D9D9 -LineHighlighterForegroundIndex=2 -LineHighlighterBackgroundIndex=2 diff --git a/Fastedit/Assets/Designs/Mica-Blue.fasteditdesign b/Fastedit/Assets/Designs/Mica-Blue.fasteditdesign deleted file mode 100644 index 7449c4b..0000000 --- a/Fastedit/Assets/Designs/Mica-Blue.fasteditdesign +++ /dev/null @@ -1,31 +0,0 @@ -ThemeIndex=0 -TextSelectionColorIndex=2 -TextColorIndex=2 -TextBackgroundColorIndex=1 -TextColor=#FF004BFF -TextBackgroundColor=#00FFFFFF -TextSelectionColor=#FF004BFF -LineNumberBackgroundColorIndex=1 -LineNumberBackgroundColor=#00FFFFFF -LineNumberForegroundColorIndex=2 -LineNumberForegroundColor=#FF004BFF -AppBackgroundColorIndex=2 -AppBackgroundColor=#FF002580 -TitleBarBackgroundColor=#FF0031A6 -TitleBarBackgroundColorIndex=2 -TabColorNotFocusedIndex=1 -TabColorFocusedIndex=2 -TabColorFocused=#FF0031A6 -TabColorNotFocused=#00FFFFFF -DialogBackgroundColor=#EE001A59 -DialogBackgroundColorIndex=2 -StatusbarForegroundColorIndex=2 -StatusbarBackgroundColorIndex=1 -StatusbarForegroundColor=#FF004BFF -StatusbarBackgroundColor=#00FFFFFF -UseMica=True -AcrylicEnabled=False -LineHighlighterBackground=#00000000 -LineHighlighterForeground=#FF0035B3 -LineHighlighterForegroundIndex=2 -LineHighlighterBackgroundIndex=2 diff --git a/Fastedit/Assets/Designs/Mica-Green.fasteditdesign b/Fastedit/Assets/Designs/Mica-Green.fasteditdesign deleted file mode 100644 index 432bdf7..0000000 --- a/Fastedit/Assets/Designs/Mica-Green.fasteditdesign +++ /dev/null @@ -1,31 +0,0 @@ -ThemeIndex=0 -TextSelectionColorIndex=2 -TextColorIndex=2 -TextBackgroundColorIndex=1 -TextColor=#FF00FF07 -TextBackgroundColor=#00FFFFFF -TextSelectionColor=#FF00B305 -LineNumberBackgroundColorIndex=1 -LineNumberBackgroundColor=#00FFFFFF -LineNumberForegroundColorIndex=2 -LineNumberForegroundColor=#FF00FF07 -AppBackgroundColorIndex=2 -AppBackgroundColor=#FF008003 -TitleBarBackgroundColor=#FF008003 -TitleBarBackgroundColorIndex=2 -TabColorNotFocusedIndex=1 -TabColorFocusedIndex=2 -TabColorFocused=#FF00A605 -TabColorNotFocused=#00FFFFFF -DialogBackgroundColor=#EE005402 -DialogBackgroundColorIndex=2 -StatusbarForegroundColorIndex=2 -StatusbarBackgroundColorIndex=1 -StatusbarForegroundColor=#FF00FF07 -StatusbarBackgroundColor=#00FFFFFF -UseMica=True -AcrylicEnabled=False -LineHighlighterBackground=#00000000 -LineHighlighterForeground=#FF00B305 -LineHighlighterForegroundIndex=2 -LineHighlighterBackgroundIndex=2 diff --git a/Fastedit/Assets/Designs/Mica-Purple.fasteditdesign b/Fastedit/Assets/Designs/Mica-Purple.fasteditdesign deleted file mode 100644 index b943397..0000000 --- a/Fastedit/Assets/Designs/Mica-Purple.fasteditdesign +++ /dev/null @@ -1,31 +0,0 @@ -ThemeIndex=0 -TextSelectionColorIndex=2 -TextColorIndex=2 -TextBackgroundColorIndex=1 -TextColor=#FFFF00FF -TextBackgroundColor=#00FFFFFF -TextSelectionColor=#FFFF00FF -LineNumberBackgroundColorIndex=1 -LineNumberBackgroundColor=#00FFFFFF -LineNumberForegroundColorIndex=2 -LineNumberForegroundColor=#FFFF00FF -AppBackgroundColorIndex=2 -AppBackgroundColor=#FF8D00FF -TitleBarBackgroundColor=#FF8D00FF -TitleBarBackgroundColorIndex=2 -TabColorNotFocusedIndex=1 -TabColorFocusedIndex=2 -TabColorFocused=#FF8D00FF -TabColorNotFocused=#00FFFFFF -DialogBackgroundColor=#EE474747 -DialogBackgroundColorIndex=2 -StatusbarForegroundColorIndex=2 -StatusbarBackgroundColorIndex=1 -StatusbarForegroundColor=#FFFF00FF -StatusbarBackgroundColor=#00FFFFFF -UseMica=True -AcrylicEnabled=False -LineHighlighterBackground=#00000000 -LineHighlighterForeground=#FF8D00FF -LineHighlighterForegroundIndex=2 -LineHighlighterBackgroundIndex=2 diff --git a/Fastedit/Assets/Designs/Mica-Red.fasteditdesign b/Fastedit/Assets/Designs/Mica-Red.fasteditdesign deleted file mode 100644 index 8c549b3..0000000 --- a/Fastedit/Assets/Designs/Mica-Red.fasteditdesign +++ /dev/null @@ -1,31 +0,0 @@ -ThemeIndex=0 -TextSelectionColorIndex=2 -TextColorIndex=2 -TextBackgroundColorIndex=1 -TextColor=#FFFF3C00 -TextBackgroundColor=#00FFFFFF -TextSelectionColor=#FF992400 -LineNumberBackgroundColorIndex=1 -LineNumberBackgroundColor=#00FFFFFF -LineNumberForegroundColorIndex=2 -LineNumberForegroundColor=#FFFF3C00 -AppBackgroundColorIndex=2 -AppBackgroundColor=#66FF0000 -TitleBarBackgroundColor=#4DFF0000 -TitleBarBackgroundColorIndex=2 -TabColorNotFocusedIndex=1 -TabColorFocusedIndex=2 -TabColorFocused=#FFFF0000 -TabColorNotFocused=#00FFFFFF -DialogBackgroundColor=#EE800105 -DialogBackgroundColorIndex=2 -StatusbarForegroundColorIndex=2 -StatusbarBackgroundColorIndex=1 -StatusbarForegroundColor=#FFFF3C00 -StatusbarBackgroundColor=#00FFFFFF -UseMica=True -AcrylicEnabled=False -LineHighlighterBackground=#00000000 -LineHighlighterForeground=#FFFF3C00 -LineHighlighterForegroundIndex=2 -LineHighlighterBackgroundIndex=2 diff --git a/Fastedit/Assets/Designs/Mica-WhiteBlack.fasteditdesign b/Fastedit/Assets/Designs/Mica-WhiteBlack.fasteditdesign deleted file mode 100644 index 502fc37..0000000 --- a/Fastedit/Assets/Designs/Mica-WhiteBlack.fasteditdesign +++ /dev/null @@ -1,31 +0,0 @@ -ThemeIndex=1 -TextSelectionColorIndex=2 -TextColorIndex=2 -TextBackgroundColorIndex=1 -TextColor=#FF000000 -TextBackgroundColor=#00FFFFFF -TextSelectionColor=#FF808080 -LineNumberBackgroundColorIndex=1 -LineNumberBackgroundColor=#00FFFFFF -LineNumberForegroundColorIndex=2 -LineNumberForegroundColor=#FF000000 -AppBackgroundColorIndex=2 -AppBackgroundColor=#FFFFFFFF -TitleBarBackgroundColor=#00C2C2C2 -TitleBarBackgroundColorIndex=2 -TabColorNotFocusedIndex=1 -TabColorFocusedIndex=2 -TabColorFocused=#99D4D4D4 -TabColorNotFocused=#00FFFFFF -DialogBackgroundColor=#EE474747 -DialogBackgroundColorIndex=2 -StatusbarForegroundColorIndex=2 -StatusbarBackgroundColorIndex=1 -StatusbarForegroundColor=#FF000000 -StatusbarBackgroundColor=#00FFFFFF -UseMica=True -AcrylicEnabled=False -LineHighlighterBackground=#33999999 -LineHighlighterForeground=#80BFBFBF -LineHighlighterForegroundIndex=2 -LineHighlighterBackgroundIndex=2 diff --git a/Fastedit/Assets/SocialIcons/GitHub-Mark-120px-plus.png b/Fastedit/Assets/SocialIcons/GitHub-Mark-120px-plus.png deleted file mode 100644 index ea6ff54..0000000 Binary files a/Fastedit/Assets/SocialIcons/GitHub-Mark-120px-plus.png and /dev/null differ diff --git a/Fastedit/Assets/SocialIcons/GitHub-Mark-Light-120px-plus.png b/Fastedit/Assets/SocialIcons/GitHub-Mark-Light-120px-plus.png deleted file mode 100644 index 192846a..0000000 Binary files a/Fastedit/Assets/SocialIcons/GitHub-Mark-Light-120px-plus.png and /dev/null differ diff --git a/Fastedit/Assets/SocialIcons/Instagram_Glyph_Gradient_RGB.png b/Fastedit/Assets/SocialIcons/Instagram_Glyph_Gradient_RGB.png deleted file mode 100644 index ca40657..0000000 Binary files a/Fastedit/Assets/SocialIcons/Instagram_Glyph_Gradient_RGB.png and /dev/null differ diff --git a/Fastedit/Assets/news.txt b/Fastedit/Assets/changelog.txt similarity index 87% rename from Fastedit/Assets/news.txt rename to Fastedit/Assets/changelog.txt index 14eb730..27e78c2 100644 --- a/Fastedit/Assets/news.txt +++ b/Fastedit/Assets/changelog.txt @@ -1,4 +1,22 @@ -Fastedit Changelog: +Fastedit Changelog: + +------------------------------------------------------- +Version 2.0.0 [01/17/2023] + • rebuilt the app from the ground up + • faster and way more stable database + • syntaxhighlighting + • new textbox with a lot more features + • textlimit is now 100 million characters + • new designs + • faster startup time + • cleaned up settings page + • many more small improvements and overall a more stable experience + + Known issues: + • search sometimes has some weird behaviour + • replace not implemented yet + • Close all not implemented + ------------------------------------------------------- Version 1.6.2 [05/20/2022] @@ -12,8 +30,8 @@ Version 1.5.2 [05/06/2022] • Added a compact overlay mode for secondary instance • Improved startup performance mostly for a larger amount of tabs • Designchange now changes the design of all instances - • Fixed a bug, where the line under your cursor got copied if nothing selected - • Fixed a bug, where you could not open a file using the Windows-rightlickmenu, + • Fixed a bug, where the line under your cursor got copied if nothig selected + • Fixed a bug, where you could not open a file using the Windows-rignhtlickmenu, if the app was already running ------------------------------------------------------- @@ -105,4 +123,4 @@ Version 1.0.1 - 02/09/2022 because it caused too many crashes -> I will add this in the future ------------------------------------------------------- -Version 1.0.0 - 01/24/2022 +Version 1.0.0 - 01/24/2022 \ No newline at end of file diff --git a/Fastedit/Controls/ColorChooserButton.xaml b/Fastedit/Controls/ColorChooserButton.xaml deleted file mode 100644 index bb0c9c3..0000000 --- a/Fastedit/Controls/ColorChooserButton.xaml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - diff --git a/Fastedit/Controls/ColorChooserButton.xaml.cs b/Fastedit/Controls/ColorChooserButton.xaml.cs deleted file mode 100644 index 98822c6..0000000 --- a/Fastedit/Controls/ColorChooserButton.xaml.cs +++ /dev/null @@ -1,77 +0,0 @@ -using Windows.UI; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Media; - -namespace Fastedit.Controls -{ - public sealed partial class ColorChooserButton : UserControl - { - public bool IsUsedAsDisplay { get; set; } - private bool _IsCompact; - public bool IsCompact - { - get => _IsCompact; - set - { - if (value) - { - Colordisplay.Height = 20; - } - else - { - Colordisplay.Height = 30; - } - _IsCompact = value; - } - } - private readonly AppSettings appsettings = new AppSettings(); - private readonly Color buttonbordercolor = Colors.Black; - - public ColorChooserButton() - { - this.InitializeComponent(); - - buttonbordercolor = appsettings.CurrentApplicationTheme == ElementTheme.Light ? Colors.Black : Colors.White; - - Colordisplay.BorderBrush = new SolidColorBrush(buttonbordercolor); - } - - public delegate void ColorChanged(ColorPicker sender); - public event ColorChanged ColorChangedEvent; - - public bool IsAlphaEnabled - { - set - { - ColorPickerFlyout.IsAlphaEnabled = value; - } - } - public Color Color - { - get { return ColorPickerFlyout.Color; } - set { ColorPickerFlyout.Color = value; } - } - - private void Rectangle_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) - { - if (!IsUsedAsDisplay) - { - flyout.ShowAt(Colordisplay); - } - } - - private void ColorPickerFlyout_ColorChanged_1(ColorPicker sender, ColorChangedEventArgs args) - { - - } - - private void flyout_Closed(object sender, object e) - { - if (!IsUsedAsDisplay) - { - ColorChangedEvent?.Invoke(ColorPickerFlyout); - } - } - } -} diff --git a/Fastedit/Controls/CustomizationControl.xaml b/Fastedit/Controls/CustomizationControl.xaml deleted file mode 100644 index c5e3ee8..0000000 --- a/Fastedit/Controls/CustomizationControl.xaml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - diff --git a/Fastedit/Controls/CustomizationControl.xaml.cs b/Fastedit/Controls/CustomizationControl.xaml.cs deleted file mode 100644 index 2b8e012..0000000 --- a/Fastedit/Controls/CustomizationControl.xaml.cs +++ /dev/null @@ -1,78 +0,0 @@ -using Fastedit.Core; -using Fastedit.Extensions; -using Fastedit.Views.SettingsPage; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices.WindowsRuntime; -using Windows.Foundation; -using Windows.Foundation.Collections; -using Windows.UI; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Controls.Primitives; -using Windows.UI.Xaml.Data; -using Windows.UI.Xaml.Input; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Navigation; - -namespace Fastedit.Controls -{ - public sealed partial class CustomizationControl : UserControl - { - private AppSettings appsettings = new AppSettings(); - - public bool IsAlphaEnabled { set => ColorPickerButton.IsAlphaEnabled = value; } - public string Header { get; set; } = ""; - public Visibility TransparentComboboxItem - { - get => Cb_Item_Transparent.Visibility; - set => Cb_Item_Transparent.Visibility = value; - } - public string ResourceKey { get; set; } = ""; - public AccentColors Accentcolor { get; set; } = AccentColors.Default; - public bool SaveChangesToSettings { get; set; } = true; - - public event ColorChanged ColorChangedEvent; - public delegate void ColorChanged(); - - public CustomizationControl() - { - this.InitializeComponent(); - } - - public void RetrieveFromSettings() - { - ColorPickerButton.Color = appsettings.GetSettingsAsColorWithDefault(ResourceKey, DefaultValues.SystemAccentColor); - combobox.SelectedIndex = appsettings.GetSettingsAsInt(ResourceKey + "Index", 0); - } - - private void ColorPickerButton_ColorChangedEvent(ColorPicker sender) - { - appsettings.SaveSettings(ResourceKey, sender.Color); - ColorChangedEvent?.Invoke(); - } - - private void combobox_SelectionChanged(object sender, SelectionChangedEventArgs e) - { - ColorPickerButton.IsUsedAsDisplay = true; - if (TransparentComboboxItem == Visibility.Visible) - { - PageSettings.SaveCustomAccentTransparentColorToSettings( - ResourceKey, Accentcolor, Colors.Transparent, - combobox, ColorPickerButton, SaveChangesToSettings - ); - } - else - { - PageSettings.SaveCustomAndAccentColorToSettings( - ResourceKey, Accentcolor, Colors.Transparent, - combobox, ColorPickerButton, SaveChangesToSettings - ); - } - ColorChangedEvent?.Invoke(); - appsettings.SaveSettings(ResourceKey + "Index", combobox.SelectedIndex); - } - } -} diff --git a/Fastedit/Controls/InfobarMessage.cs b/Fastedit/Controls/InfobarMessage.cs new file mode 100644 index 0000000..3e7eb4c --- /dev/null +++ b/Fastedit/Controls/InfobarMessage.cs @@ -0,0 +1,40 @@ +using Fastedit.Dialogs; +using Microsoft.UI.Xaml.Controls; +using System; +using Windows.UI.Xaml; + +namespace Fastedit.Controls +{ + public class InfobarMessage : InfoBar + { + public InfobarMessage(string title, string message, InfoBarSeverity severity, int showSeconds = 5) + { + Show(title, message, null, severity, showSeconds); + } + public InfobarMessage(string title, string message, UIElement content, InfoBarSeverity severity, int showSeconds = 5) + { + Show(title, message, content, severity, showSeconds); + } + + private void Show(string title, string message, UIElement content, InfoBarSeverity severity, int showSeconds = 5) + { + this.Title = title; + this.Message = message; + this.Content = content; + this.Severity = severity; + this.IsOpen = true; + //this.Background = DialogHelper.ContentDialogBackground(); + //this.Foreground = DialogHelper.ContentDialogForeground(); + this.RequestedTheme = DialogHelper.DialogDesign; + + DispatcherTimer autoCloseTimer = new DispatcherTimer(); + autoCloseTimer.Interval = new TimeSpan(0, 0, showSeconds); + autoCloseTimer.Start(); + autoCloseTimer.Tick += delegate + { + this.IsOpen = false; + autoCloseTimer.Stop(); + }; + } + } +} diff --git a/Fastedit/Controls/RunCommandWindow.xaml b/Fastedit/Controls/RunCommandWindow.xaml new file mode 100644 index 0000000..7a92baf --- /dev/null +++ b/Fastedit/Controls/RunCommandWindow.xaml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Fastedit/Controls/RunCommandWindow.xaml.cs b/Fastedit/Controls/RunCommandWindow.xaml.cs new file mode 100644 index 0000000..083fce3 --- /dev/null +++ b/Fastedit/Controls/RunCommandWindow.xaml.cs @@ -0,0 +1,206 @@ +using Fastedit.Tab; +using Microsoft.UI.Xaml.Controls; +using System.Collections.Generic; +using System.Linq; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; +using Windows.UI.Xaml.Input; + +namespace Fastedit.Controls +{ + public sealed partial class RunCommandWindow : UserControl + { + List CurrentTabPages = new List(); + RunCommandWindowSubItem currentPage = null; + + public RunCommandWindow() + { + this.InitializeComponent(); + } + + public void Toggle(TabView tabView) + { + if (this.Visibility == Visibility.Visible) + Hide(); + else + Show(tabView); + } + public void Show(TabView tabView) + { + //Add the current tabpages: + AddCurrentTabPages(tabView); + Items.AddRange(CurrentTabPages); + + if (itemHostListView == null) + { + itemHostListView = FindName("itemHostListView") as ListView; + } + + searchbox.Text = ""; + this.Visibility = Visibility.Visible; + showControlAnimation.Begin(); + searchbox.Focus(FocusState.Programmatic); + } + public void Hide() + { + //Remove all tabs + Items.RemoveAll(x => x.Tag is TabPageItem); + + currentPage = null; + hideControlAnimation.Begin(); + } + public List Items { get; set; } = new List(); + + private void AddCurrentTabPages(TabView tabView) + { + //remove when there are too many + if (CurrentTabPages.Count > tabView.TabItems.Count) + { + CurrentTabPages.RemoveRange(0, CurrentTabPages.Count - tabView.TabItems.Count); + } + + //overwrite or add new ones: + for (int i = 0; i < tabView.TabItems.Count; i++) + { + if (tabView.TabItems[i] is TabPageItem tab) + { + if (i < CurrentTabPages.Count) + { + CurrentTabPages[i].Command = tab.DatabaseItem.FileName; + CurrentTabPages[i].Tag = tab; + CurrentTabPages[i].Shortcut = "Open document"; + } + else + { + CurrentTabPages.Add( + new RunCommandWindowCustomItem + { + Command = tab.DatabaseItem.FileName, + Tag = tab, + Shortcut = "Open document" + }); + } + } + } + } + private void searchbox_TextChanged(object sender, TextChangedEventArgs e) + { + if (currentPage != null) + { + var source = currentPage.Items.Where(x => x.Command.ToLower().Contains(searchbox.Text.ToLower())); + itemHostListView.ItemsSource = source.OrderBy(x => x.Command); + return; + } + + var newsource = Items.Where(x => x.Command.ToLower().Contains(searchbox.Text.ToLower())); + + itemHostListView.ItemsSource = newsource.OrderBy(x => x.Command); + itemHostListView.SelectedIndex = 0; + } + private void itemHostListView_ItemClick(object sender, ItemClickEventArgs e) + { + ItemClicked(e.ClickedItem); + } + private void ItemClicked(object clickedItem) + { + if (clickedItem is RunCommandWindowItem item) + { + item.InvokeEvent(); + Hide(); + } + else if (clickedItem is RunCommandWindowSubItem subItem) + { + //change the source -> like switching to sub page: + currentPage = subItem; + searchbox.Text = ""; + itemHostListView.ItemsSource = subItem.Items; + itemHostListView.SelectedIndex = 1; + } + else if (clickedItem is RunCommandWindowCustomItem customItem) + { + //select a tabpage + if (customItem.Tag is TabPageItem tab) + { + TabPageHelper.mainPage.ChangeSelectedTab(tab); + Hide(); + } + } + } + private void UserControl_KeyDown(object sender, KeyRoutedEventArgs e) + { + if (e.Key == Windows.System.VirtualKey.Escape) + { + if (currentPage != null) + { + currentPage = null; + searchbox.Text = ""; + itemHostListView.ItemsSource = Items; + return; + } + Hide(); + } + else if (e.Key == Windows.System.VirtualKey.Down) + { + if (itemHostListView.SelectedIndex < itemHostListView.Items.Count - 1) + { + itemHostListView.SelectedIndex++; + itemHostListView.ScrollIntoView(itemHostListView.Items[itemHostListView.SelectedIndex]); + } + + itemHostListView.ScrollIntoView(itemHostListView.Items[itemHostListView.SelectedIndex]); + } + else if (e.Key == Windows.System.VirtualKey.Up) + { + if (itemHostListView.SelectedIndex > 0) + { + itemHostListView.SelectedIndex--; + itemHostListView.ScrollIntoView(itemHostListView.Items[itemHostListView.SelectedIndex]); + } + + } + else if (e.Key == Windows.System.VirtualKey.Enter) + { + ItemClicked(itemHostListView.SelectedItem); + } + } + private void hideControlAnimation_Completed(object sender, object e) + { + this.Visibility = Visibility.Collapsed; + } + } + public class RunCommandWindowItem : IRunCommandWindowItem + { + public delegate void RunCommandWindowItemClickedEvent(object sender, RoutedEventArgs e); + public event RunCommandWindowItemClickedEvent RunCommandWindowItemClicked; + public void InvokeEvent() + { + RunCommandWindowItemClicked?.Invoke(this, null); + } + + public object Tag { get; set; } + public string Command { get; set; } + public string Shortcut { get; set; } + } + + public class RunCommandWindowSubItem : IRunCommandWindowItem + { + public List Items { get; set; } = new List(); + public string Command { get; set; } + public string Shortcut { get; set; } + public object Tag { get; set; } + } + + public class RunCommandWindowCustomItem : IRunCommandWindowItem + { + public string Command { get; set; } + public string Shortcut { get; set; } + public object Tag { get; set; } + } + + public interface IRunCommandWindowItem + { + string Command { get; set; } + string Shortcut { get; set; } + object Tag { get; set; } + } +} diff --git a/Fastedit/Controls/SearchControl.xaml b/Fastedit/Controls/SearchControl.xaml new file mode 100644 index 0000000..172e1dd --- /dev/null +++ b/Fastedit/Controls/SearchControl.xaml @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Fastedit/Controls/StatusbarItem.xaml.cs b/Fastedit/Controls/StatusbarItem.xaml.cs new file mode 100644 index 0000000..0927c21 --- /dev/null +++ b/Fastedit/Controls/StatusbarItem.xaml.cs @@ -0,0 +1,58 @@ +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; +using Windows.UI.Xaml.Controls.Primitives; +using Windows.UI.Xaml.Media; + +// The User Control item template is documented at https://go.microsoft.com/fwlink/?LinkId=234236 + +namespace Fastedit.Controls +{ + public sealed partial class StatusbarItem : UserControl + { + public delegate void StatusbarItemClickEvent(StatusbarItem sender, Button children); + public event StatusbarItemClickEvent StatusbarItemClick; + + public StatusbarItem() + { + this.InitializeComponent(); + } + + public FlyoutBase CustomFlyout + { + set + { + button.Flyout = value; + } + } + + public UIElement FlyoutContent + { + get => flyout.Content; + set + { + button.Flyout = value == null ? null : flyout; + flyout.Content = value; + } + } + + private string _StaticText; + private string _ChangingText; + public string StaticText { get => _StaticText; set { _StaticText = value; UpdateContent(); } } + public string ChangingText { get => _ChangingText; set { _ChangingText = value; UpdateContent(); } } + + public new Brush Foreground { set { button.Foreground = value; } get => button.Foreground; } + public void HideFlyout() + { + flyout.Hide(); + } + + public void UpdateContent() + { + button.Content = _StaticText + _ChangingText; + } + private void button_Click(object sender, RoutedEventArgs e) + { + StatusbarItemClick?.Invoke(this, button); + } + } +} diff --git a/Fastedit/Controls/Textbox/Linenumbers.cs b/Fastedit/Controls/Textbox/Linenumbers.cs deleted file mode 100644 index 6dff9bd..0000000 --- a/Fastedit/Controls/Textbox/Linenumbers.cs +++ /dev/null @@ -1,254 +0,0 @@ -using Fastedit.Extensions; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using Windows.Foundation; -using Windows.UI.Composition; -using Windows.UI.Text; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Hosting; -using Windows.UI.Xaml.Media; - -namespace Fastedit.Controls.Textbox -{ - //Code inspired from https://github.com/JasonStein/Notepads/blob/master/src/Notepads/Controls/TextEditor/TextEditorCore.LineNumbers.cs - public class Linenumbers - { - TextControlBox tcb = null; - RichEditBox textbox = null; - private readonly IList RenderedLineNumbers = new List(); - private readonly Dictionary _miniRequisiteIntegerTextRenderingWidthCache = new Dictionary(); - - public Linenumbers(TextControlBox tb, RichEditBox textb) - { - tcb = tb; - textbox = textb; - } - - //Linenumbers - public void ShowLinenumbers() - { - if (tcb.LineNumberGrid != null) - { - ResetLinenumberCanvas(); - UpdateLinenumberRendering(); - } - } - public void HideLinenumbers() - { - if (tcb.LineNumberGrid != null) - { - for (int i = 0; i < RenderedLineNumbers.Count; i++) - { - RenderedLineNumbers[i].Visibility = Visibility.Collapsed; - } - - tcb.LineNumberGrid.BorderThickness = new Thickness(0, 0, 0, 0); - tcb.LineNumberGrid.Margin = new Thickness(0, 0, 0, 0); - tcb.LineNumberGrid.Width = .0f; - } - } - public void ResetLinenumberCanvas() - { - if (tcb.LineNumberGrid != null) - { - tcb.LineNumberGrid.Margin = new Thickness(0, 0, (-1 * tcb.Padding.Left) + 1, 0); - tcb.LineNumberGrid.Clip = new RectangleGeometry - { - Rect = new Rect( - 0, - tcb.Padding.Top, - tcb.LineNumberGrid.ActualWidth, - Math.Clamp(tcb.LineNumberGrid.ActualHeight - (tcb.Padding.Top + tcb.Padding.Bottom), .0f, Double.PositiveInfinity)) - }; - } - } - public void UpdateLinenumberRendering() - { - if (!tcb.ShowLineNumbers) return; - - if (tcb.MainContentScrollViewer != null) - { - var startRange = textbox.Document.GetRangeFromPoint( - new Point(tcb.MainContentScrollViewer.HorizontalOffset, tcb.MainContentScrollViewer.VerticalOffset), - PointOptions.ClientCoordinates); - - var endRange = textbox.Document.GetRangeFromPoint( - new Point(tcb.MainContentScrollViewer.HorizontalOffset + tcb.MainContentScrollViewer.ViewportWidth, - tcb.MainContentScrollViewer.VerticalOffset + tcb.MainContentScrollViewer.ViewportHeight), - PointOptions.ClientCoordinates); - - var document = tcb.GetLineNumberContent; - document = document.Append("\n"); - - Dictionary lineNumberTextRenderingPositions = GetLinenumberPos(document, startRange, endRange); - - var minLineNumberTextRenderingWidth = CalculateMinimumTextRenderingWidth(tcb.FontFamily, - textbox.FontSize, (document.Length - 1).ToString().Length) + 10; - - DoRenderLineNumbers(lineNumberTextRenderingPositions, minLineNumberTextRenderingWidth); - } - } - public Size GetTextSize(FontFamily font, double fontSize, string text) - { - var tb = new TextBlock { Text = text, FontFamily = font, FontSize = fontSize }; - tb.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity)); - return tb.DesiredSize; - } - public double CalculateMinimumTextRenderingWidth(FontFamily fontFamily, double fontSize, int numberTextLength) - { - var cacheKey = $"{fontFamily.Source}-{(int)fontSize}-{numberTextLength}"; - - if (_miniRequisiteIntegerTextRenderingWidthCache.ContainsKey(cacheKey)) - { - return _miniRequisiteIntegerTextRenderingWidthCache[cacheKey]; - } - - double minRequisiteWidth = 0; - - for (int i = 0; i < 10; i++) - { - var str = new string((char)('0' + i), numberTextLength); - var width = GetTextSize(fontFamily, fontSize, str).Width; - if (width > minRequisiteWidth) - { - minRequisiteWidth = width; - } - } - - _miniRequisiteIntegerTextRenderingWidthCache[cacheKey] = minRequisiteWidth; - return minRequisiteWidth; - } - private Dictionary GetLinenumberPos(string[] lines, ITextRange startRange, ITextRange endRange) - { - var offset = 0; - var lineRects = new Dictionary(); // 1 - based - - for (int i = 0; i < lines.Length - 1; i++) - { - var line = lines[i]; - - // Use "offset + line.Length + 1" instead of just "offset" here is to capture the line right above the viewport - if (offset + line.Length + 1 >= startRange.StartPosition && offset <= endRange.EndPosition) - { - textbox.Document.GetRange(offset, offset + line.Length) - .GetRect(PointOptions.ClientCoordinates, out var rect, out _); - - lineRects[i + 1] = rect; - } - else if (offset > endRange.EndPosition) - { - break; - } - - offset += line.Length + 1; // 1 for line ending: '\r' - } - - return lineRects; - } - public void DoRenderLineNumbers(Dictionary lineNumberTextRenderingPositions, double minLineNumberTextRenderingWidth) - { - var padding = tcb.FontSize / 2; - var lineNumberPadding = new Thickness(padding, 2, padding + 2, 2); - var lineNumberTextBlockHeight = tcb.GetSingleLineHeight() + tcb.Padding.Top + lineNumberPadding.Top; - var numOfReusableLineNumberBlocks = RenderedLineNumbers.Count; - - foreach (var (lineNumber, rect) in lineNumberTextRenderingPositions) - { - var margin = new Thickness(lineNumberPadding.Left, - rect.Top + lineNumberPadding.Top + tcb.Padding.Top, - lineNumberPadding.Right, - lineNumberPadding.Bottom); - - if (numOfReusableLineNumberBlocks > 0) - { - var index = numOfReusableLineNumberBlocks - 1; - var ln = RenderedLineNumbers[index]; - ln.Text = lineNumber.ToString(); - ln.Margin = margin; - ln.Height = lineNumberTextBlockHeight; - ln.Width = minLineNumberTextRenderingWidth; - ln.Visibility = Visibility.Visible; - ln.Foreground = new SolidColorBrush(tcb.LineNumberForeground); - - numOfReusableLineNumberBlocks--; - } - else - { - var lineNumberBlock = new TextBlock() - { - Text = lineNumber.ToString(), - Height = lineNumberTextBlockHeight, - Width = minLineNumberTextRenderingWidth, - Margin = margin, - TextAlignment = TextAlignment.Right, - HorizontalAlignment = HorizontalAlignment.Right, - VerticalAlignment = VerticalAlignment.Bottom, - HorizontalTextAlignment = TextAlignment.Right, - Foreground = new SolidColorBrush(tcb.LineNumberForeground) - }; - - tcb.LineNumberCanvas.Children.Add(lineNumberBlock); - RenderedLineNumbers.Add(lineNumberBlock); - } - } - - // Hide all unused rendered linenumber blocks to avoid collosion - for (int i = 0; i < numOfReusableLineNumberBlocks; i++) - { - RenderedLineNumbers[i].Visibility = Visibility.Collapsed; - } - tcb.LineNumberGrid.Width = lineNumberPadding.Left + minLineNumberTextRenderingWidth + lineNumberPadding.Right; - } - } - - public static class ExtensionClass - { - //Extension method to append an element to the stringarray - public static T[] Append(this T[] array, T item) - { - List list = new List(array) - { - item - }; - - return list.ToArray(); - } - } - public static class ScrollViewerExtensions - { - public static ExpressionAnimation StartExpressionAnimation( - this ScrollViewer scrollViewer, - UIElement target, - Axis axis) - { - return scrollViewer.StartExpressionAnimation(target, sourceAxis: axis, targetAxis: axis); - } - - public static ExpressionAnimation StartExpressionAnimation( - this ScrollViewer scrollViewer, - UIElement target, - Axis sourceAxis, - Axis targetAxis) - { - try - { - CompositionPropertySet scrollSet = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(scrollViewer); - - ExpressionAnimation animation = scrollSet.Compositor.CreateExpressionAnimation($"{nameof(scrollViewer)}.{nameof(UIElement.Translation)}.{sourceAxis}"); - animation.SetReferenceParameter(nameof(scrollViewer), scrollSet); - - Visual visual = ElementCompositionPreview.GetElementVisual(target); - visual.StartAnimation($"{nameof(Visual.Offset)}.{targetAxis}", animation); - - return animation; - } - catch - { - //Prevent crashing - return null; - } - } - } -} diff --git a/Fastedit/Controls/Textbox/Searchdialog.xaml b/Fastedit/Controls/Textbox/Searchdialog.xaml deleted file mode 100644 index 55dc1cd..0000000 --- a/Fastedit/Controls/Textbox/Searchdialog.xaml +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Fastedit/Controls/Textbox/TextControlBox.xaml.cs b/Fastedit/Controls/Textbox/TextControlBox.xaml.cs deleted file mode 100644 index 6d79c3b..0000000 --- a/Fastedit/Controls/Textbox/TextControlBox.xaml.cs +++ /dev/null @@ -1,1450 +0,0 @@ -using ColorCode; -using Fastedit.Core; -using Fastedit.Core.Tab; -using Fastedit.Dialogs; -using Fastedit.Extensions; -using Microsoft.Toolkit.Uwp.UI; -using Microsoft.Toolkit.Uwp.UI.Controls; -using Newtonsoft.Json.Linq; -using System; -using System.Buffers.Text; -using System.Diagnostics; -using System.Numerics; -using System.Reflection.Metadata; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading; -using System.Threading.Tasks; -using System.Xml.Linq; -using Windows.ApplicationModel.DataTransfer; -using Windows.Foundation; -using Windows.Security.Cryptography.Certificates; -using Windows.Storage; -using Windows.System; -using Windows.UI; -using Windows.UI.Core; -using Windows.UI.Text; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Input; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Shapes; -using Convert = Fastedit.Extensions.Convert; -using muxc = Microsoft.UI.Xaml.Controls; - -namespace Fastedit.Controls.Textbox -{ - public sealed partial class TextControlBox : UserControl - { - private readonly TabKey tabkey = null; - private readonly Linenumbers linenumbers = null; - private readonly AppSettings appsettings = new AppSettings(); - private readonly TextControlBoxFlyoutMenu flyoutmenu = null; - public ScrollViewer MainContentScrollViewer = null; - public Grid LineNumberGrid = null; - public Canvas LineNumberCanvas = null; - public Canvas LineHighlighterCanvas = null; - public Grid LineHighlighterControl = null; - private int OldLineNumber = 0; - private int OldWordCount = 0; - private bool MarkdownRoatation = false; - public string TextBuffer = string.Empty; - public bool TextLoaded = false; - - public TextControlBox() - { - this.InitializeComponent(); - tabkey = new TabKey(this); - linenumbers = new Linenumbers(this, textbox); - flyoutmenu = new TextControlBoxFlyoutMenu(this); - - //Create the flyouts - textbox.ContextFlyout = flyoutmenu.CreateFlyout(false); - //add events: - textbox.AddHandler(PointerPressedEvent, new PointerEventHandler(Textbox_PointerPressed), true); - KeyDown += TextControlBox_KeyDown; - textbox.CopyingToClipboard += Textbox_CopyingToClipboard; - textbox.TextChanged += Textbox_TextChanged; - textbox.PointerWheelChanged += Textbox_PointerWheelChanged; - textbox.SelectionChanged += Textbox_SelectionChanged; - textbox.Paste += Textbox_Paste; - //ScrollViewer - ScrollViewer.SetHorizontalScrollMode(textbox, ScrollMode.Enabled); - ScrollViewer.SetVerticalScrollMode(textbox, ScrollMode.Enabled); - base.Focus(FocusState.Programmatic); - UpdateRendering(); - } - - //Events - private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e) - { - UpdateMarkdownSize(); - UpdateLineHighlighter(); - } - private void Textbox_CopyingToClipboard(RichEditBox sender, TextControlCopyingToClipboardEventArgs args) - { - Copy(); - args.Handled = true; - } - private void Textbox_Paste(object sender, TextControlPasteEventArgs e) - { - //Prevent the textbox from pasting because it has a custom paste function - e.Handled = true; - } - private void OnLineNumberGridSizeChanged(object sender, SizeChangedEventArgs e) - { - if (LineNumberGrid != null) - { - linenumbers.ResetLinenumberCanvas(); - } - } - private void Textbox_Loaded(object sender, RoutedEventArgs e) - { - //Find and assign the children to it's variable - LineHighlighterCanvas = textbox.FindDependencyObject("LineHighlighterCanvas") as Canvas; - LineHighlighterControl = textbox.FindDependencyObject("LineHighlighterControl") as Grid; - LineHighlighterControl.Background = new SolidColorBrush(LineHighlighterBackground); - LineHighlighterControl.BorderBrush = new SolidColorBrush(LineHighlighterForeground); - LineNumberCanvas = textbox.FindDependencyObject("LineNumberCanvas") as Canvas; - LineNumberGrid = textbox.FindDependencyObject("LineNumberGrid") as Grid; - MainContentScrollViewer = textbox.FindDependencyObject("ContentElement") as ScrollViewer; - - UpdateRendering(); - textbox.Focus(FocusState.Programmatic); - } - private void Textbox_TextChanged(object sender, RoutedEventArgs e) - { - string text = GetText(); - linenumbers.UpdateLinenumberRendering(); - - if (TextBeforeLastSaved != text) - { - TextChangedevent?.Invoke(this); - SaveStatusChangedEvent?.Invoke(this, IsModified); - IsModified = true; - if (MarkdownPreview && text != null) - { - markdowntextblock.Text = text; - } - } - int words = CountWords(text); - if (words != OldWordCount) - { - OldWordCount = words; - WordCountChangedEvent?.Invoke(this, words); - } - } - private void Textbox_PointerWheelChanged(object sender, PointerRoutedEventArgs e) - { - var Control = Window.Current.CoreWindow.GetKeyState(VirtualKey.Control); - if (Control.HasFlag(CoreVirtualKeyStates.Down)) - { - ScrollViewer.SetVerticalScrollMode(textbox, ScrollMode.Disabled); - - int delta = e.GetCurrentPoint((UIElement)sender).Properties.MouseWheelDelta; - - if (delta < 0) - { - ZoomOut(0.1); - } - - if (delta > 0) - { - ZoomIn(0.1); - } - - ScrollViewer.SetVerticalScrollMode(textbox, ScrollMode.Enabled); - } - } - private void Textbox_SelectionChanged(object sender, RoutedEventArgs e) - { - UpdateLineHighlighter(); - UpdateLineNumber(); - - tabdatafromdatabase.TabSelLenght = SelectionLenght; - tabdatafromdatabase.TabSelStart = SelectionStart; - } - private void Textbox_PointerPressed(object sender, PointerRoutedEventArgs e) - { - Pointer_PressedEvent?.Invoke(this, e); - } - private void TextControlBox_KeyDown(object sender, KeyRoutedEventArgs e) - { - KeyPressedEvent?.Invoke(this, e); - var Shift = Window.Current.CoreWindow.GetKeyState(VirtualKey.Shift); - var Control = Window.Current.CoreWindow.GetKeyState(VirtualKey.Control); - - if (Control.HasFlag(CoreVirtualKeyStates.Down) && Shift.HasFlag(CoreVirtualKeyStates.None)) - { - //Cut // Copy // Paste - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.C, Copy); - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.V, Paste); - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.X, Cut); - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.D, DuplicateLine); - - //Undo // Redo - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.Z, Undo); - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.Y, Redo); - - //Select all - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.A, SelectAll); - - //Scroll up // Scroll down - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.Up, ScrollWithArrowKeys, VerticalAxis.Up); - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.Down, ScrollWithArrowKeys, VerticalAxis.Down); - - //Zoom in / Zoom out - if (e.Key.ToString() == "187") - { - ZoomIn(DefaultValues.DefaultZoomFactor); - } - if (e.Key.ToString() == "189") - { - ZoomOut(DefaultValues.DefaultZoomFactor); - } - } - else - { - //TabKey - if (Shift.HasFlag(CoreVirtualKeyStates.Down)) - { - if (e.Key == VirtualKey.Tab && SelectionLenght == 0) - { - e.Handled = true; - tabkey.MoveTextWithTab_Back_WithoutSelection(); - } - else if (e.Key == VirtualKey.Tab && SelectionLenght != 0) - { - e.Handled = true; - tabkey.MoveTextWithTab_Back_WithSelection(); - } - } - else if (Shift.HasFlag(CoreVirtualKeyStates.None)) - { - if (e.Key == VirtualKey.Tab && SelectionLenght == 0) - { - e.Handled = true; - tabkey.MoveTextWithTab_Forward_WithoutSelection(); - } - else if (e.Key == VirtualKey.Tab && SelectionLenght != 0) - { - e.Handled = true; - tabkey.MoveTextWithTab_Forward_WithSelection(); - } - } - } - } - private void TextControlBox_ScrollChanged(object sender, ScrollViewerViewChangedEventArgs e) - { - if (LineHighlighterCanvas != null && LineHighlighter == true) - { - MainContentScrollViewer.StartExpressionAnimation(LineHighlighterCanvas, Axis.Y); - } - - MainContentScrollViewer.StartExpressionAnimation(LineNumberCanvas, Axis.Y); - linenumbers.UpdateLinenumberRendering(); - UpdateLineHighlighterScroll(); - } - private void ScrollViewer_SizeChanged(object sender, SizeChangedEventArgs e) - { - linenumbers.UpdateLinenumberRendering(); - } - private void Markdowntextblock_MarkdownRendered(object sender, MarkdownRenderedEventArgs e) - { - if (progressring != null) - { - progressring.IsActive = false; - progressring.Visibility = Visibility.Collapsed; - } - } - - //Store data - public TabDataForDatabase tabdatafromdatabase = new TabDataForDatabase - { - ZoomFactor = 100, - TabName = "", - TabModified = false, - TabHeader = "", - TabToken = "", - TabPath = "", - DataBaseName = "", - TabTemp = "", - TabReadOnly = false, - TabSelLenght = 0, - TabSelStart = 0, - CurrentSelectedTabIndex = 0, - TabSaveMode = TabSaveMode.SaveAsFile, - TabEncoding = 1, - Markdown = false, - MarkdownMode2 = false, - MarkdownIsColumn = false, - WordWrap = TextWrapping.NoWrap, - }; - public string IdentifierName - { - get { return this.Name; } - set { this.Name = value; tabdatafromdatabase.TabName = value; } - } - public string FilePath { get => tabdatafromdatabase.TabPath; set { tabdatafromdatabase.TabPath = value; } } - public string DataBaseName { get => tabdatafromdatabase.DataBaseName; set { tabdatafromdatabase.DataBaseName = value; } } - public string Header - { - get => tabdatafromdatabase.TabHeader; - set - { - if (TextLoaded) - DocumentTitleChangedEvent?.Invoke(this, value); - tabdatafromdatabase.TabHeader = value; - } - } - public bool IsModified - { - get => tabdatafromdatabase.TabModified; - set - { - tabdatafromdatabase.TabModified = value; - SaveStatusChangedEvent?.Invoke(this, value); - } - } - public TabSaveMode TabSaveMode { get => tabdatafromdatabase.TabSaveMode; set {tabdatafromdatabase.TabSaveMode = value; } } - public string FileToken { get => tabdatafromdatabase.TabToken; set { tabdatafromdatabase.TabToken = value; } } - public string TempFile { get => tabdatafromdatabase.TabTemp; set { tabdatafromdatabase.TabTemp = value; } } - private Encoding _Encoding = Encoding.Default; - public Encoding Encoding - { - get => _Encoding; - set - { - if (_Encoding != value) - { - _Encoding = value; - tabdatafromdatabase.TabEncoding = Encodings.EncodingToInt(value); - IsModified = true; - if (TextLoaded) - EncodingChangedEvent?.Invoke(this, value); - } - } - } - public StorageFile Storagefile { get; set; } = null; - public string TextBeforeLastSaved { get; set; } = ""; - - //Just for setting the Encoding, without affecting the Modified state - public void SetEncoding(Encoding encoding) - { - if (_Encoding != encoding) - { - _Encoding = encoding; - tabdatafromdatabase.TabEncoding = Encodings.EncodingToInt(encoding); - if (TextLoaded) - EncodingChangedEvent?.Invoke(this, encoding); - } - } - - //TextModes: - public TextWrapping WordWrap - { - get => textbox.TextWrapping; - set { textbox.TextWrapping = value; linenumbers.UpdateLinenumberRendering(); tabdatafromdatabase.WordWrap = value; } - } - public bool IsReadOnly - { - get => textbox.IsReadOnly; - set { textbox.IsReadOnly = value; tabdatafromdatabase.TabReadOnly = value; } - } - public bool SpellChecking - { - get => textbox.IsSpellCheckEnabled; - set { textbox.IsSpellCheckEnabled = value; } - } - public bool IsHandWritingEnabled - { - get => textbox.IsHandwritingViewEnabled; - set { textbox.IsHandwritingViewEnabled = value; } - } - - //Font & Fontsize - private async void SetFontSize(double val) - { - await Dispatcher.RunAsync(CoreDispatcherPriority.High, () => - { - _textfontsize = val; - if (val > DefaultValues.MaxFontWithZoom) - { - val = DefaultValues.MaxFontWithZoom; - } - else if (val < DefaultValues.MinFontWithZoom) - { - val = DefaultValues.MinFontWithZoom; - } - - if (textbox != null) - { - textbox.FontSize = val; - } - - var newZoomFactor = Math.Round(val * 100 / appsettings.GetSettingsAsInt("FontSize", DefaultValues.DefaultFontsize)); - if (Math.Abs(newZoomFactor - _zoomFactor) >= 1) - { - _zoomFactor = newZoomFactor; - } - if (TextLoaded) - ZoomChangedEvent?.Invoke(this, newZoomFactor); - }); - } - private double _textfontsize = DefaultValues.DefaultFontsize; - public new double FontSize - { - get { return _textfontsize; } - set - { - SetFontSize(value); - } - } - public double FontSizeWithoutZoom - { - set - { - if (value > DefaultValues.MaxFontWithZoom) - { - value = DefaultValues.MaxFontWithZoom; - } - else if (value < DefaultValues.MinFontWithZoom) - { - value = DefaultValues.MinFontWithZoom; - } - textbox.FontSize = value; - } - } - public new FontFamily FontFamily - { - get { return textbox.FontFamily; } - set - { - textbox.FontFamily = value; - - linenumbers.UpdateLinenumberRendering(); - } - } - - public Rect GetSelectionRect() - { - textbox.Document.Selection.GetRect(Windows.UI.Text.PointOptions.ClientCoordinates, - out Rect rect, out var _); - return rect; - } - - //Appearance: - public Color TextColor - { - get - { - if (textbox.Foreground is SolidColorBrush colorBrush) - { - return colorBrush.Color; - } - else - { - return Color.FromArgb(255, 0, 0, 0); - } - } - set - { - textbox.Foreground = new SolidColorBrush(value); - } - } - public Color LineNumberBackground - { - get - { - if (LineNumberGrid != null) - { - return Convert.ToColor(LineNumberGrid.Background, Colors.Gray); - } - else - { - return Color.FromArgb(0, 0, 0, 0); - } - } - set - { - if (LineNumberGrid != null) - { - LineNumberGrid.Background = new SolidColorBrush(value); - } - - linenumbers.UpdateLinenumberRendering(); - } - } - private Color _LineNumberForeground; - public Color LineNumberForeground - { - get { return _LineNumberForeground; } - set - { - _LineNumberForeground = value; - linenumbers.UpdateLinenumberRendering(); - } - } - public new Color Background - { - get => Convert.ToColor(textbox.Background, Colors.Gray); - set - { - textbox.Background = new SolidColorBrush(value); - if(markdowntextblock != null) - markdowntextblock.Background = new SolidColorBrush(value); - } - } - public Color TextSelectionColor - { - get => textbox.SelectionHighlightColor.Color; - set - { - textbox.SelectionHighlightColor = new SolidColorBrush(value); - textbox.SelectionHighlightColorWhenNotFocused = new SolidColorBrush(value); - } - } - public double BackgroundOpacity - { - get { return textbox.Background.Opacity; } - set { textbox.Background.Opacity = value; } - } - private bool _ShowLineNumbers { get; set; } - public bool ShowLineNumbers - { - get { return _ShowLineNumbers; } - set - { - _ShowLineNumbers = value; - if (value == true) - linenumbers.ShowLinenumbers(); - else - linenumbers.HideLinenumbers(); - } - } - private Color _LineHighlighterForeground; - public Color LineHighlighterForeground - { - get - { - return _LineHighlighterForeground; - } - set - { - _LineHighlighterForeground = value; - if (LineHighlighterControl != null) - LineHighlighterControl.BorderBrush = new SolidColorBrush(value); - } - } - private Color _LineHighlighterBackground; - public Color LineHighlighterBackground - { - get - { - return _LineHighlighterBackground; - } - set - { - _LineHighlighterBackground = value; - if (LineHighlighterControl != null) - LineHighlighterControl.Background = new SolidColorBrush(value); - } - } - - /// - /// Update text, Linenumbers and Linehighlighter -rendering - /// - public void UpdateRendering() - { - UpdateLineHighlighter(); - UpdateLineNumber(); - } - - //Rightclickmenu - public bool ShowSelectionFlyout - { - set - { - textbox.SelectionFlyout = value ? flyoutmenu.CreateSelectionFlyout() : null; - } - get => textbox.SelectionFlyout == null ? false : true; - } - public void UpdateContextFlyout() - { - textbox.ContextFlyout = flyoutmenu.CreateFlyout(false); - } - - //Line highlighter - public void UpdateLineHighlighterScroll() - { - if (MainContentScrollViewer == null || LineHighlighterControl == null) - return; - - var selsize = GetSelectionRect(); - var MarginTop = selsize.Y - MainContentScrollViewer.VerticalOffset + LineHighlighterControl.Height*2; - bool condition = MarginTop < 40 || MarginTop > textbox.ActualHeight + 10; - - LineHighlighterControl.Visibility = Convert.BoolToVisibility(!condition); - } - public void UpdateLineHighlighter() - { - if (!LineHighlighter || LineHighlighterCanvas == null || LineHighlighterControl == null) - { - return; - } - - if (SelectionIsMultiline() && LineHighlighterControl.Visibility == Visibility.Visible) - { - LineHighlighterControl.Visibility = Visibility.Collapsed; - } - else if (LineHighlighterControl.Visibility == Visibility.Collapsed && SelectionLenght == 0) - { - LineHighlighterControl.Visibility = Visibility.Visible; - } - - if (LineHighlighterControl.Visibility == Visibility.Visible) - { - LineHighlighterControl.BorderThickness = new Thickness((double)_zoomFactor / 50); - LineHighlighterControl.Height = GetSingleLineHeight() + 4; - LineHighlighterControl.Margin = - new Thickness(LineNumberGrid.ActualWidth + 5, (GetSelectionRect().Y + textbox.Padding.Top - 2), 0, 0); - int Width = (int)(textbox.ActualWidth - LineNumberGrid.ActualWidth - 5); - LineHighlighterControl.Width = Width < 0 ? 0 : Width - (MainContentScrollViewer.ComputedVerticalScrollBarVisibility == Visibility.Visible ? 7 : 0); - } - } - private bool _LineHighlighter = false; - public bool LineHighlighter - { - set - { - if (value) - { - UpdateLineHighlighter(); - if(LineHighlighterControl != null && LineHighlighterCanvas != null) - LineHighlighterControl.Visibility = LineHighlighterCanvas.Visibility = Visibility.Visible; - } - else - { - if(LineHighlighterControl != null) - { - LineHighlighterControl.Visibility = LineHighlighterCanvas.Visibility = Visibility.Collapsed; - } - } - _LineHighlighter = value; - } - get => _LineHighlighter; - } - - //Markdown - public bool MarkdownPreview - { - get => markdowntextblock != null; - set - { - tabdatafromdatabase.Markdown = value; - if (value == true) - { - if (markdowntextblock == null || markdowntextblock_sv == null || Splittedview_Splitter == null) - { - markdowntextblock_sv = FindName("markdowntextblock_sv") as ScrollViewer; - markdowntextblock = FindName("markdowntextblock") as MarkdownTextBlock; - Splittedview_Splitter = FindName("Splittedview_Splitter") as GridSplitter; - - if (MarkdownPreview) - { - markdowntextblock.Text = GetText(); - progressring = FindName("progressring") as muxc.ProgressRing; - - markdowntextblock.Background = textbox.Background; - MarkdownRoatation = tabdatafromdatabase.MarkdownIsColumn; - Markdown_UpdateRotation(); - - if (tabdatafromdatabase.MarkdownMode2) //left-right / top-bottom - { - if (tabdatafromdatabase.MarkdownIsColumn) - { - Grid.SetColumn(markdowntextblock_sv, 0); - Grid.SetColumn(Splittedview_Splitter, 1); - Grid.SetColumn(textbox, 2); - } - else - { - Grid.SetRow(textbox, 2); - Grid.SetRow(Splittedview_Splitter, 1); - Grid.SetRow(markdowntextblock_sv, 0); - } - } - else - { - if (tabdatafromdatabase.MarkdownIsColumn) - { - Grid.SetColumn(markdowntextblock_sv, 2); - Grid.SetColumn(Splittedview_Splitter, 1); - Grid.SetColumn(textbox, 0); - } - else - { - Grid.SetRow(textbox, 0); - Grid.SetRow(Splittedview_Splitter, 1); - Grid.SetRow(markdowntextblock_sv, 2); - } - } - UpdateMarkdownSize(); - } - - } - } - else - { - splittedgrid.ColumnDefinitions.Clear(); - splittedgrid.RowDefinitions.Clear(); - if(markdowntextblock_sv != null) - UnloadObject(markdowntextblock_sv); - if(markdowntextblock != null) - UnloadObject(markdowntextblock); - if(Splittedview_Splitter != null) - UnloadObject(Splittedview_Splitter); - } - } - } - private void SetGridColumns() - { - if (splittedgrid.ColumnDefinitions.Count > 0) - return; - splittedgrid.RowDefinitions.Clear(); - splittedgrid.ColumnDefinitions.Add(new ColumnDefinition()); - splittedgrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(16)}); - splittedgrid.ColumnDefinitions.Add(new ColumnDefinition()); - } - private void SetGridRows() - { - if (splittedgrid.RowDefinitions.Count > 0) - return; - splittedgrid.ColumnDefinitions.Clear(); - splittedgrid.RowDefinitions.Add(new RowDefinition()); - splittedgrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(16) }); - splittedgrid.RowDefinitions.Add(new RowDefinition()); - } - private bool Markdown_Column() - { - SetGridColumns(); - bool res = false; - if (Grid.GetColumn(markdowntextblock_sv) == 2) - { - Grid.SetColumn(markdowntextblock_sv, 0); - Grid.SetColumn(textbox, 2); - res = true; - } - else if (Grid.GetColumn(markdowntextblock_sv) == 0) - { - Grid.SetColumn(markdowntextblock_sv, 2); - Grid.SetColumn(textbox, 0); - } - Grid.SetColumn(Splittedview_Splitter, 1); - Markdown_Button_Rotation.Angle = 0; - return res; - } - private bool Markdown_Row() - { - SetGridRows(); - bool res = false; - if (Grid.GetRow(markdowntextblock_sv) == 2) - { - Grid.SetRow(markdowntextblock_sv, 0); - Grid.SetRow(textbox, 2); - res = true; - } - else if (Grid.GetRow(markdowntextblock_sv) == 0) - { - Grid.SetRow(markdowntextblock_sv, 2); - Grid.SetRow(textbox, 0); - } - Grid.SetRow(Splittedview_Splitter, 1); - Markdown_Button_Rotation.Angle = 90; - return res; - } - private void Markdown_ToggleLeftRight() - { - if (!MarkdownPreview) - return; - bool res = false; - //Markdowntextblock is column - if (tabdatafromdatabase.MarkdownIsColumn) - { - res = Markdown_Column(); - } - //Markdowntextblock is row - else - { - res = Markdown_Row(); - } - tabdatafromdatabase.MarkdownMode2 = res; //left right / top bottom - tabdatafromdatabase.MarkdownIsColumn = tabdatafromdatabase.MarkdownIsColumn; //Is column - } - private void Markdown_UpdateRotation() - { - if (!MarkdownRoatation) - { - MarkdownRoatation = true; - tabdatafromdatabase.MarkdownIsColumn = false; - GridSplitter_GripperBar.Height = 5; - GridSplitter_GripperBar.Width = 25; - Markdown_Button_Rotation.Angle = 90; - Markdown_Button_Rotation.CenterY = 0; - SetGridRows(); - GridsplitterSettingsFlyout.Margin = new Thickness(100, 0, 0, 0); - } - else - { - MarkdownRoatation = false; - tabdatafromdatabase.MarkdownIsColumn = true; - GridSplitter_GripperBar.Height = 25; - GridSplitter_GripperBar.Width = 5; - Markdown_Button_Rotation.Angle = 0; - Markdown_Button_Rotation.CenterY = 14; - SetGridColumns(); - GridsplitterSettingsFlyout.Margin = new Thickness(0, -135, 0, 0); - } - } - private void UpdateMarkdownSize() - { - if (MarkdownPreview) - { - if (tabdatafromdatabase.MarkdownIsColumn) - { - Splittedview_Splitter.Width = 16; - Splittedview_Splitter.Height = this.ActualHeight; - } - else - { - Splittedview_Splitter.Height = 16; - Splittedview_Splitter.Width = this.ActualWidth; - } - UpdateLineHighlighter(); - } - } - private void ToggleLeftRight_Markdown_Click(object sender, RoutedEventArgs e) - { - Markdown_ToggleLeftRight(); - UpdateMarkdownSize(); - } - private void Rotate90Degree_Click(object sender, RoutedEventArgs e) - { - Markdown_UpdateRotation(); - Markdown_ToggleLeftRight(); - UpdateMarkdownSize(); - } - private void CloseMarkdown_Click(object sender, RoutedEventArgs e) - { - MarkdownPreview = false; - } - - //Selection: - public string SelectedText - { - get { return textbox.Document.Selection.Text; } - set { textbox.Document.Selection.Text = value; } - } - public int SelectionStart - { - get { return textbox.Document.Selection.StartPosition; } - set { textbox.Document.Selection.StartPosition = value; } - } - public int SelectionLenght - { - get { return textbox.Document.Selection.Length; } - } - public void SetSelection(int StartIndex, int Lenght) - { - textbox.Document.Selection.SetRange(StartIndex, StartIndex + Lenght); - } - public void SelectAll() - { - SetSelection(0, GetText().Length); - } - public bool SelectionIsMultiline() - { - return textbox.Document.Selection.Text.Contains("\r") || textbox.Document.Selection.Text.Contains("\n"); - } - - //Zoom actions: - private double __zoomFactor = 100; - public double _zoomFactor { get => __zoomFactor; set { __zoomFactor = value; tabdatafromdatabase.ZoomFactor = value; } } - public void SetFontZoomFactor(double ZoomFactor) - { - var fontZoomFactor = Math.Round(ZoomFactor); - if (fontZoomFactor >= DefaultValues.MinZoom && fontZoomFactor <= DefaultValues.MaxZoom) - { - FontSize = fontZoomFactor / 100 * appsettings.GetSettingsAsInt("FontSize", DefaultValues.DefaultFontsize); - _zoomFactor = ZoomFactor; - } - } - public void ZoomIn(double Factor) - { - if (_zoomFactor < DefaultValues.MaxZoom) - { - if (_zoomFactor % 10 > 0) - { - SetFontZoomFactor(Math.Ceiling(_zoomFactor / 10) * 10); - } - else - { - FontSize += Factor * appsettings.GetSettingsAsInt("FontSize", DefaultValues.DefaultFontsize); - } - } - } - public void ZoomOut(double Factor) - { - if (_zoomFactor > DefaultValues.MinZoom) - { - if (_zoomFactor % 10 > 0) - { - SetFontZoomFactor(Math.Floor(_zoomFactor / 10) * 10); - } - else - { - FontSize -= Factor * appsettings.GetSettingsAsInt("FontSize", DefaultValues.DefaultFontsize); - } - } - } - - //Cursorposition & Linenumbering - public int GetCurrentLineNumber - { - get - { - return textbox.Document.Selection.GetIndex(TextRangeUnit.Paragraph); - } - } - public int GetLinesCount - { - get - { - return GetText().Split('\r', '\n').Length; - } - } - public string[] GetLineNumberContent - { - get - { - return GetText().Split('\r', '\n'); - } - } - public double GetSingleLineHeight() - { - textbox.Document.GetRange(0, 0).GetRect(PointOptions.ClientCoordinates, out var rect, out _); - return rect.Height <= 0 ? 1.35 * textbox.FontSize : rect.Height; - } - public int CountWords(string text = null) - { - if (text == null) - { - text = GetText(); - } - - return text.Split(new char[] { '\n', ' ', '\r' }, StringSplitOptions.RemoveEmptyEntries).Length; - } - - //Scrollbar-Positions - public ScrollbarPositions GetScrollbarPositions() - { - if (MainContentScrollViewer != null) - { - return new ScrollbarPositions - { - ScrollbarPositionHorizontal = MainContentScrollViewer.HorizontalOffset, - ScrollbarPositionVertical = MainContentScrollViewer.VerticalOffset - }; - } - else - { - return new ScrollbarPositions - { - ScrollbarPositionHorizontal = 0, - ScrollbarPositionVertical = 0 - }; - } - } - public void SetScrollbarPositions(ScrollbarPositions pos, bool DisableAnimations = false) - { - if (MainContentScrollViewer != null) - { - MainContentScrollViewer.ChangeView(pos.ScrollbarPositionHorizontal, pos.ScrollbarPositionVertical, null, DisableAnimations); - } - } - public void ScrollIntoView() - { - if (MainContentScrollViewer != null) - { - double vOffset = MainContentScrollViewer.VerticalOffset + this.ActualHeight / 2; - MainContentScrollViewer.ChangeView(null, vOffset, null, true); - } - } - - //Undo-Redo - public void Undo() - { - textbox.Document.Undo(); - } - public void Redo() - { - textbox.Document.Redo(); - } - - //Basic Textediting: - public void Copy() - { - void DoCopy(string text = null) - { - var dataPackage = new DataPackage(); - dataPackage.SetText(text == null ? textbox.Document.Selection.Text : text); - Clipboard.SetContentWithOptions( - dataPackage, - new ClipboardContentOptions() - { - IsAllowedInHistory = true, - IsRoamable = true - }); - try - { - Clipboard.Flush(); - } - catch (Exception e) - { - Debug.WriteLine("Exception in TextControlBox --> Copy:" + "\n" + e.Message); - } - } - if (textbox.Document.Selection.Length == 0) - { - DoCopy(GetLineNumberContent[GetCurrentLineNumber-1]); - } - else - { - DoCopy(); - } - } - public void DuplicateLine() - { - if (textbox.Document.Selection.Length == 0) - { - textbox.Document.Selection.SetIndex(TextRangeUnit.Paragraph, GetCurrentLineNumber, false); - string selectedtext = GetLineNumberContent[GetCurrentLineNumber-1]; - textbox.Document.Selection.Text = selectedtext + "\n"; - SetSelection(SelectionStart + (selectedtext.Length*2)+1, 0); - } - else - { - SetSelection(SelectionStart, 0); - DuplicateLine(); - } - } - public async void Paste() - { - if (!IsReadOnly) - { - DataPackageView dataPackageView = Clipboard.GetContent(); - if (dataPackageView.Contains(StandardDataFormats.Text)) - { - string text = await dataPackageView.GetTextAsync(); - if (SelectionLenght > 0) - { - textbox.Document.Selection.Text = ""; - } - - textbox.Document.Selection.Text = text; - textbox.Document.Selection.SetRange(SelectionStart + text.Length, SelectionStart + text.Length); - } - } - } - public void Cut() - { - if (!IsReadOnly) - { - if (textbox.Document.Selection.Length == 0) - { - var CurrentSelStart = SelectionStart; - - SelectLine(GetCurrentLineNumber); - textbox.Document.Selection.Cut(); - SetSelection(CurrentSelStart, 0); - - } - else - { - textbox.Document.Selection.Cut(); - } - } - } - public void SurroundSelectionBy(string surroundtext) - { - textbox.Document.Selection.Text = surroundtext + SelectedText + surroundtext; - } - public void SurroundSelectionBy(string surroundtext1, string surroundtext2) - { - textbox.Document.Selection.Text = surroundtext1 + SelectedText + surroundtext2; - } - - //Info-Toast - public void ShowInfoToast(bool ShowSavedMessage, string text = "") - { - ContentSavedInfo.IsOpen = true; - ContentSavedInfo.Background = DefaultValues.ContentDialogBackgroundColor(); - ContentSavedInfo.Foreground = DefaultValues.ContentDialogForegroundColor(); - if (text.Length == 0 || ShowSavedMessage) - { - ContentSavedInfo.Title = appsettings.GetResourceString("Toast_SaveSucced/Text"); - } - else - { - ContentSavedInfo.Title = text; - } - - DispatcherTimer hidetoastTimer = new DispatcherTimer - { - Interval = new TimeSpan(0, 0, 0, DefaultValues.TextBoxInfoToast_Time) - }; - hidetoastTimer.Stop(); - hidetoastTimer.Tick += delegate - { - hidetoastTimer.Stop(); - ContentSavedInfo.IsOpen = false; - }; - hidetoastTimer.Start(); - } - - //Set & Get text - /// - /// Get the text of the textbox - /// - /// The text - public string GetText() - { - if (!TextLoaded) - { - return TextBuffer; - } - textbox.Document.GetText(TextGetOptions.None, out string out1); - if (out1.Length != 0) - { - out1 = out1.Remove(out1.Length - 1, 1); - } - if (out1 == null) - return ""; - return out1; - } - /// - /// Set text to textbox - /// - /// The text to set to - public async Task SetText(string text, bool ismodified = false) - { - await this.Dispatcher.RunAsync(CoreDispatcherPriority.High, () => - { - bool isreadonly = IsReadOnly; - if (isreadonly) - textbox.IsReadOnly = false; - - textbox.Document.SetText(TextSetOptions.None, text); - TextBeforeLastSaved = GetText(); - IsModified = ismodified; - textbox.TextDocument.ClearUndoRedoHistory(); - if (isreadonly == true) - textbox.IsReadOnly = isreadonly; - }); - } - /// - /// Overrides the whole text, but the modified state stays - /// - /// - /// - public async Task ChangeText(string text, TextSetOptions textSetOptions = TextSetOptions.None) - { - await this.Dispatcher.RunAsync(CoreDispatcherPriority.High, () => - { - bool isreadonly = IsReadOnly; - if (isreadonly) - textbox.IsReadOnly = false; - - textbox.Document.SetText(textSetOptions, text); - - if (isreadonly == true) - textbox.IsReadOnly = isreadonly; - }); - } - - //Replace text - public bool ReplaceInText(string Word, string ReplaceWord, bool Up, bool MatchCase, bool WholeWord) - { - if (Word.Length == 0) - { - return false; - } - - bool res = FindInText(Word, Up, MatchCase, WholeWord); - if (res) - { - SelectedText = ReplaceWord; - } - - return res; - } - public bool ReplaceAll(string Word, string ReplaceWord, bool Up, bool MatchCase, bool WholeWord) - { - - if (Word.Length == 0) - { - return false; - } - - int selstart = SelectionStart, sellenght = SelectionLenght; - - if (!WholeWord) - { - SelectAll(); - if (MatchCase) - { - SelectedText = GetText().Replace(Word, ReplaceWord); - } - else - { - SelectedText = GetText().Replace(Word.ToLower(), ReplaceWord.ToLower()); - } - - return true; - } - - SetSelection(0, 0); - bool res = true; - while (res) - { - res = ReplaceInText(Word, ReplaceWord, Up, MatchCase, WholeWord); - } - - SetSelection(selstart, sellenght); - return true; - } - - /// - /// Selects a word in the textbox text - /// - /// The Word to search for - /// The searchdirection: Up / Down - /// - /// - /// The Text to search in. If null it uses the textbox text - /// - public bool FindInText(string Word, bool Up, bool MatchCase, bool WholeWord) - { - string Text = GetText(); - bool NotFound() - { - if (Word.Length > 20) - { - Word = Word.Substring(0, 20) + "... "; - } - SetSelection(0, 0); - ShowInfoToast(false, Word + " " + InfoBarMessages.SearchNotFound); - return false; - } - //Search down: - if (!Up) - { - if (!MatchCase) - { - Text = Text.ToLower(); - Word = Word.ToLower(); - } - if (SelectionStart == -1) - { - SelectionStart = 0; - } - - int startpos = SelectionStart; - if (SelectionLenght > 0) - { - startpos = SelectionStart + SelectionLenght; - } - if (Word.Length + startpos > Text.Length) - { - return NotFound(); - } - - int index = WholeWord ? Extensions.StringBuilder.IndexOfWholeWord(Text, Word, startpos) : Text.IndexOf(Word, startpos); - if (index == -1) - { - return NotFound(); - } - SetSelection(index, Word.Length); - textbox.Document.Selection.ScrollIntoView(PointOptions.Start); - return true; - } - else - { - try - { - if (!MatchCase) - { - Text = Text.ToLower(); - Word = Word.ToLower(); - } - if (SelectionStart == -1) - { - SelectionStart = 0; - } - - string shortedText = Text.Substring(0, SelectionStart); - int index = WholeWord ? Extensions.StringBuilder.LastIndexOfWholeWord(shortedText, Word) : shortedText.LastIndexOf(Word); - if (index == -1) - { - SetSelection(Text.Length, 0); - return NotFound(); - } - - SetSelection(index, Word.Length); - textbox.Document.Selection.ScrollIntoView(PointOptions.Start); - return true; - } - catch (Exception ex) - { - Debug.WriteLine("Exception in TextControlBox --> FindInText:" + "\n" + ex.Message); - return false; - } - } - } - - //Go to line - public bool GoToLine(int line) - { - if (appsettings.GetSettingsAsBool("SelectLineAfterGoingToIt", true)) - { - SelectLine(line); - } - else - { - textbox.Document.Selection.SetIndex(TextRangeUnit.Paragraph, line, false); - textbox.Focus(FocusState.Programmatic); - } - textbox.Document.Selection.ScrollIntoView(PointOptions.None); - return true; - } - public void SelectLine(int Line) - { - textbox.Document.Selection.SetIndex(TextRangeUnit.Paragraph, Line, true); - } - - //Other - public new void Focus(FocusState focusstate) - { - textbox.Focus(focusstate); - } - private void UpdateLineNumber() - { - if (GetCurrentLineNumber != OldLineNumber) - { - if (SelectionLenght > 0) - { - int linenumber = GetCurrentLineNumber + textbox.Document.Selection.Text.Split(new char[] { '\n', '\r' }).Length; - LineNumberchangedEvent?.Invoke(this, linenumber); - } - else - LineNumberchangedEvent?.Invoke(this, GetCurrentLineNumber); - - OldLineNumber = GetCurrentLineNumber; - } - } - public void ScrollWithArrowKeys(VerticalAxis axis) - { - if (MainContentScrollViewer == null) - return; - - if (axis == VerticalAxis.Up) - { - MainContentScrollViewer.ChangeView(null, MainContentScrollViewer.VerticalOffset - 10, null, true); - } - if (axis == VerticalAxis.Down) - { - MainContentScrollViewer.ChangeView(null, MainContentScrollViewer.VerticalOffset + 10, null, true); - } - } - - //Events - public delegate void TextChanged(TextControlBox sender); - public delegate void KeyPressed(TextControlBox sender, KeyRoutedEventArgs e); - public delegate void ZoomChanged(TextControlBox sender, double ZoomFactor); - public delegate void LineNumberChanged(TextControlBox sender, int CurrentLine); - public delegate void DocumentTitleChanged(TextControlBox sender, string Header); - public delegate void Pointer_Pressed(TextControlBox sender, PointerRoutedEventArgs e); - public delegate void Encoding_Changed(TextControlBox sender, Encoding e); - public delegate void SaveStatusChanged(TextControlBox sender, bool IsModified); - public delegate void WordCountChanged(TextControlBox sender, int Words); - public event KeyPressed KeyPressedEvent; - public event ZoomChanged ZoomChangedEvent; - public event LineNumberChanged LineNumberchangedEvent; - public event DocumentTitleChanged DocumentTitleChangedEvent; - public event Pointer_Pressed Pointer_PressedEvent; - public event Encoding_Changed EncodingChangedEvent; - public event TextChanged TextChangedevent; - public event WordCountChanged WordCountChangedEvent; - public event SaveStatusChanged SaveStatusChangedEvent; - } - public class MyRichEditBox : RichEditBox - { - public DependencyObject FindDependencyObject(string name) - { - return this.GetTemplateChild(name); - } - //Override the OnKeyDown class to make custom shortcuts and disable defaults - protected override void OnKeyDown(KeyRoutedEventArgs e) - { - var ctrl = Window.Current.CoreWindow.GetKeyState(VirtualKey.Control); - var shift = Window.Current.CoreWindow.GetKeyState(VirtualKey.Shift); - if (ctrl.HasFlag(CoreVirtualKeyStates.Down)) - { - if (e.Key == VirtualKey.Back || - e.Key == VirtualKey.Delete || - e.Key == VirtualKey.Enter || - e.Key == VirtualKey.Right || - e.Key == VirtualKey.Left || - e.Key == VirtualKey.Up || - e.Key == VirtualKey.Down) - { - base.OnKeyDown(e); - } - else - { - return; - } - } - else if (e.Key == VirtualKey.Enter && shift.HasFlag(CoreVirtualKeyStates.Down)) - { - return; - } - else - { - base.OnKeyDown(e); - } - } - } - public class SelectionPoint - { - public int SelectionStart { get; set; } - public int SelectionLenght { get; set; } - } - public class TextBoxDocument - { - public string FilePath { get; set; } - public string DataBaseName { get; set; } - public string Header { get; set; } - public bool IsModified { get; set; } - public bool IsHandWritingEnabled { get; set; } - public TabSaveMode TabSaveMode { get; set; } - public string FileToken { get; set; } - public StorageFile Storagefile { get; set; } - public TextWrapping WordWrap { get; set; } - public string TempFile { get; set; } - public Encoding Encoding { get; set; } - public double ZoomFactor { get; set; } - public bool IsReadonly { get; set; } - public string InternalTabName { get; set; } - } -} diff --git a/Fastedit/Controls/Textbox/TextControlBoxFlyoutMenu.cs b/Fastedit/Controls/Textbox/TextControlBoxFlyoutMenu.cs deleted file mode 100644 index 2f805f6..0000000 --- a/Fastedit/Controls/Textbox/TextControlBoxFlyoutMenu.cs +++ /dev/null @@ -1,235 +0,0 @@ -using Fastedit.Dialogs; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using Windows.UI.Popups; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using muxc = Microsoft.UI.Xaml.Controls; - -namespace Fastedit.Controls.Textbox -{ - public class TextControlBoxFlyoutMenu - { - private List buttons = null; - private AppSettings appsettings = new AppSettings(); - private TextControlBox textbox = null; - - public TextControlBoxFlyoutMenu(TextControlBox textbox) - { - buttons = CreateButtons(textbox); - this.textbox = textbox; - } - - /* - //Retrive from settings and create the flyout - public List CreateListFromSettings() - { - try - { - List Items = new List(); - - string Buttons = appsettings.GetSettingsAsString("TextControlBoxFlyout", ""); - if (Buttons.Length == 0) - return null; - - var split = Buttons.Split("|", StringSplitOptions.RemoveEmptyEntries); - for (int j = 0; j < split.Length; j++) - { - Items.Add(split[j]); - } - return Items; - } - catch(Exception e) - { - Debug.WriteLine("CreateListFromSettings : " + e.Message); - return null; - } - } - public MenuFlyout CreateFlyoutFromList(List items) - { - try - { - var flyout = new MenuFlyout(); - flyout.Placement = Windows.UI.Xaml.Controls.Primitives.FlyoutPlacementMode.BottomEdgeAlignedLeft; - flyout.ShowMode = Windows.UI.Xaml.Controls.Primitives.FlyoutShowMode.TransientWithDismissOnPointerMoveAway; - if (items == null) - return null; - - for (int i = 0; i < items.Count; i++) - { - if (items[i].Contains("Separator", System.StringComparison.Ordinal)) - { - flyout.Items.Add(new MenuFlyoutSeparator()); - } - else - { - flyout.Items.Add(GetButtonFromList(items[i])); - } - } - return flyout; - } - catch (Exception e) - { - Debug.WriteLine("CreateFlyoutFromList : " + e.Message); - return null; - } - } - */ - public List CreateButtons(TextControlBox textbox) - { - List lst = new List(); - string CopyText = AppSettings.GetResourceStringStatic("TextControlBoxFlyoutMenu_Copy/Text"); - string PasteText = AppSettings.GetResourceStringStatic("TextControlBoxFlyoutMenu_Paste/Text"); - string CutText = AppSettings.GetResourceStringStatic("TextControlBoxFlyoutMenu_Cut/Text"); - string UndoText = AppSettings.GetResourceStringStatic("TextControlBoxFlyoutMenu_Undo/Text"); - string SelectAllText = AppSettings.GetResourceStringStatic("TextControlBoxFlyoutMenu_SelectAll/Text"); - var CopyBtn = new MenuFlyoutItem { Name = "Copy", Text = CopyText, Icon = new SymbolIcon { Symbol = Symbol.Copy } }; - var CutBtn = new MenuFlyoutItem { Name = "Cut", Text = CutText, Icon = new SymbolIcon { Symbol = Symbol.Cut } }; - var FindText = new MenuFlyoutItem { Name = "Find", Text = "Find", Icon = new SymbolIcon { Symbol = Symbol.Find } }; - var ShareText = new MenuFlyoutItem { Name = "Share", Text = "Share selected", Icon = new SymbolIcon { Symbol = Symbol.Share } }; - var PasteBtn = new MenuFlyoutItem { Name = "Paste", Text = PasteText, Icon = new SymbolIcon { Symbol = Symbol.Paste } }; - var UndoBtn = new MenuFlyoutItem { Name = "Undo", Text = UndoText, Icon = new SymbolIcon { Symbol = Symbol.Undo } }; - var Selectall = new MenuFlyoutItem { Name = "SelectAll", Text = SelectAllText, Icon = new SymbolIcon { Symbol = Symbol.SelectAll } }; - ToolTipService.SetToolTip(CopyBtn, CopyText); - ToolTipService.SetToolTip(PasteBtn, PasteText); - ToolTipService.SetToolTip(CutBtn, CutText); - ToolTipService.SetToolTip(UndoBtn, UndoText); - ToolTipService.SetToolTip(Selectall, SelectAllText); - ToolTipService.SetToolTip(ShareText, "Share the selected text"); - lst.Add(CopyBtn); - lst.Add(PasteBtn); - lst.Add(CutBtn); - lst.Add(UndoBtn); - lst.Add(Selectall); - lst.Add(ShareText); - lst.Add(FindText); - //Only create the buttons, without the events: - //if (textbox == null) - // return lst; - - CopyBtn.Click += delegate - { - textbox.Copy(); - }; - PasteBtn.Click += delegate - { - textbox.Paste(); - }; - CutBtn.Click += delegate - { - textbox.Cut(); - }; - UndoBtn.Click += delegate - { - textbox.Undo(); - }; - Selectall.Click += delegate - { - textbox.SelectAll(); - }; - ShareText.Click += delegate - { - ShareFile.ShareText(textbox.SelectedText); - }; - FindText.Click += delegate - { - textbox.FindInText(textbox.SelectedText, false, false, false); - }; - return lst; - } - public MenuFlyoutItem GetButtonFromList(string name) - { - return buttons.Find(item => item.Name == name); - } - - public MenuFlyout CreateFlyout(bool SelectionFlyout) - { - if (textbox == null) - return null; - - if (buttons == null) - buttons = CreateButtons(textbox); - var flyout = new MenuFlyout(); - flyout.Placement = Windows.UI.Xaml.Controls.Primitives.FlyoutPlacementMode.BottomEdgeAlignedLeft; - flyout.ShowMode = Windows.UI.Xaml.Controls.Primitives.FlyoutShowMode.TransientWithDismissOnPointerMoveAway; - //if text is selected - if (SelectionFlyout) - { - flyout.Items.Add(GetButtonFromList("Copy")); - flyout.Items.Add(GetButtonFromList("Cut")); - flyout.Items.Add(GetButtonFromList("Paste")); - flyout.Items.Add(new MenuFlyoutSeparator()); - flyout.Items.Add(GetButtonFromList("Find")); - flyout.Items.Add(GetButtonFromList("Share")); - flyout.Items.Add(new MenuFlyoutSeparator()); - flyout.Items.Add(GetButtonFromList("Undo")); - flyout.Items.Add(GetButtonFromList("SelectAll")); - } - else //if no text is selected - { - flyout.Items.Add(GetButtonFromList("Copy")); - flyout.Items.Add(GetButtonFromList("Cut")); - flyout.Items.Add(GetButtonFromList("Paste")); - flyout.Items.Add(new MenuFlyoutSeparator()); - flyout.Items.Add(GetButtonFromList("Undo")); - flyout.Items.Add(GetButtonFromList("SelectAll")); - } - return flyout; - //return CreateFlyoutFromList(CreateListFromSettings()); - } - - public CommandBarFlyout CreateSelectionFlyout() - { - if (textbox == null) - return null; - - if (buttons == null) - buttons = CreateButtons(textbox); - - string CopyText = AppSettings.GetResourceStringStatic("TextControlBoxFlyoutMenu_Copy/Text"); - string PasteText = AppSettings.GetResourceStringStatic("TextControlBoxFlyoutMenu_Paste/Text"); - string CutText = AppSettings.GetResourceStringStatic("TextControlBoxFlyoutMenu_Cut/Text"); - string UndoText = AppSettings.GetResourceStringStatic("TextControlBoxFlyoutMenu_Undo/Text"); - string SelectAllText = AppSettings.GetResourceStringStatic("TextControlBoxFlyoutMenu_SelectAll/Text"); - var CopyBtn = new AppBarButton { Name = "Copy", Label = CopyText, Icon = new SymbolIcon { Symbol = Symbol.Copy }, LabelPosition = CommandBarLabelPosition.Collapsed }; - var CutBtn = new AppBarButton { Name = "Cut", Label = CutText, Icon = new SymbolIcon { Symbol = Symbol.Cut }, LabelPosition = CommandBarLabelPosition.Collapsed }; - var FindText = new AppBarButton { Name = "Find", Label = "Find", Icon = new SymbolIcon { Symbol = Symbol.Find }, LabelPosition = CommandBarLabelPosition.Collapsed }; - var ShareText = new AppBarButton { Name = "Share", Label = "Share selected", Icon = new SymbolIcon { Symbol = Symbol.Share }, LabelPosition =CommandBarLabelPosition.Collapsed }; - ToolTipService.SetToolTip(CopyBtn, CopyText); - ToolTipService.SetToolTip(CutBtn, CutText); - ToolTipService.SetToolTip(ShareText, "Share selected"); - ToolTipService.SetToolTip(FindText, "Find selected"); - - ShareText.Click += delegate - { - ShareFile.ShareText(textbox.SelectedText); - }; - FindText.Click += delegate - { - textbox.FindInText(textbox.SelectedText, false, false, false); - }; - CutBtn.Click += delegate - { - textbox.Cut(); - }; - CopyBtn.Click += delegate - { - textbox.Copy(); - }; - var flyout = new CommandBarFlyout(); - flyout.PrimaryCommands.Add(CopyBtn); - flyout.PrimaryCommands.Add(CutBtn); - flyout.PrimaryCommands.Add(ShareText); - flyout.PrimaryCommands.Add(FindText); - return flyout; - } - } - //public class TextControlBoxFlyout_Button - //{ - // public string ButtonName { get; set; } - // public string Text { get; set; } = ""; - // public bool IsOn { get; set; } = false; - // public string CheckBoxName { get; set; } = ""; - //} -} diff --git a/Fastedit/Core/DefaultValues.cs b/Fastedit/Core/DefaultValues.cs deleted file mode 100644 index 125b1aa..0000000 --- a/Fastedit/Core/DefaultValues.cs +++ /dev/null @@ -1,142 +0,0 @@ -using System; -using Windows.Storage; -using Windows.UI; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Markup; -using Windows.UI.Xaml.Media; - -namespace Fastedit.Core -{ - public class DefaultValues - { - //MainPage - public static string LocalFolderPath = ApplicationData.Current.LocalFolder.Path.ToString(); - public static int AutoSaveTempFileMinutes = 4; - public static int AutoBackupDataBaseMinutes = 4; - public static CornerRadius DefaultDialogCornerRadius = new CornerRadius(5); - public static bool LoadRecentTabsOnStart = true; - public static SolidColorBrush WrongInput_Color = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0)); - public static SolidColorBrush CorrectInput_Color = new SolidColorBrush(Color.FromArgb(255, 0, 255, 0)); - public static string DefaultThemeName = "Acrylic-Dark.fasteditdesign"; - public static string DefaultWindows11ThemeName = "Mica-Accentcolor.fasteditdesign"; - public static int TextBoxInfoToast_Time = 3; //How long the infotoast is displayed on the textbox until it gets closed - - //Tab Actions - public static CornerRadius DefaultTabCornerRadius = new CornerRadius(5, 5, 0, 0); - public static double DefaultZoomFactor = 0.2; - public static int MaxZoom = 300; - public static int MinZoom = 20; - public static int MinFontWithZoom = 2; - public static int MaxFontWithZoom = 120; - public static string NewDocName = "Untitled.txt"; - public static bool HandWritingEnabled = false; - public static string DefaultTabSize = "\t"; - public static string DefaultTabIconId = "\uE8A5"; - - //SetttingsPage - public static bool SpellCheckingEnabled = false; - public static int DefaultFontsize = 16; - public static int defaultTabSizeMode = 0; //0-2 - public static string DefaultFontFamily = "Consolas"; - - public static string CustomDesigns_FolderName = "Designs"; - public static string Database_FolderName = "DataBase"; - public static string RecycleBin_FolderName = "RecycleBin"; - public static string Backup_FolderName = "Backup"; - public static string Extension_FasteditDesign = ".fasteditdesign"; - - //Colors - public static Color SystemAccentColor - { - get - { - return (Color)XamlBindingHelper.ConvertValue(typeof(Color), Application.Current.Resources["SystemAccentColor"].ToString()); - } - } - public static Color SystemAccentColorLight1 - { - get - { - return (Color)XamlBindingHelper.ConvertValue(typeof(Color), Application.Current.Resources["SystemAccentColorLight1"].ToString()); - } - } - public static Color SystemAccentColorDark2 - { - get - { - return (Color)XamlBindingHelper.ConvertValue(typeof(Color), Application.Current.Resources["SystemAccentColorDark2"].ToString()); - } - } - public static Color SystemAccentColorDark1 - { - get - { - return (Color)XamlBindingHelper.ConvertValue(typeof(Color), Application.Current.Resources["SystemAccentColorDark1"].ToString()); - } - } - public static Color SystemAccentColorLight2 - { - get - { - try - { - var color = Application.Current.Resources["SystemAccentColorLight2"]; - if (color != null) - { - return (Color)XamlBindingHelper.ConvertValue(typeof(Color), Application.Current.Resources["SystemAccentColorLight2"].ToString()); - } - return Color.FromArgb(0, 0, 0, 0); - } - catch - { - return Color.FromArgb(0, 0, 0, 0); - } - } - } - - public static Color SetColorTransparency(Color clr, int Transparency) - { - return Color.FromArgb((byte)Transparency, clr.R, clr.G, clr.B); - } - - public static Color DefaultTextColor = SystemAccentColorLight2; - public static Color DefaultTextSelectionColor = SystemAccentColor; - public static Color DefaultTextBackgroundColor = Color.FromArgb(0, 0, 0, 0); - public static Color DefaultCommandBarBackgroundColor = SystemAccentColorLight2; - public static Color DefaultTabColorNotFocused = Color.FromArgb(0, 0, 0, 0); - public static Color DefaultTabColorFocused - { - get - { - return Color.FromArgb(120, SystemAccentColorDark2.R, SystemAccentColorDark2.G, SystemAccentColorDark2.B); ; - } - } - - public static Color DefaultAppBackgroundColor = SystemAccentColor; - public static Color DefaultTitleBarBackgroundColor = SystemAccentColor; - public static Color DefaultLineNumberForegroundColor = Colors.LightGray; - public static Color DefaultLineNumberBackgroundColor = Color.FromArgb(10, 0, 0, 0); - public static Color DefaultDialogBackground = SystemAccentColor; - public static Color DefaultStatusbarForegroundColor = Color.FromArgb(255, 255, 255, 255); - public static Color DefaultStatusbarBackgroundColor = Color.FromArgb(100, 0, 0, 0); - - public static Brush ContentDialogBackgroundColor() - { - AppSettings appsettings = new AppSettings(); - return appsettings.CreateBrushWithOrWithoutAcrylic( - appsettings.GetSettingsAsColorWithDefault("DialogBackgroundColor", DefaultDialogBackground)); - } - public static SolidColorBrush ContentDialogForegroundColor() - { - AppSettings appsettings = new AppSettings(); - return new SolidColorBrush(Extensions.Convert.WhiteOrBlackFromColorBrightness( - appsettings.GetSettingsAsColorWithDefault("DialogBackgroundColor", DefaultDialogBackground) - )); - } - public static ElementTheme ContentDialogTheme() - { - AppSettings appsettings = new AppSettings(); - return (ElementTheme)Enum.Parse(typeof(ElementTheme), appsettings.GetSettingsAsInt("ThemeIndex", 0).ToString()); - } - } -} diff --git a/Fastedit/Core/Tab/TabActions.cs b/Fastedit/Core/Tab/TabActions.cs deleted file mode 100644 index f64588c..0000000 --- a/Fastedit/Core/Tab/TabActions.cs +++ /dev/null @@ -1,1320 +0,0 @@ -using Fastedit.Controls.Textbox; -using Fastedit.Dialogs; -using Fastedit.Extensions; -using Fastedit.Helper; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Numerics; -using System.Runtime.InteropServices.WindowsRuntime; -using System.Text; -using System.Threading.Tasks; -using Windows.ApplicationModel.Activation; -using Windows.Storage; -using Windows.Storage.AccessCache; -using Windows.Storage.Pickers; -using Windows.UI.Popups; -using Windows.UI.ViewManagement; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Input; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Shapes; -using static System.Net.WebRequestMethods; -using muxc = Microsoft.UI.Xaml.Controls; -using Path = System.IO.Path; -using StringBuilder = Fastedit.Extensions.StringBuilder; - -namespace Fastedit.Core.Tab -{ - public class TabActions - { - //Class implementations - private readonly muxc.TabView TextTabControl; - private readonly static AppSettings appsettings = new AppSettings(); - private readonly static TabDataBase tabdatabase = new TabDataBase(); - private readonly MainPage mainpage = null; - private readonly static TabPageHelper tabpagehelper = new TabPageHelper(); - private readonly static SaveFileHelper savefilehelper = new SaveFileHelper(); - private StorageFolder DatabaseFolder = null; - //Other variables - public muxc.TabViewItem SettingsTabPage = null; - private readonly DispatcherTimer CloseTabsTimerToSaveDatabase = new DispatcherTimer - { - Interval = new TimeSpan(0, 0, 0, 5) - }; - - public void ShowInfobar(string Content, string Title = "", muxc.InfoBarSeverity severity = muxc.InfoBarSeverity.Warning, int Time = 5) - { - mainpage.ShowInfobar(Content, Title, severity, Time); - } - public void ShowInfobar(muxc.InfoBar infobar) - { - mainpage.ShowInfobar(infobar); - } - - //Initialisation - public TabActions(muxc.TabView TabControl, MainPage mainpage = null) - { - this.mainpage = mainpage; - if (this.mainpage == null) - this.mainpage = new MainPage(); - - TextTabControl = TabControl; - CloseTabsTimerToSaveDatabase.Tick += CloseTabsTimerToSaveDatabase_Tick; - } - - public bool SettingsPageOpened() - { - return SettingsTabPage != null; - } - public int GetTabItemCount() - { - if (SettingsPageOpened()) - { - return TextTabControl.TabItems.Count - 1; - } - else - { - return TextTabControl.TabItems.Count; - } - } - public object[] GetTabItemArray() - { - if (SettingsPageOpened()) - { - var lst = TextTabControl.TabItems.ToList(); - lst.Remove(SettingsTabPage); - return lst.ToArray(); - } - else - { - return TextTabControl.TabItems.ToArray(); - } - } - public IList GetTabItems() - { - if (SettingsPageOpened()) - { - var lst = TextTabControl.TabItems.ToList(); - lst.Remove(SettingsTabPage); - return lst; - } - else - { - return TextTabControl.TabItems; - } - } - //Get the number of actual visible tabpages: - public int GetShownTabPagesCount() - { - int VisibleItemCount = 0; - for (int i = 0; i < TextTabControl.TabItems.Count; i++) - { - if (TextTabControl.TabItems[i] is muxc.TabViewItem Tab) - { - if (Tab.Visibility == Visibility.Visible) - VisibleItemCount++; - } - } - return VisibleItemCount; - } - public List GetShownTabPages() - { - List visibleItems = new List(); - for (int i = 0; i < TextTabControl.TabItems.Count; i++) - { - if (TextTabControl.TabItems[i] is muxc.TabViewItem Tab) - { - if (Tab.Visibility == Visibility.Visible) - visibleItems.Add(Tab); - } - } - return visibleItems; - } - - //Events - private void TextControlBox_TextChangedevent(TextControlBox sender) - { - tabpagehelper.SetTabModified(GetSelectedTabPage(), true); - } - private void TabPage_RightTapped(object sender, RightTappedRoutedEventArgs e) - { - TabPageFlyout.CreateFlyoutForTab( - TextTabControl, mainpage, sender, tabpagehelper.GetTabReadOnly(sender as muxc.TabViewItem) - ).ShowAt(sender as UIElement, e.GetPosition(sender as UIElement)); - } - private void Tcb_PointerPressed(object sender, PointerRoutedEventArgs e) - { - var point = e.GetCurrentPoint(sender as UIElement); - if (point.Properties.IsXButton2Pressed) - { - SelectNextTab(); - } - else if (point.Properties.IsXButton1Pressed) - { - SelectPreviousTab(); - } - } - - //Get Textbox & Tabpage - public TextControlBox GetTextBoxFromSelectedTabPage() - { - if (TextTabControl.SelectedIndex < GetTabItemCount() && TextTabControl.SelectedIndex > -1) - { - if (GetTabItemArray()[TextTabControl.SelectedIndex] is muxc.TabViewItem tab) - { - if (tab.Content is TextControlBox tb) - return tb; - } - } - return null; - } - public TextControlBox GetTextBoxFromTabPage(muxc.TabViewItem TabPage) - { - if (TabPage != null) - { - if (TabPage.Content is TextControlBox tb) - return tb; - } - return null; - } - public muxc.TabViewItem GetSelectedTabPage() - { - if (TextTabControl.SelectedItem is muxc.TabViewItem Tab) - return Tab; - return null; - } - public muxc.TabViewItem GetTabPageByName(string Name) - { - var control = TextTabControl.FindName(Name); - if (control == null) return null; - if (control is muxc.TabViewItem tab) - return tab; - return null; - } - - //New Tab - public muxc.TabViewItem NewTab() - { - var TabPage = NewTabPage(); - var tcb = NewTextBox(); - tcb.IsModified = false; - tcb.Header = NewTabTitleName(); - tcb.IdentifierName = NewTabName(); - tcb.FilePath = string.Empty; - tcb.FileToken = string.Empty; - - TabPage.Header = tcb.Header; - TabPage.Content = tcb; - TabPage.Name = $"{tcb.IdentifierName}.Tab"; - - TextTabControl.TabItems.Add(TabPage); - TextTabControl.SelectedItem = TabPage; - return TabPage; - } - public muxc.TabViewItem NewAllParametersTab(TabDataForDatabase document, bool AddToTabControl = true, StorageFile file = null) - { - TextControlBox tcb = NewTextBox(); - muxc.TabViewItem TabPage = NewTabPage(); - - tcb.TextBeforeLastSaved = string.Empty; - tcb.FontSizeWithoutZoom = appsettings.GetSettingsAsInt("FontSize", DefaultValues.DefaultFontsize); - tcb.IsModified = document.TabModified; - tcb.Header = document.TabHeader; - tcb.IdentifierName = document.TabName; - tcb.TempFile = document.TabTemp; - tcb.FilePath = document.TabPath; - tcb.DataBaseName = document.DataBaseName; - tcb.FileToken = document.TabToken; - tcb.IsReadOnly = document.TabReadOnly; - tcb.SetFontZoomFactor(document.ZoomFactor); - tcb.WordWrap = document.WordWrap; - tcb.TabSaveMode = document.TabSaveMode; - tcb.tabdatafromdatabase = document; - - if (file != null) - { - tcb.Storagefile = file; - } - - tcb.SetEncoding(Encodings.IntToEncoding(document.TabEncoding)); - - TabPage.Content = tcb; - TabPage.Name = $"{tcb.IdentifierName}.Tab"; - TabPage.Header = tcb.Header; - if (document.TabReadOnly) - TabPage.IconSource = new muxc.SymbolIconSource() { Symbol = Symbol.ProtectedDocument }; - else - TabPage.IconSource = - new muxc.FontIconSource - { - FontFamily = new FontFamily("Segoe MDL2 Assets"), - Glyph = appsettings.GetSettingsAsString("TabIconId", - DefaultValues.DefaultTabIconId) - }; - - tcb.Margin = mainpage.TextBoxMargin(); - - - if (AddToTabControl == true) - { - TextTabControl.TabItems.Add(TabPage); - TextTabControl.SelectedItem = TabPage; - } - return TabPage; - } - private TextControlBox NewTextBox() - { - TextControlBox tcb = new TextControlBox(); - tcb.TextChangedevent += TextControlBox_TextChangedevent; - tcb.PointerPressed += Tcb_PointerPressed; - tcb.FilePath = string.Empty; - tcb.FontFamily = new FontFamily(appsettings.GetSettingsAsString("FontFamily", DefaultValues.DefaultFontFamily)); - tcb.SetEncoding(Encoding.Default); - tcb.TabSaveMode = TabSaveMode.SaveAsTemp; - tcb.Storagefile = null; - tcb.WordWrap = TextWrapping.NoWrap; - tcb.HorizontalAlignment = HorizontalAlignment.Stretch; - tcb.VerticalAlignment = VerticalAlignment.Stretch; - tcb.MarkdownPreview = false; - tcb.IsHandWritingEnabled = appsettings.GetSettingsAsBool("HandwritingEnabled", DefaultValues.HandWritingEnabled); - tcb.ShowSelectionFlyout = appsettings.GetSettingsAsBool("TextboxShowSelectionFlyout", false); - //Designs - tcb.LineHighlighter = appsettings.GetSettingsAsBool("LineHighlighter"); - tcb.FontSize = appsettings.GetSettingsAsInt("FontSize", DefaultValues.DefaultFontsize); - tcb.LineNumberForeground = appsettings.GetSettingsAsColorWithDefault("LineNumberForegroundColor", DefaultValues.DefaultLineNumberForegroundColor); - tcb.LineNumberBackground = appsettings.GetSettingsAsColorWithDefault("LineNumberBackgroundColor", DefaultValues.DefaultLineNumberBackgroundColor); - tcb.ShowLineNumbers = appsettings.GetSettingsAsBool("ShowLineNumbers", true); - tcb.Background = appsettings.GetSettingsAsColorWithDefault("TextBackgroundColor", DefaultValues.DefaultTextBackgroundColor); - tcb.TextColor = appsettings.GetSettingsAsColorWithDefault("TextColor", DefaultValues.DefaultTextColor); - tcb.TextSelectionColor = appsettings.GetSettingsAsColorWithDefault("TextSelectionColor", DefaultValues.DefaultTextSelectionColor); - tcb.SpellChecking = appsettings.GetSettingsAsBool("Spellchecking", DefaultValues.SpellCheckingEnabled); - return tcb; - } - private muxc.TabViewItem NewTabPage() - { - var TabPage = new muxc.TabViewItem(); - TabPage.RightTapped += TabPage_RightTapped; - TabPage.IconSource = - new muxc.FontIconSource - { - FontFamily = new FontFamily("Segoe MDL2 Assets"), - Glyph = appsettings.GetSettingsAsString("TabIconId", DefaultValues.DefaultTabIconId) - }; - TabPage.CornerRadius = DefaultValues.DefaultTabCornerRadius; - TabPage.HorizontalAlignment = HorizontalAlignment.Stretch; - TabPage.VerticalAlignment = VerticalAlignment.Stretch; - return TabPage; - } - - private string NewTabName() - { - int count = 1; - string TabName = "Tab" + count; - - if (GetTabItemCount() < 1) - { - return TabName; - } - else - { - while (count < GetTabItemCount() + 1) - { - TabName = "Tab" + count; - count++; - - if (GetTabPageByName(TabName + ".Tab") == null) - { - break; - } - else - { - TabName = "Tab" + count; - } - } - return TabName; - } - } - private string NewTabTitleName() - { - var NewDocName = appsettings.GetSettingsAsString("NewTabTitleName", DefaultValues.NewDocName); - string Extension = Path.GetExtension(NewDocName); - string outname = StringBuilder.ReplaceLastOccurenceInString(NewDocName, Extension, ""); - int doccount = 0; - - for (int i = 0; i < GetTabItemCount(); i++) - { - if (TabHasTitle(outname + doccount)) - { - doccount++; - } - else - { - break; - } - } - return outname + doccount + Extension; - } - private bool TabHasTitle(string Title) - { - var TabItems = GetTabItems(); - for (int i = 0; i < TabItems.Count; i++) - { - if (TabItems[i] is muxc.TabViewItem tab) - { - string Header = tab.Header.ToString(); - string ext = Path.GetExtension(Header); - if (ext != null && ext != string.Empty) - { - if (Header.Remove(Header.Length - ext.Length) == Title) - { - return true; - } - } - } - } - return false; - } - - public void SelectNextTab() - { - int IndexToSelect = TextTabControl.SelectedIndex + 1; - if (TextTabControl.TabItems.Count > IndexToSelect && IndexToSelect >= 0) - { - TextTabControl.SelectedIndex = IndexToSelect; - } - } - public void SelectPreviousTab() - { - int IndexToSelect = TextTabControl.SelectedIndex - 1; - if (TextTabControl.TabItems.Count > IndexToSelect && IndexToSelect >= 0) - { - TextTabControl.SelectedIndex = IndexToSelect; - } - } - - //Tabs: - public async Task FileExist(muxc.TabViewItem Tab) - { - try - { - await StorageApplicationPermissions.FutureAccessList.GetFileAsync(tabpagehelper.GetTabToken(Tab)); - return true; - } - catch (FileNotFoundException) { return false; } - catch (UnauthorizedAccessException) { return false; } - catch (ArgumentException) { return false; } - } - - /// - /// Moves the file to the inbuild recyclebin - /// - /// The file to move to - /// Wether the function succeed or failed - private async Task MoveFileToRecycleBin(muxc.TabViewItem Tab) - { - if (GetTextBoxFromTabPage(Tab) is TextControlBox textbox) - { - StorageFolder recylcebinfolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(DefaultValues.RecycleBin_FolderName, CreationCollisionOption.OpenIfExists); - StorageFile file = await recylcebinfolder.CreateFileAsync(textbox.Header, CreationCollisionOption.GenerateUniqueName); - - return await savefilehelper.WriteTextToFile(file, textbox.Encoding, textbox.GetText(), textbox.TabSaveMode); - } - return false; - } - public async Task OpenFileFromRecylceBin(StorageFile file, string Filename) - { - try - { - if (file != null) - { - var (Succed, TabPage) = await DoOpenFile(TabPage: null, file: file, TabSaveMode.SaveAsTemp, SaveDatabase: false, false, "", false, true, true); - var textbox = tabpagehelper.GetTextBoxFromTabPage(TabPage); - if (textbox == null) - return false; - - textbox.FilePath = ""; - textbox.FileToken = ""; - textbox.Storagefile = null; - textbox.DataBaseName = ""; - - if (!TextTabControl.TabItems.Contains(TabPage)) - { - TextTabControl.TabItems.Add(TabPage); - TextTabControl.SelectedIndex = GetTabItemCount() - 1; - } - tabpagehelper.SetTabStorageFile(TabPage, file); - return Succed; - } - } - catch (Exception e) - { - ShowInfobar(ErrorDialogs.OpenErrorDialog(e.Message)); - } - return false; - } - - //Close and Load Tabs - /// - /// Saves all tab data to the database - /// - /// - public async Task SaveAllTabChanges(bool DeleteAllTemporarySavedFiles = true) - { - try - { - if (DatabaseFolder == null) - { - DatabaseFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(DefaultValues.Database_FolderName, CreationCollisionOption.OpenIfExists); - } - if(DeleteAllTemporarySavedFiles) - tabdatabase.DeleteAllTemporarySavedFiles(DatabaseFolder.Path); - - var tabitems = GetTabItems(); - for (int i = 0; i < tabitems.Count; i++) - { - if (tabitems[i] is muxc.TabViewItem Tab) - { - await SaveTempFile(Tab, DatabaseFolder); - } - else - { - ShowInfobar(ErrorDialogs.GetTabErrorDialog()); - } - } - return await tabdatabase.SaveTabPageData(TextTabControl); - } - catch (Exception e) - { - Debug.WriteLine("Exception in TabActions --> SaveAllTabChanges:" + "\n" + e.Message); - return false; - } - } - - public async Task SetTextFromBuffer(muxc.TabViewItem Tab) - { - var textbox = GetTextBoxFromTabPage(Tab); - if (textbox != null) - { - if (!textbox.TextLoaded) - { - textbox.TextLoaded = true; - await textbox.SetText(textbox.TextBuffer, textbox.IsModified); - textbox.SetSelection(textbox.tabdatafromdatabase.TabSelStart, textbox.tabdatafromdatabase.TabSelLenght); - textbox.ScrollIntoView(); - textbox.UpdateRendering(); - } - } - } - /// - /// Close tabs and save to database on application exit - /// - /// the status of the function - public async Task CloseTabs() - { - try - { - if (GetTabItemCount() == 0) - return await SaveAllTabChanges(); - - //Check whether to save tabs, and reopen on restart or show asktosave-dialog and close them - if (appsettings.GetSettingsAsBool("LoadRecentTabs", true)) - { - if (await SaveAllTabChanges() == false) - { - throw new Exception(); - } - return true; - } - else - { - var items = TextTabControl.TabItems.ToList(); - for (int i = 0; i < items.Count; i++) - { - if (items[i] is muxc.TabViewItem Tab) - { - if(Tab.Content is TextControlBox tb) - { - if (tabpagehelper.GetIsModified(Tab)) - { - bool succed = await savefilehelper.ShowAskSaveDialogForTab(Tab, false); - if (succed == false) - return false; - } - if (await RemoveTab(Tab) == false) - return false; - } - } - } - return true; - } - } - catch - { - var dlgres = await new InfoBox(AppSettings.GetResourceStringStatic("ErrorDialogs_SaveDataBaseError/Text"), appsettings.GetResourceString("ErrorDialogs_Title_DataBaseError/Text")) - { - CloseButtonText = AppSettings.GetResourceStringStatic("ErrorDialogs_SaveDataBaseError_Close/Text"), - PrimaryButtonText = AppSettings.GetResourceStringStatic("ErrorDialogs_SaveDataBaseError_Retry/Text"), - SecondaryButtonText = AppSettings.GetResourceStringStatic("ErrorDialogs_SaveDataBaseError_CloseAnyway/Text"), - }.ShowAsync(); - if (dlgres == ContentDialogResult.Primary) - { - return await CloseTabs(); - } - else if (dlgres == ContentDialogResult.Secondary) - { - return true; - } - } - return false; - } - /// - /// Loads the tabs from the database and retrives everything from the last saved season - /// - /// Whether load the tabs from latest backup or from the default database folder - /// - /// - public async Task LoadTabs(bool FromBackup) - { - try - { - //Datalist for tab to save tabpages to - var tabdatafromdatabase = await tabdatabase.GetTabData(FromBackup); - if (tabdatafromdatabase == null) - return false; - - int LastSelectedTabIndex = 0; - var MethodeSucced = true; - - TextTabControl.TabItems.Clear(); - string[] tempFilePaths = Directory.GetFiles( - Path.Combine(ApplicationData.Current.LocalFolder.Path, FromBackup ? DefaultValues.Backup_FolderName : DefaultValues.Database_FolderName) - ); - - async Task<(string Text, Encoding encoding, bool succed)> getTabtext(TextControlBox textbox) - { - for (int fc = 0; fc < tempFilePaths.Length; fc++) - { - if (Path.GetFileName(tempFilePaths[fc]) == textbox.TempFile) - { - return await ReadTextFromPathAsync(tempFilePaths[fc]); - } - } - return ("", null, false); - } - - //Create a list with the tabs and store them into it - List TabItemList = new List(); - for (int i = 0; i < tabdatafromdatabase.Count; i++) - { - TabDataForDatabase DataItem = tabdatafromdatabase[i]; - - var Tab = NewAllParametersTab(DataItem, false); - - if (Tab.Content is TextControlBox textbox) - { - var result = await getTabtext(textbox); - if (result.succed) - { - //Load the text just for the selected tab - if(i == DataItem.CurrentSelectedTabIndex) - { - textbox.TextLoaded = true; - await textbox.SetText(result.Text, textbox.IsModified); - textbox.SetSelection(textbox.tabdatafromdatabase.TabSelStart, textbox.tabdatafromdatabase.TabSelLenght); - textbox.ScrollIntoView(); - textbox.UpdateRendering(); - } - else - textbox.TextBuffer = result.Text; - - //To update the tab header: - tabpagehelper.SetTabModified(Tab, DataItem.TabModified); - textbox.MarkdownPreview = DataItem.Markdown; - if(DataItem.TabToken != string.Empty) - { - var file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(DataItem.TabToken); - if (file != null) - textbox.Storagefile = file; - } - LastSelectedTabIndex = DataItem.CurrentSelectedTabIndex; - TabItemList.Add(Tab); - } - else - { - MethodeSucced = false; - } - } - } - - //When an error happened - if (!MethodeSucced) - { - ShowInfobar(ErrorDialogs.LoadTabsError()); - return false; - } - //Add the items from list to TabControl - for (int i = 0; i < TabItemList.Count; i++) - { - TextTabControl.TabItems.Add(TabItemList[i]); - } - - //Select the recent opened tab - if (TextTabControl.TabItems.Count <= LastSelectedTabIndex) - { - TextTabControl.SelectedIndex = LastSelectedTabIndex - 1 > 0 ? LastSelectedTabIndex - 1 : 0; - } - else - { - TextTabControl.SelectedIndex = LastSelectedTabIndex; - } - - return MethodeSucced; - } - catch - { - ShowInfobar(ErrorDialogs.LoadTabsError()); - } - return false; - } - - /// - /// Removes tab from TabView and clears all data from memory - /// - /// - /// - public async Task RemoveTab(muxc.TabViewItem Tab) - { - try - { - if (tabpagehelper.GetIsModified(Tab)) - { - await MoveFileToRecycleBin(Tab); - } - - var token = tabpagehelper.GetTabToken(Tab); - //Remove Token from futureaccesslist - if (StorageApplicationPermissions.FutureAccessList.ContainsItem(token) && token.Length > 0) - { - StorageApplicationPermissions.FutureAccessList.Remove(token); - } - - return TextTabControl.TabItems.Remove(Tab); - } - catch (Exception e) - { - await new InfoBox("Remove tab error\n" + e.Message, "Error").ShowAsync(); - return false; - } - } - private async Task CloseTab(muxc.TabViewItem Tab) - { - try - { - if (Tab.Visibility == Visibility.Collapsed) - return true; - var textbox = GetTextBoxFromTabPage(Tab); - if (textbox != null) - { - //If the tab is newly created and has no content - if (textbox.GetText().Length == 0 && textbox.IsModified == false && textbox.FilePath.Length == 0 && textbox.DataBaseName.Length == 0) - { - return await RemoveTab(Tab); - } - else - { - var tabsavemode = textbox.TabSaveMode; - if (tabsavemode == TabSaveMode.SaveAsTemp) - { - ContentDialogResult dlgres; - //Choose whether use the AskSaveDialogNeverSaved or AskSaveDialog - if (textbox.FileToken.Length == 0) - dlgres = await SaveDialogs.AskSaveDialogNeverSaved(Tab); - else - dlgres = await SaveDialogs.AskSaveDialog(Tab); - - //If Save-button is pressed: - if (dlgres == ContentDialogResult.Primary) - { - if (await savefilehelper.Save(Tab)) - { - return await RemoveTab(Tab); - } - return false; - } - //If don't-save-button is pressed: - else if (dlgres == ContentDialogResult.Secondary) - { - return await RemoveTab(Tab); - } - //If cancel-button is pressed: - return false; - } - else if (tabsavemode == TabSaveMode.SaveAsFile || tabsavemode == TabSaveMode.SaveAsDragDrop) - { - //If the file exists - if (await FileExist(Tab)) - { - if (textbox.IsModified) - { - bool res = await savefilehelper.ShowAskSaveDialogForTab(Tab, false); - if (res) - { - return await RemoveTab(Tab); - } - } - else - { - return await RemoveTab(Tab); - } - } - //If the file doesn't exist - else - { - bool res = await savefilehelper.ShowAskSaveDialogForTab(Tab, true); - if (res) - { - return await RemoveTab(Tab); - } - } - - } - } - } - } - catch (Exception e) - { - Debug.WriteLine("Exception in TabActions -> CloseTab\n" + e.Message); - - ShowInfobar(ErrorDialogs.CloseTabError()); - } - return false; - } - public async Task CloseAllButThis(muxc.TabViewItem Tab) - { - List tabs = GetShownTabPages(); - for (int i = 0; i < tabs.Count; i++) - { - if (tabs[i] != null && tabs[i] != Tab) - if (await CloseTab(tabs[i] as muxc.TabViewItem) == false) - return; - } - await SaveAllTabChanges(); - } - public async Task CloseAllLeft(muxc.TabViewItem Tab) - { - int CurrentTabIndex = TextTabControl.TabItems.IndexOf(Tab); - var tabrange = GetShownTabPages().ToList().GetRange(0, CurrentTabIndex); - for (int i = 0; i < tabrange.Count; i++) - { - if (tabrange[i] != null) - { - if (await CloseTab(tabrange[i] as muxc.TabViewItem) == false) - return; - } - } - - await SaveAllTabChanges(); - } - public async Task CloseAllRight(muxc.TabViewItem Tab) - { - int CurrentTabIndex = TextTabControl.TabItems.IndexOf(Tab); - List tabpages = GetShownTabPages().ToList(); - if (CurrentTabIndex < 0 || CurrentTabIndex >= tabpages.Count) - return false; - var tabrange = tabpages.GetRange(CurrentTabIndex + 1, tabpages.Count - CurrentTabIndex -1); - for (int i = 0; i< tabrange.Count; i++) - { - if (tabrange[i] != null) - { - if (await CloseTab(tabrange[i] as muxc.TabViewItem) == false) - return false; - } - } - return await SaveAllTabChanges(); - } - public async Task CloseAllWithoutSave() - { - List tabs = GetShownTabPages(); - for (int i = 0; i < tabs.Count; i++) - { - if (tabs[i] != null) - await RemoveTab(tabs[i] as muxc.TabViewItem); - } - - await SaveAllTabChanges(); - } - public async Task CloseAllTabs() - { - List TabsToRemove = GetShownTabPages(); - for (int i = 0; i < TabsToRemove.Count; i++) - { - var tab = TabsToRemove[i]; - if(tab != null) - { - if (await CloseTab(tab as muxc.TabViewItem) == false) - return; - } - } - await SaveAllTabChanges(); - } - - public async Task CloseTabAndSaveDataBase(muxc.TabViewItem Tab) - { - bool res = await CloseTab(Tab); - CloseTabsTimerToSaveDatabase.Stop(); - CloseTabsTimerToSaveDatabase.Start(); - return res; - } - private async void CloseTabsTimerToSaveDatabase_Tick(object sender, object e) - { - if (sender is DispatcherTimer timer) - { - timer.Stop(); - await SaveAllTabChanges(); - } - } - - /// - /// Save the file to the temp-buffer - /// - /// - /// wheater the save succed - public async Task SaveTempFile(muxc.TabViewItem TabPage, StorageFolder folder) - { - try - { - if (TabPage.Content is TextControlBox textbox) - { - var filename = GetTextBoxFromTabPage(TabPage).Name; - StorageFile file = await folder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists); - if (file != null) - { - //I really don't know why this happens, but every time I just use the first CreateFileAsync methode for the file Tab1, it wont be created. - //But all the other files are. So this is the simplest solution to fix this, because I DON'T know :( - if (textbox.Name == "Tab1") - file = await folder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists); - - System.IO.File.WriteAllText(Path.Combine(folder.Path, filename), textbox.GetText()); - textbox.TempFile = file.Name; - if (textbox.TabSaveMode == TabSaveMode.SaveAsTemp) - textbox.Storagefile = file; - return true; - } - } - } - catch (Exception e) - { - ShowInfobar("Error while saving temporary file to database\n" + e.Message, "Error"); - } - return false; - } - - /// - /// The process to open a file - /// When the TabPage parameter is null, it automatically creates a new tab - /// When the Filetoken parameter is null it creates a new token - /// - /// The tabpage to display the file, when null a new tab will be created - /// The file to read from - /// The TabSaveMode - /// Whether the file is locked - /// Save database after opening or not - /// The token of the file - /// Whether the file is modified or not - /// Whether create a new token for the file or use the old one, when the token is emty it creates a new one - /// Check whether the file is already opened or not - /// Update the UI after opening - /// The status of the file and the TabPage, which is created in this methode - public async Task<(bool Succed, muxc.TabViewItem TabPage)> DoOpenFile( - muxc.TabViewItem TabPage, StorageFile file, TabSaveMode tabsavemode, bool SaveDatabase = true, - bool Locked = false, string FileToken = "", bool IsModified = false, bool CreateNewToken = true, - bool CheckForFileAlreadyOpened = true) - { - async Task<(bool, muxc.TabViewItem)> open() - { - var (Text, encoding, Succed) = await ReadTextFromFileAsync(file); - if (Succed) - { - if (FileToken.Length == 0 || CreateNewToken) - { - FileToken = StorageApplicationPermissions.FutureAccessList.Add(file); - } - - if (TabPage == null) - { - TabPage = NewAllParametersTab(new TabDataForDatabase - { - TabName = NewTabName(), - TabHeader = file.Name, - TabToken = FileToken, - TabModified = false, - TabPath = file.Path, - DataBaseName = file.Name, - TabTemp = string.Empty, - TabReadOnly = false, - ZoomFactor = 100, - TabSaveMode = tabsavemode, - TabSelLenght = 0, - TabSelStart = 0, - TabEncoding = 0, - WordWrap = TextWrapping.NoWrap, - }, true, file); - } - var textbox = GetTextBoxFromTabPage(TabPage); - Debug.WriteLine("TabModified:" + textbox.IsModified); - if (textbox != null) - { - await Task.Run(() => textbox.SetText(Text)); - textbox.SetEncoding(encoding); - textbox.TabSaveMode = tabsavemode; - textbox.FilePath = file.Path; - textbox.DataBaseName = file.Name; - textbox.FileToken = FileToken; - textbox.IsReadOnly = Locked; - textbox.Storagefile = file; - textbox.IsModified = IsModified; - if (SaveDatabase) - await SaveAllTabChanges(); - return (true, TabPage); - } - } - return (false, null); - } - - if (TabPage == null && CheckForFileAlreadyOpened) - { - muxc.TabViewItem tab = FileAlreadyOpened(file); - if (tab != null) - { - TextTabControl.SelectedItem = tab; - return (true, tab); - } - } - return await open(); - } - - /// - /// Open a file and create a new tab - /// - /// the Storagefile to open - public async Task OpenStorageFile(StorageFile file, TabSaveMode tabsavemode = TabSaveMode.SaveAsFile) - { - try - { - if (file != null) - { - var (Succed, TabPage) = await DoOpenFile(TabPage: null, file: file, tabsavemode: tabsavemode, SaveDatabase: false, false, "", false, true, true); - if (Succed) - { - if (!TextTabControl.TabItems.Contains(TabPage)) - { - TextTabControl.TabItems.Add(TabPage); - TextTabControl.SelectedItem = TabPage; - } - tabpagehelper.SetTabStorageFile(TabPage, file); - tabpagehelper.SetTabModified(TabPage, false); - } - return Succed; - } - } - catch (Exception e) - { - ShowInfobar(ErrorDialogs.OpenErrorDialog(e.Message)); - } - return false; - } - - /// - /// Open a file with open file picker - /// - /// Tab with the content of the opened file - public async Task> OpenFile() - { - try - { - var picker = new FileOpenPicker - { - ViewMode = PickerViewMode.Thumbnail, - SuggestedStartLocation = PickerLocationId.DocumentsLibrary - }; - - //Add the fileextensions to the OpenFilePicker - FileExtensions fileextentions = new FileExtensions(); - - for(int i = 0; i tabs = new List(); - var files = await picker.PickMultipleFilesAsync(); - for (int i = 0; i < files.Count; i++) - { - if (files[i] != null) - { - //Open the file with the DoOpenFile function - var (Succed, TabPage) = await DoOpenFile(null, files[i], TabSaveMode.SaveAsFile, true); - if(Succed) - tabs.Add(TabPage); - } - } - return tabs; - } - catch - { - ShowInfobar(ErrorDialogs.OpenErrorDialog()); - return null; - } - } - - public async Task OpenFileFromCommandLine(CommandLineLaunchNavigationParameter commandLine) - { - try - { - if (commandLine.Arguments.Length < 1) - return false; - - string path = StringBuilder.GetAbsolutePath(commandLine.Arguments, commandLine.CurrentDirectoryPath); - if (path == null || path.Length < 1) - return false; - - StorageFile file = await StorageFile.GetFileFromPathAsync(path); - if (file != null) - { - return await OpenStorageFile(file, TabSaveMode.SaveAsFile); - } - } - catch (FileNotFoundException) - { - ShowInfobar(InfoBarMessages.FileNotFound, InfoBarMessages.FileNotFoundTitle, muxc.InfoBarSeverity.Error); - } - catch (UnauthorizedAccessException) - { - ShowInfobar(InfoBarMessages.FileNoAccess, InfoBarMessages.FileNoAccessTitle, muxc.InfoBarSeverity.Error); - } - catch (ArgumentException) - { - ShowInfobar(InfoBarMessages.FileInvalidPath, InfoBarMessages.FileInvalidPathTitle, muxc.InfoBarSeverity.Error); - } - return false; - } - - public async Task OpenFilesFromEvent(FileActivatedEventArgs e) - { - bool res = true; - for (int i = 0; i < e.Files.Count; i++) - { - if (e.Files[i] is StorageFile file) - { - if (await OpenStorageFile(file) == false) - { - res = false; - } - } - } - return res; - } - - /// - /// Check it file is already opened - /// - /// the file which is compared to the other tabs - /// Another tablist when using a custom one - /// Compare also the text - /// The text - /// null when the file is not already opened; the tab in which the file is already opened - public muxc.TabViewItem FileAlreadyOpened(StorageFile file, List OtherTabList = null, bool CheckTextboxContent = false, string TextBoxContent = "") - { - muxc.TabViewItem DoCheck(muxc.TabViewItem Tab) - { - if (file.Path == tabpagehelper.GetTabFilepath(Tab)) - { - if (CheckTextboxContent) - { - if (GetTextBoxFromTabPage(Tab).GetText() == TextBoxContent) - { - return Tab; - } - return null; - } - - return Tab; - } - return null; - } - - if (OtherTabList == null) - { - for (int i = 0; i < TextTabControl.TabItems.Count; i++) - { - if (TextTabControl.TabItems[i] is muxc.TabViewItem Tab) - { - if (DoCheck(Tab) != null) - { - return Tab; - } - } - } - } - else - { - for (int i = 0; i < OtherTabList.Count; i++) - { - if (OtherTabList[i] is muxc.TabViewItem Tab) - { - if (DoCheck(Tab) != null) - { - return Tab; - } - } - } - } - return null; - } - - public async Task OpenFileWithEncoding(muxc.TabViewItem tab, Encoding enc) - { - try - { - if (tabpagehelper.GetIsModified(tab)) - { - var dlgres = await SaveDialogs.AskSaveDialog(tab); - if (dlgres == ContentDialogResult.Primary) - { - var saveres = await savefilehelper.Save(tab); - if (!saveres) - return false; - } - else if (dlgres == ContentDialogResult.None) - return false; - } - - if (tab == null) - return false; - - var tb = tabpagehelper.GetTextBoxFromTabPage(tab); - if (tb == null) - return false; - - var res = await ReadTextFromFileAsync(tb.Storagefile, enc); - if (res.Succed) - { - tb.Encoding = enc; - await tb.SetText(res.Text); - tabpagehelper.SetTabModified(tab, false); - return true; - } - } - catch (Exception ex) - { - ShowInfobar(ex.Message); - } - return false; - } - - /// - /// Rename the selected file - /// - /// The new name - /// wheter the rename function succed or not - public async Task RenameFile(string name) - { - try - { - muxc.TabViewItem Tabpage = GetSelectedTabPage(); - if (Tabpage != null) - { - if (name.Length < 1 && !StringBuilder.IsValidFilename(name)) - { - var infoBox = new InfoBox("The filename is invalid!"); - await infoBox.ShowAsync(); - return false; - } - else - { - if (GetTextBoxFromTabPage(Tabpage) is TextControlBox textbox) - { - if (tabpagehelper.GetTabSaveMode(Tabpage) != TabSaveMode.SaveAsTemp) - { - await textbox.Storagefile.RenameAsync(name, NameCollisionOption.FailIfExists); - tabpagehelper.SetTabHeader(Tabpage, name); - textbox.FilePath = textbox.Storagefile.Path; - return true; - } - else - { - tabpagehelper.SetTabHeader(Tabpage, name); - return true; - } - } - } - } - } - catch (Exception e) - { - await new InfoBox(e.Message, "Error").ShowAsync(); - } - return false; - } - - /// - /// Read text from Storagefile - /// - /// The file to read from - /// the text read from the file and the encoding of the text - public async Task<(string Text, Encoding encoding, bool Succed)> ReadTextFromFileAsync(StorageFile file, Encoding encoding = null) - { - try - { - if (file == null) - return ("", Encoding.Default, false); - - using (var stream = (await file.OpenReadAsync()).AsStreamForRead()) - { - byte[] buffer = new byte[stream.Length]; - stream.Read(buffer, 0, buffer.Length); - string text = ""; - if(encoding == null) - { - encoding = Encodings.DetectTextEncoding(buffer, out text); - } - text = encoding.GetString(buffer, 0, buffer.Length); - return (text, encoding, true); - } - } - catch (Exception e) - { - ShowInfobar(e.Message + "\nFile: " + tabpagehelper.GetPathFromStorageFile(file)); - return ("", Encoding.Default, false); - } - } - public async Task<(string Text, Encoding encoding, bool Succed)> ReadTextFromPathAsync(string Path) - { - try - { - Encoding encoding = Encoding.Default; - using (var stream = new StreamReader(Path)) - { - byte[] buffer = new byte[stream.BaseStream.Length]; - stream.BaseStream.Read(buffer, 0, buffer.Length); - string text = ""; - text = encoding.GetString(buffer, 0, buffer.Length); - return (text, encoding, true); - } - } - catch (Exception e) - { - await new InfoBox(e.Message + "\nFile: " + Path).ShowAsync(); - return ("", Encoding.Default, false); - } - } - } - -} diff --git a/Fastedit/Core/Tab/TabDataBase.cs b/Fastedit/Core/Tab/TabDataBase.cs deleted file mode 100644 index 3839a96..0000000 --- a/Fastedit/Core/Tab/TabDataBase.cs +++ /dev/null @@ -1,156 +0,0 @@ -using Fastedit.Controls.Textbox; -using Fastedit.Dialogs; -using Fastedit.Extensions; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Threading.Tasks; -using Windows.Storage; -using Windows.UI.Xaml; -using muxc = Microsoft.UI.Xaml.Controls; - -namespace Fastedit.Core.Tab -{ - public class TabDataBase - { - public string DataBaseName = "Tabs.tdb"; - - private async Task ReadFromFile(string Path) - { - using (var reader = new StreamReader(Path)) - { - var txt = await reader.ReadToEndAsync(); - reader.Close(); - reader.Dispose(); - return txt; - } - } - private async Task WriteToFile(string Path, string text) - { - try - { - File.WriteAllText(Path, text); - return true; - } - catch (Exception e) - { - await new InfoBox("Could not write to file\n" + Path).ShowAsync(); - Debug.WriteLine("Exception in TabDataBase --> WriteToFile:" + "\n" + e.Message); - return false; - } - } - - //Create the data to save - public string CreateTabDataBase(muxc.TabView TabView) - { - string outputtext = string.Empty; - int CurrentSelectedTabPageIndex = TabView.SelectedIndex; - - for (int i = 0; i < TabView.TabItems.Count; i++) - { - if (TabView.TabItems[i] is muxc.TabViewItem Tab) - { - if (Tab.Content is TextControlBox tb) - { - tb.tabdatafromdatabase.CurrentSelectedTabIndex = CurrentSelectedTabPageIndex; - outputtext += JsonConvert.SerializeObject(tb.tabdatafromdatabase) + "\n"; - } - } - } - return outputtext; - } - //Creates the database-file in a specified folder - public async Task SaveTabPageData(muxc.TabView TabView) - { - try - { - if (TabView.TabItems.Count == 0) - return true; - - var FilePath = Path.Combine(DefaultValues.LocalFolderPath, DefaultValues.Database_FolderName, DataBaseName); - return await WriteToFile(FilePath, CreateTabDataBase(TabView)); - } - catch (Exception e) - { - await new InfoBox(e.Message).ShowAsync(); - return false; - } - } - - //Gets the data from the default App-Folder or from custom folder - public async Task> GetTabData(bool FromBackup) - { - try - { - List databaseData = new List(); - - string DataBaseFileName = - Path.Combine(DefaultValues.LocalFolderPath, FromBackup ? DefaultValues.Backup_FolderName : DefaultValues.Database_FolderName, DataBaseName); - - if (File.Exists(DataBaseFileName)) - { - var lines = (await ReadFromFile(DataBaseFileName)).Split("\n", StringSplitOptions.RemoveEmptyEntries); - - for (int i = 0; i < lines.Length; i++) - { - databaseData.Add(JsonConvert.DeserializeObject(lines[i])); - } - return databaseData; - } - } - catch (Exception e) - { - Debug.WriteLine("Exception in TabDataBase --> GetTabData:" + "\n" + e.Message); - } - return null; - } - - //Delets all files from backup folder - public void DeleteAllTemporarySavedFiles(string FolderPath = "") - { - if (FolderPath == "") - { - FolderPath = Path.Combine(DefaultValues.LocalFolderPath, DefaultValues.Database_FolderName); - } - - DirectoryInfo dr = new DirectoryInfo(FolderPath); - - if (dr.Exists) - { - var FilePath = Directory.GetFiles(FolderPath); - for (int i = 0; i < FilePath.Length; i++) - { - if (FilePath[i] != null) - { - File.Delete(FilePath[i]); - } - } - } - } - } - - public class TabDataForDatabase - { - public string TabName { get; set; } - public bool TabModified { get; set; } - public string TabHeader { get; set; } - public string TabToken { get; set; } - public string TabPath { get; set; } - public string DataBaseName { get; set; } - public string TabTemp { get; set; } - public bool TabReadOnly { get; set; } - public int TabSelStart { get; set; } - public int TabSelLenght { get; set; } - public TabSaveMode TabSaveMode { get; set; } - public int TabEncoding { get; set; } - public double ZoomFactor { get; set; } - public TextWrapping WordWrap { get; set; } - public int CurrentSelectedTabIndex { get; set; } - public bool Markdown { get; set; } - public bool MarkdownMode2 { get; set; } - public bool MarkdownIsColumn { get; set; } - //public bool IsInSecondaryView { get; set; } - } -} diff --git a/Fastedit/Core/Tab/TabPageFlyout.cs b/Fastedit/Core/Tab/TabPageFlyout.cs deleted file mode 100644 index b869c92..0000000 --- a/Fastedit/Core/Tab/TabPageFlyout.cs +++ /dev/null @@ -1,141 +0,0 @@ -using Fastedit.Controls.Textbox; -using Fastedit.Dialogs; -using Fastedit.Helper; -using Microsoft.UI.Xaml.Controls; -using System; -using Windows.Foundation; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Media; -using muxc = Microsoft.UI.Xaml.Controls; - -namespace Fastedit.Core.Tab -{ - public class TabPageFlyout - { - public static MenuFlyout CreateFlyoutForTab(muxc.TabView tabview, MainPage mainpage, object sender, bool ForLockedTab) - { - if (sender is muxc.TabViewItem TabPage) - { - if (TabPage.Content is TextControlBox tb) - { - if (tb == null) return null; - - var tabactions = new TabActions(tabview); - var tabpagehelper = new TabPageHelper(); - var savefilehelper = new SaveFileHelper(); - - MenuFlyout myFlyout = new MenuFlyout(); - MenuFlyoutItem CloseItem = new MenuFlyoutItem { Text = AppSettings.GetResourceStringStatic("TabRightClickMenu_Close/Text") }; - MenuFlyoutItem LockFile = new MenuFlyoutItem { Text = AppSettings.GetResourceStringStatic("TabRightClickMenu_Lock/Text") }; - MenuFlyoutItem ShareFile = new MenuFlyoutItem { Text = AppSettings.GetResourceStringStatic("TabRightClickMenu_Share/Text") }; - MenuFlyoutItem FileInfo = new MenuFlyoutItem { Text = AppSettings.GetResourceStringStatic("TabRightClickMenu_Info/Text") }; - MenuFlyoutItem SaveFile = new MenuFlyoutItem { Text = AppSettings.GetResourceStringStatic("TabRightClickMenu_Save/Text") }; - MenuFlyoutItem CloseAll = new MenuFlyoutItem { Text = AppSettings.GetResourceStringStatic("TabRightClickMenu_CloseAll/Text") }; - MenuFlyoutItem CloseAllButThis = new MenuFlyoutItem { Text = AppSettings.GetResourceStringStatic("TabRightClickMenu_CloseAll_ButThis/Text") }; - MenuFlyoutItem CloseAllLeft = new MenuFlyoutItem { Text = AppSettings.GetResourceStringStatic("TabRightClickMenu_CloseAll_Left/Text") }; - MenuFlyoutItem CloseAllRight = new MenuFlyoutItem { Text = AppSettings.GetResourceStringStatic("TabRightClickMenu_CloseAll_Right/Text") }; - MenuFlyoutItem CloseAllWithoutSave = new MenuFlyoutItem { Text = AppSettings.GetResourceStringStatic("TabRightClickMenu_CloseAll_WithoutSave/Text") }; - MenuFlyoutItem ExpandToSecondaryView = new MenuFlyoutItem { Text = AppSettings.GetResourceStringStatic("TabRightClickMenu_OpenInNewWindow/Text") }; - - if (ForLockedTab) - { - LockFile.Text = AppSettings.GetResourceStringStatic("TabRightClickMenu_Unlock/Text"); - } - - //Icons: - ShareFile.Icon = new SymbolIcon { Symbol = Symbol.Share }; - LockFile.Icon = new SymbolIcon { Symbol = Symbol.ProtectedDocument }; - SaveFile.Icon = new SymbolIcon { Symbol = Symbol.Save }; - CloseItem.Icon = new FontIcon - { - FontFamily = new FontFamily("Segoe MDL2 Assets"), - Glyph = "\uEF2C" - }; - FileInfo.Icon = new FontIcon - { - FontFamily = new FontFamily("Segoe MDL2 Assets"), - Glyph = "\uE946" - }; - CloseAllLeft.Icon = new FontIcon - { - FontFamily = new FontFamily("Segoe MDL2 Assets"), - Glyph = "\uEC52" - }; - CloseAllRight.Icon = new FontIcon - { - FontFamily = new FontFamily("Segoe MDL2 Assets"), - Glyph = "\uEBE7" - }; - ExpandToSecondaryView.Icon = new FontIcon - { - FontFamily = new FontFamily("Segoe MDL2 Assets"), - Glyph = "\uE78B" - }; - - LockFile.Click += delegate - { - tabpagehelper.SetUnsetLockFile(TabPage); - }; - ShareFile.Click += delegate - { - new ShareFile(tabactions.GetTextBoxFromSelectedTabPage()); - }; - CloseItem.Click += async delegate - { - await tabactions.CloseTabAndSaveDataBase(TabPage); - }; - SaveFile.Click += async delegate - { - await savefilehelper.Save(TabPage); - }; - FileInfo.Click += async delegate - { - await new FileInfoDialog(TabPage).ShowAsync(); - }; - CloseAll.Click += async delegate - { - await tabactions.CloseAllTabs(); - }; - CloseAllButThis.Click += async delegate - { - await tabactions.CloseAllButThis(TabPage); - }; - CloseAllLeft.Click += async delegate - { - await tabactions.CloseAllLeft(TabPage); - }; - CloseAllRight.Click += async delegate - { - await tabactions.CloseAllRight(TabPage); - }; - CloseAllWithoutSave.Click += async delegate - { - await tabactions.CloseAllWithoutSave(); - }; - ExpandToSecondaryView.Click += async delegate - { - await mainpage.secondaryeditinginstance.ExpandTabPageToNewView(TabPage); - }; - - myFlyout.Items.Add(CloseItem); - myFlyout.Items.Add(new MenuFlyoutSeparator()); - myFlyout.Items.Add(FileInfo); - myFlyout.Items.Add(LockFile); - myFlyout.Items.Add(new MenuFlyoutSeparator()); - myFlyout.Items.Add(ShareFile); - myFlyout.Items.Add(ExpandToSecondaryView); - myFlyout.Items.Add(new MenuFlyoutSeparator()); - myFlyout.Items.Add(SaveFile); - myFlyout.Items.Add(new MenuFlyoutSeparator()); - myFlyout.Items.Add(CloseAll); - myFlyout.Items.Add(CloseAllButThis); - myFlyout.Items.Add(CloseAllLeft); - myFlyout.Items.Add(CloseAllRight); - myFlyout.Items.Add(CloseAllWithoutSave); - return myFlyout; - } - } - return null; - } - } -} diff --git a/Fastedit/Designs/Design1.json b/Fastedit/Designs/Design1.json new file mode 100644 index 0000000..e8bfc04 --- /dev/null +++ b/Fastedit/Designs/Design1.json @@ -0,0 +1,108 @@ +{ + "Theme": 2, + "BackgroundType": 0, + "BackgroundColor": { + "A": 100, + "R": 35, + "G": 35, + "B": 35 + }, + "TextColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 255 + }, + "SelectionColor": { + "A": 100, + "R": 150, + "G": 150, + "B": 150 + }, + "LineNumberColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 255 + }, + "LineNumberBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "LineHighlighterBackground": { + "A": 50, + "R": 100, + "G": 100, + "B": 100 + }, + "TextBoxBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "CursorColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 255 + }, + "SearchHighlightColor": { + "A": 150, + "R": 255, + "G": 150, + "B": 100 + }, + "TextboxBackgroundType": 2, + "SelectedTabPageHeaderTextColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 255 + }, + "UnSelectedTabPageHeaderTextColor": { + "A": 255, + "R": 150, + "G": 150, + "B": 150 + }, + "UnselectedTabPageHeaderBackground": { + "A": 10, + "R": 10, + "G": 10, + "B": 10 + }, + "SelectedTabPageHeaderBackground": { + "A": 100, + "R": 30, + "G": 30, + "B": 30 + }, + "StatusbarTextColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 255 + }, + "StatusbarBackgroundColor": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "DialogBackgroundType": 2, + "DialogBackgroundColor": { + "A": 255, + "R": 35, + "G": 35, + "B": 35 + }, + "DialogTextColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 255 + } +} \ No newline at end of file diff --git a/Fastedit/Designs/Design2.json b/Fastedit/Designs/Design2.json new file mode 100644 index 0000000..ab6004e --- /dev/null +++ b/Fastedit/Designs/Design2.json @@ -0,0 +1,108 @@ +{ + "Theme": 1, + "BackgroundColor": { + "A": 100, + "R": 255, + "G": 255, + "B": 255 + }, + "TextColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 0 + }, + "SelectionColor": { + "A": 100, + "R": 100, + "G": 100, + "B": 100 + }, + "BackgroundType": 0, + "LineNumberColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 0 + }, + "LineNumberBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "LineHighlighterBackground": { + "A": 50, + "R": 100, + "G": 100, + "B": 100 + }, + "TextBoxBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "CursorColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 0 + }, + "SearchHighlightColor": { + "A": 150, + "R": 255, + "G": 150, + "B": 0 + }, + "TextboxBackgroundType": 2, + "SelectedTabPageHeaderTextColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 0 + }, + "UnSelectedTabPageHeaderTextColor": { + "A": 255, + "R": 50, + "G": 50, + "B": 50 + }, + "UnselectedTabPageHeaderBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "SelectedTabPageHeaderBackground": { + "A": 100, + "R": 255, + "G": 255, + "B": 255 + }, + "StatusbarTextColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 255 + }, + "StatusbarBackgroundColor": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "DialogBackgroundColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 255 + }, + "DialogTextColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 0 + }, + "DialogBackgroundType": 0 +} \ No newline at end of file diff --git a/Fastedit/Designs/Design3.json b/Fastedit/Designs/Design3.json new file mode 100644 index 0000000..0c76343 --- /dev/null +++ b/Fastedit/Designs/Design3.json @@ -0,0 +1,109 @@ +{ + "Theme": 1, + "BackgroundType": 2, + "BackgroundColor": { + "A": 100, + "R": 255, + "G": 255, + "B": 255 + }, + "TextColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 0 + }, + "SelectionColor": { + "A": 100, + "R": 100, + "G": 100, + "B": 150 + }, + + "LineNumberColor": { + "A": 100, + "R": 150, + "G": 150, + "B": 150 + }, + "LineNumberBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "LineHighlighterBackground": { + "A": 50, + "R": 180, + "G": 180, + "B": 180 + }, + "TextboxBackgroundType": 2, + "TextBoxBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "CursorColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 0 + }, + "SearchHighlightColor": { + "A": 150, + "R": 255, + "G": 150, + "B": 0 + }, + "SelectedTabPageHeaderTextColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 0 + }, + "UnSelectedTabPageHeaderTextColor": { + "A": 150, + "R": 0, + "G": 0, + "B": 0 + }, + "UnselectedTabPageHeaderBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "SelectedTabPageHeaderBackground": { + "A": 20, + "R": 50, + "G": 50, + "B": 50 + }, + "StatusbarTextColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 0 + }, + "StatusbarBackgroundColor": { + "A": 255, + "R": 245, + "G": 245, + "B": 245 + }, + "DialogBackgroundColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 255 + }, + "DialogTextColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 0 + }, + "DialogBackgroundType": 0 +} \ No newline at end of file diff --git a/Fastedit/Designs/Design4.json b/Fastedit/Designs/Design4.json new file mode 100644 index 0000000..3c6a70e --- /dev/null +++ b/Fastedit/Designs/Design4.json @@ -0,0 +1,109 @@ +{ + "Theme": 2, + "BackgroundType": 0, + "BackgroundColor": { + "A": 155, + "R": 40, + "G": 40, + "B": 40 + }, + "TextColor": { + "A": 225, + "R": 255, + "G": 255, + "B": 255 + }, + "SelectionColor": { + "A": 100, + "R": 200, + "G": 200, + "B": 200 + }, + "LineNumberColor": { + "A": 100, + "R": 255, + "G": 255, + "B": 255 + }, + "LineNumberBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "LineHighlighterBackground": { + "A": 50, + "R": 100, + "G": 100, + "B": 100 + }, + "TextboxBackgroundType": 2, + "TextBoxBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "CursorColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 255 + }, + "SearchHighlightColor": { + "A": 150, + "R": 255, + "G": 150, + "B": 0 + }, + "SelectedTabPageHeaderTextColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 255 + }, + "UnSelectedTabPageHeaderTextColor": { + "A": 150, + "R": 255, + "G": 255, + "B": 255 + }, + "UnselectedTabPageHeaderBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "SelectedTabPageHeaderBackground": { + "A": 110, + "R": 15, + "G": 15, + "B": 15 + }, + "StatusbarTextColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 255 + }, + "StatusbarBackgroundType": 2, + "StatusbarBackgroundColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 0 + }, + "DialogBackgroundColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 0 + }, + "DialogTextColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 255 + }, + "DialogBackgroundType": 0 +} \ No newline at end of file diff --git a/Fastedit/Designs/Design5.json b/Fastedit/Designs/Design5.json new file mode 100644 index 0000000..892fee9 --- /dev/null +++ b/Fastedit/Designs/Design5.json @@ -0,0 +1,99 @@ +{ + "Theme": 2, + "BackgroundType": 2, + "BackgroundColor": null, + "TextColor": { + "A": 255, + "R": 255, + "G": 0, + "B": 0 + }, + "SelectionColor": { + "A": 100, + "R": 200, + "G": 0, + "B": 0 + }, + "LineNumberColor": { + "A": 200, + "R": 255, + "G": 0, + "B": 0 + }, + "LineNumberBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "LineHighlighterBackground": { + "A": 50, + "R": 100, + "G": 100, + "B": 100 + }, + "TextboxBackgroundType": 2, + "TextBoxBackground": null, + "CursorColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 255 + }, + "SearchHighlightColor": { + "A": 150, + "R": 255, + "G": 150, + "B": 0 + }, + "SelectedTabPageHeaderTextColor": { + "A": 255, + "R": 255, + "G": 0, + "B": 0 + }, + "UnSelectedTabPageHeaderTextColor": { + "A": 230, + "R": 255, + "G": 0, + "B": 0 + }, + "UnselectedTabPageHeaderBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "SelectedTabPageHeaderBackground": { + "A": 150, + "R": 15, + "G": 15, + "B": 15 + }, + "StatusbarTextColor": { + "A": 255, + "R": 255, + "G": 0, + "B": 0 + }, + "StatusbarBackgroundType": 1, + "StatusbarBackgroundColor": { + "A": 20, + "R": 20, + "G": 20, + "B": 20 + }, + "DialogBackgroundColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 0 + }, + "DialogTextColor": { + "A": 255, + "R": 255, + "G": 0, + "B": 0 + }, + "DialogBackgroundType": 0 +} \ No newline at end of file diff --git a/Fastedit/Designs/Design6.json b/Fastedit/Designs/Design6.json new file mode 100644 index 0000000..7695a2a --- /dev/null +++ b/Fastedit/Designs/Design6.json @@ -0,0 +1,99 @@ +{ + "Theme": 2, + "BackgroundType": 2, + "BackgroundColor": null, + "TextColor": { + "A": 255, + "R": 0, + "G": 255, + "B": 0 + }, + "SelectionColor": { + "A": 100, + "R": 0, + "G": 200, + "B": 0 + }, + "LineNumberColor": { + "A": 200, + "R": 0, + "G": 255, + "B": 0 + }, + "LineNumberBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "LineHighlighterBackground": { + "A": 50, + "R": 100, + "G": 100, + "B": 100 + }, + "TextboxBackgroundType": 2, + "TextBoxBackground": null, + "CursorColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 255 + }, + "SearchHighlightColor": { + "A": 150, + "R": 255, + "G": 150, + "B": 0 + }, + "SelectedTabPageHeaderTextColor": { + "A": 255, + "R": 0, + "G": 255, + "B": 0 + }, + "UnSelectedTabPageHeaderTextColor": { + "A": 230, + "R": 0, + "G": 255, + "B": 0 + }, + "UnselectedTabPageHeaderBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "SelectedTabPageHeaderBackground": { + "A": 150, + "R": 15, + "G": 15, + "B": 15 + }, + "StatusbarTextColor": { + "A": 255, + "R": 0, + "G": 255, + "B": 0 + }, + "StatusbarBackgroundType": 1, + "StatusbarBackgroundColor": { + "A": 20, + "R": 20, + "G": 20, + "B": 20 + }, + "DialogBackgroundColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 0 + }, + "DialogTextColor": { + "A": 255, + "R": 0, + "G": 255, + "B": 0 + }, + "DialogBackgroundType": 0 +} \ No newline at end of file diff --git a/Fastedit/Designs/Design7.json b/Fastedit/Designs/Design7.json new file mode 100644 index 0000000..7954485 --- /dev/null +++ b/Fastedit/Designs/Design7.json @@ -0,0 +1,99 @@ +{ + "Theme": 2, + "BackgroundType": 2, + "BackgroundColor": null, + "TextColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 255 + }, + "SelectionColor": { + "A": 100, + "R": 0, + "G": 0, + "B": 200 + }, + "LineNumberColor": { + "A": 200, + "R": 0, + "G": 0, + "B": 255 + }, + "LineNumberBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "LineHighlighterBackground": { + "A": 50, + "R": 100, + "G": 100, + "B": 100 + }, + "TextboxBackgroundType": 2, + "TextBoxBackground": null, + "CursorColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 255 + }, + "SearchHighlightColor": { + "A": 150, + "R": 255, + "G": 150, + "B": 0 + }, + "SelectedTabPageHeaderTextColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 255 + }, + "UnSelectedTabPageHeaderTextColor": { + "A": 230, + "R": 0, + "G": 0, + "B": 255 + }, + "UnselectedTabPageHeaderBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "SelectedTabPageHeaderBackground": { + "A": 150, + "R": 15, + "G": 15, + "B": 15 + }, + "StatusbarTextColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 255 + }, + "StatusbarBackgroundType": 1, + "StatusbarBackgroundColor": { + "A": 20, + "R": 20, + "G": 20, + "B": 20 + }, + "DialogBackgroundColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 0 + }, + "DialogTextColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 255 + }, + "DialogBackgroundType": 0 +} \ No newline at end of file diff --git a/Fastedit/Designs/Design8.json b/Fastedit/Designs/Design8.json new file mode 100644 index 0000000..15e1bf7 --- /dev/null +++ b/Fastedit/Designs/Design8.json @@ -0,0 +1,99 @@ +{ + "Theme": 2, + "BackgroundType": 2, + "BackgroundColor": null, + "TextColor": { + "A": 255, + "R": 255, + "G": 0, + "B": 255 + }, + "SelectionColor": { + "A": 100, + "R": 200, + "G": 0, + "B": 200 + }, + "LineNumberColor": { + "A": 200, + "R": 255, + "G": 0, + "B": 255 + }, + "LineNumberBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "LineHighlighterBackground": { + "A": 50, + "R": 100, + "G": 100, + "B": 100 + }, + "TextboxBackgroundType": 2, + "TextBoxBackground": null, + "CursorColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 255 + }, + "SearchHighlightColor": { + "A": 150, + "R": 255, + "G": 150, + "B": 0 + }, + "SelectedTabPageHeaderTextColor": { + "A": 255, + "R": 255, + "G": 0, + "B": 255 + }, + "UnSelectedTabPageHeaderTextColor": { + "A": 230, + "R": 255, + "G": 0, + "B": 255 + }, + "UnselectedTabPageHeaderBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "SelectedTabPageHeaderBackground": { + "A": 150, + "R": 15, + "G": 15, + "B": 15 + }, + "StatusbarTextColor": { + "A": 255, + "R": 255, + "G": 0, + "B": 255 + }, + "StatusbarBackgroundType": 1, + "StatusbarBackgroundColor": { + "A": 20, + "R": 20, + "G": 20, + "B": 20 + }, + "DialogBackgroundColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 0 + }, + "DialogTextColor": { + "A": 255, + "R": 255, + "G": 0, + "B": 255 + }, + "DialogBackgroundType": 0 +} \ No newline at end of file diff --git a/Fastedit/Designs/Design9.json b/Fastedit/Designs/Design9.json new file mode 100644 index 0000000..e7b06eb --- /dev/null +++ b/Fastedit/Designs/Design9.json @@ -0,0 +1,99 @@ +{ + "Theme": 2, + "BackgroundType": 2, + "BackgroundColor": null, + "TextColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 0 + }, + "SelectionColor": { + "A": 100, + "R": 200, + "G": 200, + "B": 0 + }, + "LineNumberColor": { + "A": 200, + "R": 255, + "G": 255, + "B": 0 + }, + "LineNumberBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "LineHighlighterBackground": { + "A": 50, + "R": 100, + "G": 100, + "B": 100 + }, + "TextboxBackgroundType": 2, + "TextBoxBackground": null, + "CursorColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 255 + }, + "SearchHighlightColor": { + "A": 150, + "R": 255, + "G": 150, + "B": 0 + }, + "SelectedTabPageHeaderTextColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 0 + }, + "UnSelectedTabPageHeaderTextColor": { + "A": 230, + "R": 255, + "G": 255, + "B": 0 + }, + "UnselectedTabPageHeaderBackground": { + "A": 0, + "R": 0, + "G": 0, + "B": 0 + }, + "SelectedTabPageHeaderBackground": { + "A": 150, + "R": 15, + "G": 15, + "B": 15 + }, + "StatusbarTextColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 0 + }, + "StatusbarBackgroundType": 1, + "StatusbarBackgroundColor": { + "A": 20, + "R": 20, + "G": 20, + "B": 20 + }, + "DialogBackgroundColor": { + "A": 255, + "R": 0, + "G": 0, + "B": 0 + }, + "DialogTextColor": { + "A": 255, + "R": 255, + "G": 255, + "B": 0 + }, + "DialogBackgroundType": 0 +} \ No newline at end of file diff --git a/Fastedit/Dialogs/AskSaveDialog.cs b/Fastedit/Dialogs/AskSaveDialog.cs new file mode 100644 index 0000000..133c572 --- /dev/null +++ b/Fastedit/Dialogs/AskSaveDialog.cs @@ -0,0 +1,34 @@ +using Fastedit.Storage; +using Fastedit.Tab; +using System; +using System.Threading.Tasks; +using Windows.UI.Xaml.Controls; + +namespace Fastedit.Dialogs +{ + public class AskSaveDialog + { + public static async Task Show(TabPageItem tab) + { + var SaveDialog = new ContentDialog + { + Background = DialogHelper.ContentDialogBackground(), + Foreground = DialogHelper.ContentDialogForeground(), + RequestedTheme = DialogHelper.DialogDesign, + Title = "Save file?", + Content = "Would you like to save the file " + tab.DatabaseItem.FileName + "?", + PrimaryButtonText = "Save", + SecondaryButtonText = "Don't save", + CloseButtonText = "Cancel", + DefaultButton = ContentDialogButton.Primary, + }; + var res = await SaveDialog.ShowAsync(); + if (res == ContentDialogResult.Primary) + return await SaveFileHelper.Save(tab); + else if (res == ContentDialogResult.Secondary) + return true; + else + return false; + } + } +} diff --git a/Fastedit/Dialogs/DialogHelper.cs b/Fastedit/Dialogs/DialogHelper.cs new file mode 100644 index 0000000..47b8171 --- /dev/null +++ b/Fastedit/Dialogs/DialogHelper.cs @@ -0,0 +1,19 @@ +using Fastedit.Helper; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Media; + +namespace Fastedit.Dialogs +{ + public class DialogHelper + { + public static ElementTheme DialogDesign => ThemeHelper.CurrentTheme; + public static Brush ContentDialogBackground() + { + return DesignHelper.CreateBackgroundBrush(ConvertHelper.ToColor(DesignHelper.CurrentDesign.DialogBackgroundColor), DesignHelper.CurrentDesign.DialogBackgroundType); + } + public static SolidColorBrush ContentDialogForeground() + { + return new SolidColorBrush(ConvertHelper.ToColor(DesignHelper.CurrentDesign.DialogTextColor)); + } + } +} diff --git a/Fastedit/Dialogs/EncodingDialog.cs b/Fastedit/Dialogs/EncodingDialog.cs index e8497d5..b1f3af5 100644 --- a/Fastedit/Dialogs/EncodingDialog.cs +++ b/Fastedit/Dialogs/EncodingDialog.cs @@ -1,76 +1,56 @@ -using Fastedit.Controls.Textbox; -using Fastedit.Core; -using Fastedit.Extensions; +using Fastedit.Helper; +using Fastedit.Storage; +using Fastedit.Tab; using System; -using System.Linq; -using System.Text; using System.Threading.Tasks; -using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; -using mucx = Microsoft.UI.Xaml.Controls; namespace Fastedit.Dialogs { public class EncodingDialog { - ContentDialog dialog = null; - Encoding selectedEncoding = null; + private static ComboBox encodingCombobox; - private int GetIndexOfSelected(ComboBox cb, Encoding enc) + public static async Task Show(TabPageItem tab) { - var name = Encodings.EncodingToString(enc); - var lst = cb.Items.ToList(); - return lst.IndexOf(lst.Find(item => ((ComboBoxItem)item).Content.ToString() == name)); - } + if (tab == null) + return; - public EncodingDialog(mucx.TabViewItem TabPage) - { - if (TabPage.Content is TextControlBox textbox) + //create the combobox: + if (encodingCombobox == null) { - var encodingcombobox = new ComboBox + encodingCombobox = new ComboBox { - Width = 150, + Header = "Encoding:", + HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center, + VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center }; + encodingCombobox.ItemsSource = EncodingHelper.AllEncodingNames; + } - for(int i = 0; i 0 ? "Reopen" : "", //only when tab is a local file + CloseButtonText = "Cancel", + DefaultButton = ContentDialogButton.Primary, + }; + var res = await dialog.ShowAsync(); + dialog.Content = null; + + if (res == ContentDialogResult.Primary) + tab.Encoding = EncodingHelper.GetEncodingByIndex(encodingCombobox.SelectedIndex); + else if (res == ContentDialogResult.Secondary) + { + //reopen the file with the encoding specified + await OpenFileHelper.ReopenWithEncoding(tab, EncodingHelper.GetEncodingByIndex(encodingCombobox.SelectedIndex)); } } - public async Task ShowDialog() - { - await dialog.ShowAsync(); - } } } diff --git a/Fastedit/Dialogs/ErrorDialogs.cs b/Fastedit/Dialogs/ErrorDialogs.cs deleted file mode 100644 index 815009f..0000000 --- a/Fastedit/Dialogs/ErrorDialogs.cs +++ /dev/null @@ -1,83 +0,0 @@ -using System; -using Windows.UI.Xaml; -using muxc = Microsoft.UI.Xaml.Controls; - -namespace Fastedit.Dialogs -{ - public class ErrorDialogs - { - public static muxc.InfoBar CreateInfobar(string Content = "", string Title = "", muxc.InfoBarSeverity severity = muxc.InfoBarSeverity.Warning, int VisibilityTime = 5, object content = null) - { - return new muxc.InfoBar - { - Severity = severity, - Title = Title, - Message = Content, - IsOpen = true, - Content = content, - Margin = new Thickness(0, 0, 0, 5) - }; - - } - - public static muxc.InfoBar FileNoAccessExceptionErrorDialog(Exception e, string FilePath = "") - { - return CreateInfobar("No access to the file\n" + e.Message + "\nFile: " + FilePath, "", muxc.InfoBarSeverity.Error); - } - - public static muxc.InfoBar FileNotFoundExceptionErrorDialog(Exception e, string FilePath = "") - { - return CreateInfobar("The file could not be found\n" + e.Message + "\nFile: " + FilePath, "", muxc.InfoBarSeverity.Error); - } - - public static muxc.InfoBar LoadSettingsError(Exception e) - { - return CreateInfobar("Couldn't load app-settings!\n" + e.Message,"", muxc.InfoBarSeverity.Error); - } - - public static muxc.InfoBar SaveErrorDialog() - { - return CreateInfobar(AppSettings.GetResourceStringStatic("ErrorDialogs_SaveErrorDialog/Text"),"", muxc.InfoBarSeverity.Error); - } - - public static muxc.InfoBar SaveFileError(string DataBaseName) - { - return CreateInfobar(AppSettings.GetResourceStringStatic("ErrorDialogs_SaveFileError/Text") + DataBaseName, "", muxc.InfoBarSeverity.Error); - } - - public static muxc.InfoBar OpenErrorDialog(string filepath = "") - { - return CreateInfobar(AppSettings.GetResourceStringStatic("ErrorDialogs_OpenErrorDialog/Text") + "\nFile: " + - filepath, "", muxc.InfoBarSeverity.Error); - } - - public static muxc.InfoBar CreateTabErrorDialog() - { - return CreateInfobar(AppSettings.GetResourceStringStatic("ErrorDialogs_CreateTabErrorDialog/Text"),"", muxc.InfoBarSeverity.Error); - } - - public static muxc.InfoBar GetTabErrorDialog() - { - return CreateInfobar(AppSettings.GetResourceStringStatic("ErrorDialogs_GetTabError/Text"),"", muxc.InfoBarSeverity.Error); - } - - public static muxc.InfoBar CloseTabError() - { - return CreateInfobar(AppSettings.GetResourceStringStatic("ErrorDialogs_CloseTabError/Text"), "", muxc.InfoBarSeverity.Error); - } - - public static muxc.InfoBar LoadTabsError() - { - return CreateInfobar(AppSettings.GetResourceStringStatic("ErrorDialogs_LoadTabsError/Text"),"", muxc.InfoBarSeverity.Error); - } - - public static muxc.InfoBar LoadTempTabError() - { - return CreateInfobar(AppSettings.GetResourceStringStatic("ErrorDialogs.LoadTempTabError/Text"), "", muxc.InfoBarSeverity.Error); - } - public static muxc.InfoBar LoadDesignError() - { - return CreateInfobar("Could not load the design", "", muxc.InfoBarSeverity.Error); - } - } -} diff --git a/Fastedit/Dialogs/FileInfoDialog.cs b/Fastedit/Dialogs/FileInfoDialog.cs new file mode 100644 index 0000000..8b88668 --- /dev/null +++ b/Fastedit/Dialogs/FileInfoDialog.cs @@ -0,0 +1,70 @@ +using Fastedit.Helper; +using Fastedit.Storage; +using Fastedit.Tab; +using System; +using System.IO; +using System.Text; +using System.Threading.Tasks; +using Windows.Storage.AccessCache; +using Windows.Storage.FileProperties; +using Windows.UI.Xaml.Controls; + +namespace Fastedit.Dialogs +{ + public class FileInfoDialog + { + public static async Task Show(TabPageItem tab) + { + if (tab == null) + return; + + StringBuilder content = new StringBuilder(); + + //File extension + string fileExtension = Path.GetExtension(tab.DatabaseItem.FilePath.Length > 0 ? tab.DatabaseItem.FilePath : tab.DatabaseItem.FileName); + var ectension = FileExtensions.FindByExtension(fileExtension); + if (ectension != null) + content.AppendLine("Extension: " + fileExtension + " (" + ectension.ExtensionName + ")"); ; + + //only if the tab is based on a file + if (tab.DatabaseItem.FileToken.Length > 0) + { + try + { + var file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(tab.DatabaseItem.FileToken); + + BasicProperties fileProperties = await file.GetBasicPropertiesAsync(); + //calculate the filesize and extension + + content.AppendLine("Path: " + tab.DatabaseItem.FilePath); + content.AppendLine("Created: " + file.DateCreated); + content.AppendLine("Last modified: " + fileProperties.DateModified); + content.AppendLine("Size: " + SizeCalculationHelper.SplitSize(fileProperties.Size)); + + } + catch (FileNotFoundException) { } + } + + if (tab.textbox.CodeLanguage != null) + content.AppendLine("Code language: " + tab.textbox.CodeLanguage.Name); + + content.AppendLine("Words: " + tab.CountWords()); + content.AppendLine("Lines: " + tab.textbox.NumberOfLines); + content.AppendLine("Characters: " + tab.textbox.CharacterCount); + + string FileName = tab.DatabaseItem.FileToken.Length == 0 ? tab.DatabaseItem.FileName : Path.GetFileName(tab.DatabaseItem.FilePath); + + var dialog = new ContentDialog + { + Background = DialogHelper.ContentDialogBackground(), + Foreground = DialogHelper.ContentDialogForeground(), + RequestedTheme = DialogHelper.DialogDesign, + Title = "Info " + FileName, + Content = content.ToString(), + CloseButtonText = "Ok", + DefaultButton = ContentDialogButton.Close, + }; + await dialog.ShowAsync(); + } + } +} diff --git a/Fastedit/Dialogs/FileInfoDialog.xaml b/Fastedit/Dialogs/FileInfoDialog.xaml deleted file mode 100644 index 17e1f4e..0000000 --- a/Fastedit/Dialogs/FileInfoDialog.xaml +++ /dev/null @@ -1,10 +0,0 @@ - - - \ No newline at end of file diff --git a/Fastedit/Dialogs/FileInfoDialog.xaml.cs b/Fastedit/Dialogs/FileInfoDialog.xaml.cs deleted file mode 100644 index 84abe3b..0000000 --- a/Fastedit/Dialogs/FileInfoDialog.xaml.cs +++ /dev/null @@ -1,112 +0,0 @@ -using Fastedit.Controls.Textbox; -using Fastedit.Core; -using Fastedit.Extensions; -using System; -using System.IO; -using System.Threading.Tasks; -using Windows.ApplicationModel.Resources; -using Windows.Storage; -using Windows.Storage.FileProperties; -using Windows.UI.Xaml.Controls; -using muxc = Microsoft.UI.Xaml.Controls; - -namespace Fastedit.Dialogs -{ - public sealed partial class FileInfoDialog : ContentDialog - { - ResourceLoader Resloader = ResourceLoader.GetForCurrentView(); - - private async Task Createcontent(muxc.TabViewItem Tab) - { - if (Tab.Content is TextControlBox textbox) - { - if (textbox != null) - { - var Resloader = ResourceLoader.GetForCurrentView(); - AppSettings appsettings = new AppSettings(); - StorageFile file = textbox.Storagefile; - string tabheader = textbox.Header; - string tabtext = textbox.GetText(); - string FilePath = textbox.FilePath; - string FileExtension = Path.GetExtension(textbox.Header); - string DataCreatedTime = string.Empty; - string NoDataToDisplay = string.Empty; - string FileSize = string.Empty; - string LastModified = string.Empty; - int NbrOfWords = textbox.CountWords(tabtext); - FileExtensions fe = new FileExtensions(); - for (int i = 0; i < fe.FileExtentionList.Count; i++) - { - if (fe.FileExtentionList[i].Extension.Contains(FileExtension)) - { - FileExtension += " (" + fe.FileExtentionList[i].ExtensionName + ")"; - break; - } - } - if (file != null) - { - BasicProperties basicProperties = await file.GetBasicPropertiesAsync(); - - FilePath = textbox.TabSaveMode == TabSaveMode.SaveAsTemp ? NoDataToDisplay : file.Path; - DataCreatedTime = file.DateCreated.ToString(); - LastModified = basicProperties.DateModified.ToString(); - FileSize = basicProperties.Size.ToString() + "B"; - if (basicProperties.Size > 1000.0) - { - FileSize = (basicProperties.Size / 1000.0).ToString() + "KB"; - } - else if (basicProperties.Size == 0) - { - FileSize = NoDataToDisplay; - } - } - - string DialogContent = Resloader.GetString("FileInfo_Filename/Text") + " " + tabheader + "\n" + - Resloader.GetString("FileInfo_Filepath/Text") + " " + FilePath + "\n" + - Resloader.GetString("FileInfo_Extension/Text") + " " + FileExtension + "\n" + - Resloader.GetString("FileInfo_Created/Text") + " " + DataCreatedTime + "\n"; - if (LastModified != NoDataToDisplay) - { - DialogContent += Resloader.GetString("FileInfo_LastModified/Text") + " " + DataCreatedTime + "\n"; - } - - if (FileSize != NoDataToDisplay) - { - DialogContent += Resloader.GetString("FileInfo_FileSize/Text") + " " + FileSize + "\n"; - } - - DialogContent += Resloader.GetString("FileInfo_WordCount/Text") + " " + NbrOfWords + "\n" + - Resloader.GetString("FileInfo_CharacterCount/Text") + " " + tabtext.Length + "\n"; - - DialogContent += Resloader.GetString("FileInfo_Lines/Text") + " " + textbox.GetLinesCount + "\n"; - - return DialogContent; - } - return ""; - } - return ""; - } - private async void InitDialog(muxc.TabViewItem Tab, TextControlBox textbox) - { - this.Background = DefaultValues.ContentDialogBackgroundColor(); - CornerRadius = DefaultValues.DefaultDialogCornerRadius; - RequestedTheme = DefaultValues.ContentDialogTheme(); - Foreground = DefaultValues.ContentDialogForegroundColor(); - Title = Resloader.GetString("FileInfo_FileInfo/Text") + " " + textbox.Header; - CloseButtonText = Resloader.GetString("FileInfo_OkButton/Text"); - DataDisplayTextbox.Text = await Createcontent(Tab); - } - public FileInfoDialog(muxc.TabViewItem Tab) - { - this.InitializeComponent(); - if (Tab.Content is TextControlBox textbox) - { - InitDialog(Tab, textbox); - } - else - { - this.Hide(); - } - } - } -} diff --git a/Fastedit/Dialogs/GoToLineDialog.cs b/Fastedit/Dialogs/GoToLineDialog.cs new file mode 100644 index 0000000..d9c72f9 --- /dev/null +++ b/Fastedit/Dialogs/GoToLineDialog.cs @@ -0,0 +1,48 @@ +using Fastedit.Helper; +using Fastedit.Tab; +using Microsoft.UI.Xaml.Controls; +using System; +using System.Threading.Tasks; +using Windows.UI.Xaml.Controls; + +namespace Fastedit.Dialogs +{ + internal class GoToLineDialog + { + public static async Task Show(TabPageItem tab) + { + if (tab == null) + return false; + + var input = new NumberBox + { + SpinButtonPlacementMode = NumberBoxSpinButtonPlacementMode.Inline, + VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Stretch, + Maximum = tab.textbox.NumberOfLines, + Minimum = 0, + LargeChange = 50, + SmallChange = 1, + }; + var dialog = new ContentDialog + { + Background = DialogHelper.ContentDialogBackground(), + Foreground = DialogHelper.ContentDialogForeground(), + RequestedTheme = DialogHelper.DialogDesign, + Title = "Go to line", + Content = input, + PrimaryButtonText = "Ok", + CloseButtonText = "Cancel", + DefaultButton = ContentDialogButton.Primary, + }; + var res = await dialog.ShowAsync(); + + if (res == ContentDialogResult.Primary) + { + EditActions.GoToLine(tab, ConvertHelper.ToInt(input.Value - 1, 0)); + return true; + } + return false; + } + + } +} diff --git a/Fastedit/Dialogs/InfoBarMessages.cs b/Fastedit/Dialogs/InfoBarMessages.cs deleted file mode 100644 index 9b95ba8..0000000 --- a/Fastedit/Dialogs/InfoBarMessages.cs +++ /dev/null @@ -1,25 +0,0 @@ -namespace Fastedit.Dialogs -{ - public static class InfoBarMessages - { - public static string FileNotFound = AppSettings.GetResourceStringStatic("InfoBarMessage_FileNotFound/Text"); - public static string FileNotFoundTitle = AppSettings.GetResourceStringStatic("InfoBarMessage_FileNotFound_Title/Text"); - - public static string FileNoAccess = AppSettings.GetResourceStringStatic("InfoBarMessage_FileNoAccess/Text"); - public static string FileNoAccessTitle = AppSettings.GetResourceStringStatic("InfoBarMessage_FileNoAccess_Title/Text"); - - public static string FileInvalidPath = AppSettings.GetResourceStringStatic("InfoBarMessage_FileInvalidPath/Text"); - public static string FileInvalidPathTitle = AppSettings.GetResourceStringStatic("InfoBarMessage_FileInvalidPath_Title/Text"); - - public static string CouldNotOpenInNewView = AppSettings.GetResourceStringStatic("InfoBarMessage_NotOpenInNewView/Text"); - public static string CouldNotOpenInNewViewTitle = AppSettings.GetResourceStringStatic("InfoBarMessage_NotOpenInNewView_Title/Text"); - - public static string CloseAllInstances = AppSettings.GetResourceStringStatic("InfoBarMesssage_CloseAllInstances/Text"); - public static string CloseAllInstances_Title = AppSettings.GetResourceStringStatic("InfoBarMesssage_CloseAllInstances_Title/Text"); - - public static string SearchNotFound = AppSettings.GetResourceStringStatic("InfoBarMessage_SearchNotFound/Text"); - - public static string LoadingFile = AppSettings.GetResourceStringStatic("InfoBarMessage_LoadingFile/Text"); - public static string UpdatingEncoding = AppSettings.GetResourceStringStatic("InfoBarMessage_UpdatingEncoding/Text"); - } -} diff --git a/Fastedit/Dialogs/InfoBox.cs b/Fastedit/Dialogs/InfoBox.cs deleted file mode 100644 index 972ddae..0000000 --- a/Fastedit/Dialogs/InfoBox.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Fastedit.Core; -using Windows.UI.Xaml.Controls; - -namespace Fastedit.Dialogs -{ - public class InfoBox : ContentDialog - { - //private ContentDialog dialog = null; - public InfoBox(string content, string Title = "") - { - this.Title = Title; - Background = DefaultValues.ContentDialogBackgroundColor(); - CornerRadius = DefaultValues.DefaultDialogCornerRadius; - PrimaryButtonText = "Ok"; - Foreground = DefaultValues.ContentDialogForegroundColor(); - RequestedTheme = DefaultValues.ContentDialogTheme(); - - Content = new TextBlock - { - Text = content, - TextWrapping = Windows.UI.Xaml.TextWrapping.Wrap - }; - } - } -} diff --git a/Fastedit/Dialogs/InfoMessages.cs b/Fastedit/Dialogs/InfoMessages.cs new file mode 100644 index 0000000..1f4c347 --- /dev/null +++ b/Fastedit/Dialogs/InfoMessages.cs @@ -0,0 +1,45 @@ +using Fastedit.Controls; +using Fastedit.Tab; +using System; +using Windows.UI.Xaml.Controls; + +namespace Fastedit.Dialogs +{ + public class InfoMessages + { + public static StackPanel InfoMessagePanel = null; + + public static void Add(InfobarMessage message) + { + InfoMessagePanel.Children.Add(message); + } + public static void NoAccesToSaveFile() => Add(new InfobarMessage("No access", "No access to write to file", Microsoft.UI.Xaml.Controls.InfoBarSeverity.Error)); + public static void NoAccesToReadFile() => Add(new InfobarMessage("No access", "No access to read from file", Microsoft.UI.Xaml.Controls.InfoBarSeverity.Error)); + public static void UnhandledException(string message) => Add(new InfobarMessage("Exception", "Unhandled exception: \n" + message, Microsoft.UI.Xaml.Controls.InfoBarSeverity.Error)); + public static void ClearRecyclebinError() => Add(new InfobarMessage("Clear recyclebin", "Error occured while clearing the recycle bin", Microsoft.UI.Xaml.Controls.InfoBarSeverity.Error)); + public static void DeleteFromRecyclebinError() => Add(new InfobarMessage("Delete from recyclebin", "Error occured while deleting the file from recycle bin", Microsoft.UI.Xaml.Controls.InfoBarSeverity.Error)); + public static void RecyclebinClearSucceed() => Add(new InfobarMessage("Clear recyclebin", "Successfully cleared recycle bin", Microsoft.UI.Xaml.Controls.InfoBarSeverity.Success)); + public static void MoveToRecyclebinError() => Add(new InfobarMessage("Move to recyclebin", "Error occured while moving the file to recyclebin", Microsoft.UI.Xaml.Controls.InfoBarSeverity.Error)); + public static void OpenFromRecyclebinError() => Add(new InfobarMessage("Open from recyclebin", "Error occured while opening the file from the recyclebin", Microsoft.UI.Xaml.Controls.InfoBarSeverity.Error)); + public static void FileNameInvalidCharacters() => Add(new InfobarMessage("Invalid character", "The text entered contains invalid characters for a file name", Microsoft.UI.Xaml.Controls.InfoBarSeverity.Error)); + public static void DesignLoadError(string designName, Exception ex) => Add(new InfobarMessage("Design load failed", "Could not load the design " + designName + "\n" + ex.Message, Microsoft.UI.Xaml.Controls.InfoBarSeverity.Error)); + public static void DetectEncodingError(Exception ex) => Add(new InfobarMessage("Detect encoding", "Could not detect the encoding\n" + ex.Message, Microsoft.UI.Xaml.Controls.InfoBarSeverity.Error)); + public static void SettingsExportSucceed() => Add(new InfobarMessage("Settings export", "Settings successfully exported", Microsoft.UI.Xaml.Controls.InfoBarSeverity.Success)); + public static void SettingsImportSucceed() => Add(new InfobarMessage("Settings import", "Settings successfully imported", Microsoft.UI.Xaml.Controls.InfoBarSeverity.Success)); + public static void SettingsExportFailed() => Add(new InfobarMessage("Settings export", "Failed while exporting settings", Microsoft.UI.Xaml.Controls.InfoBarSeverity.Error)); + public static void SettingsImportFailed() => Add(new InfobarMessage("Settings import", "Faild while importing settings", Microsoft.UI.Xaml.Controls.InfoBarSeverity.Error)); + public static void ClearTemporaryFilesFailed() => Add(new InfobarMessage("Temporary files", "Failed while clearing temporary files", Microsoft.UI.Xaml.Controls.InfoBarSeverity.Error)); + public static void ClearTemporaryFilesSucceed() => Add(new InfobarMessage("Temporary files", "Successfully cleared temporary files", Microsoft.UI.Xaml.Controls.InfoBarSeverity.Success)); + + public static void WelcomeMessage() + { + var btn = new Button { Content = "Designs", Margin = new Windows.UI.Xaml.Thickness(0, 0, 0, 10) }; + btn.Click += delegate + { + TabPageHelper.mainPage.ShowSettings("DesignPage"); + }; + Add(new InfobarMessage("Welcome to Fastedit", "To customize your experience,\npress the button below", btn, Microsoft.UI.Xaml.Controls.InfoBarSeverity.Success, 8)); + } + + } +} diff --git a/Fastedit/Dialogs/ProgressWindowItem.cs b/Fastedit/Dialogs/ProgressWindowItem.cs new file mode 100644 index 0000000..7fbe272 --- /dev/null +++ b/Fastedit/Dialogs/ProgressWindowItem.cs @@ -0,0 +1,31 @@ +using Windows.UI.Xaml.Controls; + +namespace Fastedit.Dialogs +{ + public class ProgressWindowItem + { + public ProgressWindowItem(Microsoft.UI.Xaml.Controls.ProgressRing progressRing, TextBlock progressDisplay) + { + ProgressRing = progressRing; + ProgressDisplay = progressDisplay; + } + + public Microsoft.UI.Xaml.Controls.ProgressRing ProgressRing { get; set; } + public TextBlock ProgressDisplay { get; set; } + + public void ShowProgress() + { + ProgressRing.IsActive = true; + ProgressRing.Visibility = ProgressDisplay.Visibility = Windows.UI.Xaml.Visibility.Visible; + } + public void HideProgress() + { + ProgressRing.IsActive = false; + ProgressRing.Visibility = ProgressDisplay.Visibility = Windows.UI.Xaml.Visibility.Collapsed; + } + public void SetText(string text) + { + ProgressDisplay.Text = text; + } + } +} diff --git a/Fastedit/Dialogs/RecycleBinDialog.cs b/Fastedit/Dialogs/RecycleBinDialog.cs new file mode 100644 index 0000000..20a4c50 --- /dev/null +++ b/Fastedit/Dialogs/RecycleBinDialog.cs @@ -0,0 +1,211 @@ +using Fastedit.Helper; +using Fastedit.Settings; +using Fastedit.Storage; +using Fastedit.Tab; +using Microsoft.UI.Xaml.Controls; +using System; +using System.Diagnostics; +using System.IO; +using System.Threading.Tasks; +using Windows.Storage; +using Windows.UI.Xaml.Controls; + +namespace Fastedit.Dialogs +{ + public class RecycleBinDialog + { + ListView listview = null; + ContentDialog dialog = null; + TabView tabView = null; + + public async Task ShowDialog() + { + if (dialog != null) + { + await dialog.ShowAsync(); + } + } + + public RecycleBinDialog(TabView tabView) + { + this.tabView = tabView; + + listview = new ListView() + { + HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Stretch, + VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Stretch, + SelectionMode = ListViewSelectionMode.Multiple + }; + dialog = new ContentDialog() + { + Background = DialogHelper.ContentDialogBackground(), + Foreground = DialogHelper.ContentDialogForeground(), + RequestedTheme = DialogHelper.DialogDesign, + Title = "Recycle bin", + CloseButtonText = "Cancel", + PrimaryButtonText = "Delete", + Content = listview, + }; + dialog.Closing += Dialog_Closing; + listview.SelectionChanged += Listview_SelectionChanged; + dialog.PrimaryButtonClick += RecyclebinWindow_PrimaryButtonClick; + dialog.SecondaryButtonClick += RecyclebinWindow_SecondaryButtonClick; + UpdateListViewItems(listview); + } + + private void Dialog_Closing(ContentDialog sender, ContentDialogClosingEventArgs args) + { + listview.Items.Clear(); + } + + //delete selected items: + private async void RecyclebinWindow_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) + { + if (listview.SelectedItems.Count == 0) + return; + + args.Cancel = true; + + try + { + while (listview.SelectedItems.Count > 0) + { + var selecteditem = listview.SelectedItems[listview.SelectedItems.Count - 1] as RecycleBinListViewItem; + await selecteditem.file.DeleteAsync(); + listview.Items.Remove(selecteditem); + } + } + catch (Exception ex) + { + InfoMessages.DeleteFromRecyclebinError(); + Debug.WriteLine("Exception in RecycleBinDialog --> RecyclebinWindow_PrimaryButtonClick:" + "\n" + ex.Message); + } + } + private async void RecyclebinWindow_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) + { + if (listview.SelectedItems.Count == 0) + return; + try + { + args.Cancel = true; + while (listview.SelectedItems.Count > 0) + { + var selecteditem = listview.SelectedItems[listview.SelectedItems.Count - 1] as RecycleBinListViewItem; + var res = await OpenFileHelper.DoOpen(tabView, selecteditem.file, true); + if (res != null) + { + await selecteditem.file.DeleteAsync(); + listview.Items.Remove(selecteditem); + } + } + } + catch + { + InfoMessages.OpenFromRecyclebinError(); + } + } + private void Listview_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + if (e.AddedItems.Count >= 1) + { + dialog.SecondaryButtonText = "Open"; + dialog.PrimaryButtonText = "Delete"; + } + else + dialog.PrimaryButtonText = dialog.SecondaryButtonText = ""; + } + + public async void UpdateListViewItems(ListView listview) + { + if (!Directory.Exists(DefaultValues.RecycleBinPath)) + Directory.CreateDirectory(DefaultValues.RecycleBinPath); + + listview.Items.Clear(); + StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(DefaultValues.RecycleBinPath); + var files = await folder.GetFilesAsync(); + for (int i = 0; i < files.Count; i++) + { + listview.Items.Add(new RecycleBinListViewItem(files[i])); + } + } + public static async Task ClearRecycleBin() + { + try + { + if (!Directory.Exists(DefaultValues.RecycleBinPath)) + Directory.CreateDirectory(DefaultValues.RecycleBinPath); + + StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(DefaultValues.RecycleBinPath); + var files = await folder.GetFilesAsync(); + for (int i = 0; i < files.Count; i++) + { + if (files[i] == null) + return ClearRecycleBinResult.NullError; + await files[i].DeleteAsync(); + } + + //check if all have been deleted + var files_2 = await folder.GetFilesAsync(); + return files_2.Count == 0 ? ClearRecycleBinResult.Success : ClearRecycleBinResult.NotAllFilesDeleted; + } + catch (Exception ex) + { + InfoMessages.ClearRecyclebinError(); + Debug.WriteLine("Exception in RecycleBinDialog -> ClearRecycleBin " + ex.Message); + return ClearRecycleBinResult.Exception; + } + } + public static async Task MoveFileToRecycleBin(TabPageItem tab) + { + try + { + if (!Directory.Exists(DefaultValues.RecycleBinPath)) + Directory.CreateDirectory(DefaultValues.RecycleBinPath); + + var folder = await StorageFolder.GetFolderFromPathAsync(DefaultValues.RecycleBinPath); + if (folder == null) + return false; + + var file = await folder.CreateFileAsync(tab.DatabaseItem.FileName, CreationCollisionOption.GenerateUniqueName); + if (file == null) + return false; + + await FileIO.WriteTextAsync(file, tab.textbox.GetText()); + + return true; + } + catch (Exception ex) + { + InfoMessages.MoveToRecyclebinError(); + Debug.WriteLine("Exception in RecycleBinDialog -> MoveFileToRecycleBin" + ex.Message); + return false; + } + } + + public static string GetSize() + { + if (!Directory.Exists(DefaultValues.RecycleBinPath)) + Directory.CreateDirectory(DefaultValues.RecycleBinPath); + + return SizeCalculationHelper.CalculateFolderSize(DefaultValues.RecycleBinPath); + } + } + + public enum ClearRecycleBinResult + { + Success, Exception, NotAllFilesDeleted, NullError + } + public class RecycleBinListViewItem : ListViewItem + { + public StorageFile file { get; set; } + + public RecycleBinListViewItem(StorageFile file) + { + this.file = file; + this.Content = new TextBlock + { + Text = file.Name + "\n" + file.DateCreated.UtcDateTime.ToString() + }; + } + } +} \ No newline at end of file diff --git a/Fastedit/Dialogs/RecyclebinWindow.cs b/Fastedit/Dialogs/RecyclebinWindow.cs deleted file mode 100644 index 07b1ab6..0000000 --- a/Fastedit/Dialogs/RecyclebinWindow.cs +++ /dev/null @@ -1,169 +0,0 @@ -using Fastedit.Core; -using Fastedit.Core.Tab; -using System; -using System.Diagnostics; -using System.Threading.Tasks; -using Windows.ApplicationModel.Contacts; -using Windows.Storage; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Markup; - -namespace Fastedit.Dialogs -{ - public class RecyclebinWindow - { - ListView listview = null; - RecycleBinListViewItem selecteditem = null; - TabActions tabactions = null; - ContentDialog dialog = null; - - public async Task ShowDialog() - { - if (dialog != null) - { - await dialog.ShowAsync(); - } - } - - public RecyclebinWindow(TabActions tabactions) - { - this.tabactions = tabactions; - - listview = new ListView() - { - HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Stretch, - VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Stretch, - }; - - dialog = new ContentDialog() - { - CornerRadius = DefaultValues.DefaultDialogCornerRadius, - Background = DefaultValues.ContentDialogBackgroundColor(), - Foreground = DefaultValues.ContentDialogForegroundColor(), - RequestedTheme = DefaultValues.ContentDialogTheme(), - Title = "Recycle bin", - CloseButtonText = "Cancel", - PrimaryButtonText = "Delete", - Content = listview, - }; - dialog.Closing += Dialog_Closing; - listview.SelectionChanged += Listview_SelectionChanged; - dialog.PrimaryButtonClick += RecyclebinWindow_PrimaryButtonClick; - dialog.SecondaryButtonClick += RecyclebinWindow_SecondaryButtonClick; - UpdateListViewItems(listview); - } - - private void Dialog_Closing(ContentDialog sender, ContentDialogClosingEventArgs args) - { - listview.Items.Clear(); - } - - private async void RecyclebinWindow_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) - { - if (selecteditem != null) - { - args.Cancel = true; - try - { - await selecteditem.file.DeleteAsync(); - listview.Items.Remove(selecteditem); - } - catch (Exception ex) - { - Debug.WriteLine("Exception in RecyclebinWindow --> RecyclebinWindow_PrimaryButtonClick:" + "\n" + ex.Message); - } - } - } - private async void RecyclebinWindow_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) - { - if (selecteditem != null) - { - args.Cancel = true; - - if (await tabactions.OpenFileFromRecylceBin(selecteditem.file, selecteditem.file.Name) == true) - { - await selecteditem.file.DeleteAsync(); - listview.Items.Remove(selecteditem); - } - } - } - private void Listview_SelectionChanged(object sender, SelectionChangedEventArgs e) - { - if (e.AddedItems.Count >= 1) - { - if (e.AddedItems[0] is RecycleBinListViewItem listboxitem) - { - selecteditem = listboxitem; - if (dialog != null) - { - dialog.SecondaryButtonText = "Open"; - dialog.PrimaryButtonText = "Delete"; - } - } - } - else - { - dialog.SecondaryButtonText = ""; - dialog.PrimaryButtonText = ""; - } - } - - public async void UpdateListViewItems(ListView listview) - { - listview.Items.Clear(); - StorageFolder folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(DefaultValues.RecycleBin_FolderName, CreationCollisionOption.OpenIfExists); - var files = await folder.GetFilesAsync(); - for (int i = 0; i< files.Count; i++) - { - listview.Items.Add(new RecycleBinListViewItem(files[i])); - } - } - public static async Task ClearRecycleBin() - { - try - { - var folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(DefaultValues.RecycleBin_FolderName, CreationCollisionOption.OpenIfExists); - if (folder == null) - return ClearRecycleBinResult.NullError; - - var files = await folder.GetFilesAsync(); - for (int i = 0; i < files.Count; i++) - { - if (files[i] == null) - return ClearRecycleBinResult.NullError; - await files[i].DeleteAsync(); - } - - //check if all have been deleted - var files_2 = await folder.GetFilesAsync(); - if (files_2.Count == 0) - return ClearRecycleBinResult.Success; - else - return ClearRecycleBinResult.NotAllFilesDeleted; - } - catch (Exception ex) - { - Debug.WriteLine("Exception in RecyclebinWindow -> ClearRecycleBin" + ex.Message); - return ClearRecycleBinResult.Exception; - } - } - } - - public enum ClearRecycleBinResult - { - Success, Exception, NotAllFilesDeleted, NullError - } - public class RecycleBinListViewItem : ListViewItem - { - public StorageFile file { get; set; } - - public RecycleBinListViewItem(StorageFile file) - { - this.file = file; - this.Content = new TextBlock - { - Text = file.Name + "\n" + file.DateCreated.UtcDateTime.ToString() - }; - } - } -} diff --git a/Fastedit/Dialogs/SaveDialogs.cs b/Fastedit/Dialogs/SaveDialogs.cs deleted file mode 100644 index d773d97..0000000 --- a/Fastedit/Dialogs/SaveDialogs.cs +++ /dev/null @@ -1,75 +0,0 @@ -using Fastedit.Controls.Textbox; -using Fastedit.Core; -using System; -using System.Threading.Tasks; -using Windows.UI.Xaml.Controls; -using muxc = Microsoft.UI.Xaml.Controls; - -namespace Fastedit.Dialogs -{ - public class SaveDialogs - { - public static async Task AskSaveDialogNeverSaved(muxc.TabViewItem TabPage) - { - TextControlBox textbox = (TextControlBox)TabPage.Content; - AppSettings appsettings = new AppSettings(); - - var SaveDialog = new ContentDialog - { - Background = DefaultValues.ContentDialogBackgroundColor(), - Foreground = DefaultValues.ContentDialogForegroundColor(), - CornerRadius = DefaultValues.DefaultDialogCornerRadius, - Title = appsettings.GetResourceString("AskSaveDialog_Save/Text"), - Content = appsettings.GetResourceString("AskSaveDialog_AskToSaveFile/Text") + "\n" + textbox.Header, - PrimaryButtonText = appsettings.GetResourceString("AskSaveDialog_SaveButton/Text"), - SecondaryButtonText = appsettings.GetResourceString("AskSaveDialog_DontSaveButton/Text"), - CloseButtonText = appsettings.GetResourceString("AskSaveDialog_CancelButton/Text"), - RequestedTheme = DefaultValues.ContentDialogTheme() - }; - return await SaveDialog.ShowAsync(); - } - public static async Task AskSaveDialog(muxc.TabViewItem TabPage) - { - TextControlBox textbox = (TextControlBox)TabPage.Content; - - AppSettings appsettings = new AppSettings(); - var SaveDialog = new ContentDialog - { - Background = DefaultValues.ContentDialogBackgroundColor(), - - CornerRadius = DefaultValues.DefaultDialogCornerRadius, - Title = appsettings.GetResourceString("AskSaveDialog_Save/Text"), - Content = appsettings.GetResourceString("AskSaveDialog_AskSaveContent/Text") + "\n" + textbox.Header.Replace("*", ""), - PrimaryButtonText = appsettings.GetResourceString("AskSaveDialog_SaveButton/Text"), - SecondaryButtonText = appsettings.GetResourceString("AskSaveDialog_DontSaveButton/Text"), - CloseButtonText = appsettings.GetResourceString("AskSaveDialog_CancelButton/Text"), - RequestedTheme = DefaultValues.ContentDialogTheme(), - Foreground = DefaultValues.ContentDialogForegroundColor() - }; - return await SaveDialog.ShowAsync(); - } - public static async Task FileWasDeletedDialog(muxc.TabViewItem TabPage, bool ShowWithSecondaryButton = true) - { - TextControlBox textbox = (TextControlBox)TabPage.Content; - AppSettings appsettings = new AppSettings(); - - var SaveDialog = new ContentDialog - { - Background = DefaultValues.ContentDialogBackgroundColor(), - Foreground = DefaultValues.ContentDialogForegroundColor(), - CornerRadius = DefaultValues.DefaultDialogCornerRadius, - Title = appsettings.GetResourceString("AskSaveDialog_Save/Text"), - Content = appsettings.GetResourceString("AskSaveDialog_FileWasDeletedFromYourPc/Text") + "\n" + textbox.Header.Replace("*", ""), - PrimaryButtonText = appsettings.GetResourceString("AskSaveDialog_SaveButton/Text"), - CloseButtonText = appsettings.GetResourceString("AskSaveDialog_CancelButton/Text"), - RequestedTheme = DefaultValues.ContentDialogTheme() - }; - //Show second button only when tab gets closed - if (ShowWithSecondaryButton) - { - SaveDialog.SecondaryButtonText = appsettings.GetResourceString("AskSaveDialog_DontSaveButton/Text"); - } - return await SaveDialog.ShowAsync(); - } - } -} diff --git a/Fastedit/Dialogs/ShareDialog.cs b/Fastedit/Dialogs/ShareDialog.cs new file mode 100644 index 0000000..51951eb --- /dev/null +++ b/Fastedit/Dialogs/ShareDialog.cs @@ -0,0 +1,28 @@ +using Fastedit.Tab; +using Windows.ApplicationModel.DataTransfer; + +namespace Fastedit.Dialogs +{ + public class ShareDialog + { + private static TabPageItem CurrentTab = null; + + public static void Share(TabPageItem tab) + { + if (tab == null) + return; + + CurrentTab = tab; + DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView(); + dataTransferManager.DataRequested += DataTransferManager_DataRequested; + DataTransferManager.ShowShareUI(); + } + + private static void DataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args) + { + DataRequest request = args.Request; + request.Data.SetText(CurrentTab.textbox.GetText()); + request.Data.Properties.Title = CurrentTab.DatabaseItem.FileName; + } + } +} diff --git a/Fastedit/Dialogs/ShareFile.cs b/Fastedit/Dialogs/ShareFile.cs deleted file mode 100644 index a700528..0000000 --- a/Fastedit/Dialogs/ShareFile.cs +++ /dev/null @@ -1,38 +0,0 @@ -using Fastedit.Controls.Textbox; -using Windows.ApplicationModel.DataTransfer; - -namespace Fastedit.Dialogs -{ - public class ShareFile - { - private TextControlBox textBox = null; - - public ShareFile(TextControlBox tb) - { - textBox = tb; - DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView(); - dataTransferManager.DataRequested += DataTransferManager_DataRequested; - DataTransferManager.ShowShareUI(); - } - - private void DataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args) - { - DataRequest request = args.Request; - request.Data.SetText(textBox.GetText()); - request.Data.Properties.Title = textBox.Header; - } - - public static void ShareText(string text) - { - DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView(); - dataTransferManager.DataRequested += delegate (DataTransferManager sender, DataRequestedEventArgs args) - { - DataRequest request = args.Request; - request.Data.SetText(text); - request.Data.Properties.Title = "Share text"; - }; - DataTransferManager.ShowShareUI(); - - } - } -} diff --git a/Fastedit/Extensions/CodeFormatter.cs b/Fastedit/Extensions/CodeFormatter.cs deleted file mode 100644 index b2ffd2b..0000000 --- a/Fastedit/Extensions/CodeFormatter.cs +++ /dev/null @@ -1,88 +0,0 @@ -using Fastedit.Core; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Xml; - -namespace Fastedit.Extensions -{ - public class CodeFormatter - { - private static string Indent = DefaultValues.DefaultTabSize; - - public static XmlException FormatXml(string text, out string output) - { - output = text; - if (string.IsNullOrEmpty(text)) - return null; - - XmlDocument xmlDoc = new XmlDocument(); - StringWriter sw = new StringWriter(); - try - { - xmlDoc.LoadXml(text); - xmlDoc.Save(sw); - output = sw.ToString(); - return null; - } - catch (XmlException e) - { - return e; - } - } - - public static string FormatJson(string text) - { - if (string.IsNullOrEmpty(text)) - return text; - - var indentation = 0; - var quoteCount = 0; - var escapeCount = 0; - - var result = - from ch in text ?? string.Empty - let escaped = (ch == '\\' ? escapeCount++ : escapeCount > 0 ? escapeCount-- : escapeCount) > 0 - let quotes = ch == '"' && !escaped ? quoteCount++ : quoteCount - let unquoted = quotes % 2 == 0 - let colon = ch == ':' && unquoted ? ": " : null - let nospace = char.IsWhiteSpace(ch) && unquoted ? string.Empty : null - let lineBreak = ch == ',' && unquoted ? ch + Environment.NewLine + string.Concat(Enumerable.Repeat(Indent, indentation)) : null - let openChar = (ch == '{' || ch == '[') && unquoted ? ch + Environment.NewLine + string.Concat(Enumerable.Repeat(Indent, ++indentation)) : ch.ToString() - let closeChar = (ch == '}' || ch == ']') && unquoted ? Environment.NewLine + string.Concat(Enumerable.Repeat(Indent, --indentation)) + ch : ch.ToString() - select colon ?? nospace ?? lineBreak ?? ( - openChar.Length > 1 ? openChar : closeChar - ); - - return string.Concat(result); - } - - public static string FormatHtml(string text) - { - if (string.IsNullOrEmpty(text)) - return text; - try - { - return System.Xml.Linq.XElement.Parse(text).ToString(); - } - catch - { - return text; - // Your input is not a valid xml fragment. - } - } - - public static string FormatCs(string text) - { - if (string.IsNullOrEmpty(text)) - return text; - return CSharpSyntaxTree.ParseText(text).GetRoot().NormalizeWhitespace(Indent).ToFullString(); - - } - } -} diff --git a/Fastedit/Extensions/Convert.cs b/Fastedit/Extensions/Convert.cs deleted file mode 100644 index ac98b0b..0000000 --- a/Fastedit/Extensions/Convert.cs +++ /dev/null @@ -1,148 +0,0 @@ -using Fastedit.Core; -using System; -using System.Diagnostics; -using Windows.UI; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Markup; -using Windows.UI.Xaml.Media; - -namespace Fastedit.Extensions -{ - public static class Convert - { - public static Color GetColorFromTheme(ElementTheme theme) - { - if (theme == ElementTheme.Dark) - return Color.FromArgb(255, 0, 0, 0); - else - return Color.FromArgb(255, 255, 255, 255); - } - public static Color GetColorFromThemeReversed(ElementTheme theme) - { - if (theme == ElementTheme.Light) - return Color.FromArgb(255, 0, 0, 0); - else - return Color.FromArgb(255, 255, 255, 255); - } - public static Visibility BoolToVisibility(bool visible) - { - if (visible) - return Visibility.Visible; - else - return Visibility.Collapsed; - } - - public static Color WhiteOrBlackFromColorBrightness(Color input) - { - if (input.R + input.G + input.B >= (127 * 3)) //>=381: - { - return Color.FromArgb(255, 0, 0, 0); - } - else - { - return Color.FromArgb(255, 255, 255, 255); - } - } - - public static ElementTheme ThemeFromColorBrightness(Color input, AppSettings appsettings = null) - { - if (appsettings == null) - appsettings = new AppSettings(); - - if (appsettings.GetSettingsAsBool("UseMica", false) == true) - return ThemeHelper.RootTheme; - else - { - int midval = input.R + input.G + input.B; - if (midval >= (127 * 3)) //>=381: - return ElementTheme.Light; - else - return ElementTheme.Dark; - } - } - - public static Color ToColor(object clr, Color Default) - { - try - { - if (clr == null) return Default; - - if (clr is SolidColorBrush) { return (clr as SolidColorBrush).Color; } - else if (clr is AcrylicBrush) { return (clr as AcrylicBrush).TintColor; } - else if (clr is Color color) { return color; } - else if (Convert.ToInt(clr, -1) <= 5 && Convert.ToInt(clr, -1) >= 0) - { - AccentColors accentColor = (AccentColors)Enum.Parse(typeof(AccentColors), clr.ToString()); - if (accentColor == AccentColors.Dark2) - return DefaultValues.SystemAccentColorDark2; - else if (accentColor == AccentColors.Default) - return DefaultValues.SystemAccentColor; - else if (accentColor == AccentColors.Light2) - return DefaultValues.SystemAccentColorLight2; - else if (accentColor == AccentColors.Light1) - return DefaultValues.SystemAccentColorLight1; - else if (accentColor == AccentColors.Dark1) - return DefaultValues.SystemAccentColorDark1; - else - return Default; - } - else { return (Color)XamlBindingHelper.ConvertValue(typeof(Color), clr); } - } - catch (Exception ex) - { - Debug.WriteLine("Exception in Convert --> ToColor\n" + ex.Message); - return Default; - } - } - - public static double ToDouble(object Value, double Default = 0.0) - { - if (Value != null) - { - double Converted; - if (double.TryParse(Value.ToString(), out Converted) == true) - return Converted; - } - return Default; - } - - public static int ToInt(object Value, int Default = 0) - { - if (Value != null) - { - int Converted; - if (int.TryParse(Value.ToString(), out Converted) == true) - return Converted; - } - return Default; - } - - public static bool ToBoolean(object Value, bool Default = false) - { - bool Converted; - if (Value != null) - { - if (bool.TryParse(Value.ToString(), out Converted) == true) - return Converted; - - } - return Default; - } - - public static float ToFloat(object Value, float Default) - { - float Converted; - if (Value != null) - { - if (float.TryParse(Value.ToString(), out Converted) == true) - return Converted; - } - return Default; - } - - public static Color ToColor(SolidColorBrush clr) - { - return clr.Color; - } - } -} diff --git a/Fastedit/Extensions/Encodings.cs b/Fastedit/Extensions/Encodings.cs deleted file mode 100644 index c13d4dc..0000000 --- a/Fastedit/Extensions/Encodings.cs +++ /dev/null @@ -1,295 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Runtime.InteropServices.WindowsRuntime; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Windows.Storage; -using Windows.Storage.Streams; -using UnicodeEncoding = System.Text.UnicodeEncoding; - -namespace Fastedit.Extensions -{ - public class Encodings - { - public static readonly List AllEncodingNames = new List - { - "ANSI", "UTF-7", "UTF-8", "UTF-8-BOM", "UTF-16 BE", "UTF-16 LE","UTF-16 BE BOM", "UTF-16 LE BOM", "UTF-32 BE", "UTF-32 LE","UTF-32 BE BOM", "UTF-32 LE BOM" - }; - - private static Encoding _systemDefaultANSIEncoding; - private static Encoding _currentCultureANSIEncoding; - - public static Encoding DetectTextEncoding(byte[] b, out string text, int taster = 1000) - { - //////////////// First check the low hanging fruit by checking if a - //////////////// BOM/signature exists (sourced from http://www.unicode.org/faq/utf_bom.html#bom4) - if (b.Length >= 4 && b[0] == 0x00 && b[1] == 0x00 && b[2] == 0xFE && b[3] == 0xFF) { text = Encoding.GetEncoding("utf-32BE").GetString(b, 4, b.Length - 4); return Encoding.GetEncoding("utf-32BE"); } // UTF-32, big-endian - else if (b.Length >= 4 && b[0] == 0xFF && b[1] == 0xFE && b[2] == 0x00 && b[3] == 0x00) { text = Encoding.UTF32.GetString(b, 4, b.Length - 4); return Encoding.UTF32; } // UTF-32, little-endian - else if (b.Length >= 2 && b[0] == 0xFE && b[1] == 0xFF) { text = Encoding.BigEndianUnicode.GetString(b, 2, b.Length - 2); return Encoding.BigEndianUnicode; } // UTF-16, big-endian - else if (b.Length >= 2 && b[0] == 0xFF && b[1] == 0xFE) { text = Encoding.Unicode.GetString(b, 2, b.Length - 2); return Encoding.Unicode; } // UTF-16, little-endian - else if (b.Length >= 3 && b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF) { text = Encoding.UTF8.GetString(b, 3, b.Length - 3); return Encoding.UTF8; } // UTF-8 - else if (b.Length >= 3 && b[0] == 0x2b && b[1] == 0x2f && b[2] == 0x76) { text = Encoding.UTF7.GetString(b, 3, b.Length - 3); return Encoding.UTF7; } // UTF-7 - - //////////// If the code reaches here, no BOM/signature was found, so now - //////////// we need to 'taste' the file to see if can manually discover - //////////// the encoding. A high taster value is desired for UTF-8 - if (taster == 0 || taster > b.Length) taster = b.Length; // Taster size can't be bigger than the filesize obviously. - - // Some text files are encoded in UTF8, but have no BOM/signature. Hence - // the below manually checks for a UTF8 pattern. This code is based off - // the top answer at: https://stackoverflow.com/questions/6555015/check-for-invalid-utf8 - // For our purposes, an unnecessarily strict (and terser/slower) - // implementation is shown at: https://stackoverflow.com/questions/1031645/how-to-detect-utf-8-in-plain-c - // For the below, false positives should be exceedingly rare (and would - // be either slightly malformed UTF-8 (which would suit our purposes - // anyway) or 8-bit extended ASCII/UTF-16/32 at a vanishingly long shot). - int i = 0; - bool utf8 = false; - while (i < taster - 4) - { - if (b[i] <= 0x7F) { i += 1; continue; } // If all characters are below 0x80, then it is valid UTF8, but UTF8 is not 'required' (and therefore the text is more desirable to be treated as the default codepage of the computer). Hence, there's no "utf8 = true;" code unlike the next three checks. - if (b[i] >= 0xC2 && b[i] < 0xE0 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0) { i += 2; utf8 = true; continue; } - if (b[i] >= 0xE0 && b[i] < 0xF0 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0 && b[i + 2] >= 0x80 && b[i + 2] < 0xC0) { i += 3; utf8 = true; continue; } - if (b[i] >= 0xF0 && b[i] < 0xF5 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0 && b[i + 2] >= 0x80 && b[i + 2] < 0xC0 && b[i + 3] >= 0x80 && b[i + 3] < 0xC0) { i += 4; utf8 = true; continue; } - utf8 = false; break; - } - if (utf8 == true) - { - text = Encoding.UTF8.GetString(b); - return Encoding.UTF8; - } - - // The next check is a heuristic attempt to detect UTF-16 without a BOM. - // We simply look for zeroes in odd or even byte places, and if a certain - // threshold is reached, the code is 'probably' UF-16. - double threshold = 0.1; // proportion of chars step 2 which must be zeroed to be diagnosed as utf-16. 0.1 = 10% - int count = 0; - for (int n = 0; n < taster; n += 2) if (b[n] == 0) count++; - if (((double)count) / taster > threshold) { text = Encoding.BigEndianUnicode.GetString(b); return Encoding.BigEndianUnicode; } - count = 0; - for (int n = 1; n < taster; n += 2) if (b[n] == 0) count++; - if (((double)count) / taster > threshold) { text = Encoding.Unicode.GetString(b); return Encoding.Unicode; } // (little-endian) - - - // Finally, a long shot - let's see if we can find "charset=xyz" or - // "encoding=xyz" to identify the encoding: - for (int n = 0; n < taster - 9; n++) - { - if ( - ((b[n + 0] == 'c' || b[n + 0] == 'C') && (b[n + 1] == 'h' || b[n + 1] == 'H') && (b[n + 2] == 'a' || b[n + 2] == 'A') && (b[n + 3] == 'r' || b[n + 3] == 'R') && (b[n + 4] == 's' || b[n + 4] == 'S') && (b[n + 5] == 'e' || b[n + 5] == 'E') && (b[n + 6] == 't' || b[n + 6] == 'T') && (b[n + 7] == '=')) || - ((b[n + 0] == 'e' || b[n + 0] == 'E') && (b[n + 1] == 'n' || b[n + 1] == 'N') && (b[n + 2] == 'c' || b[n + 2] == 'C') && (b[n + 3] == 'o' || b[n + 3] == 'O') && (b[n + 4] == 'd' || b[n + 4] == 'D') && (b[n + 5] == 'i' || b[n + 5] == 'I') && (b[n + 6] == 'n' || b[n + 6] == 'N') && (b[n + 7] == 'g' || b[n + 7] == 'G') && (b[n + 8] == '=')) - ) - { - if (b[n + 0] == 'c' || b[n + 0] == 'C') n += 8; else n += 9; - if (b[n] == '"' || b[n] == '\'') n++; - int oldn = n; - while (n < taster && (b[n] == '_' || b[n] == '-' || (b[n] >= '0' && b[n] <= '9') || (b[n] >= 'a' && b[n] <= 'z') || (b[n] >= 'A' && b[n] <= 'Z'))) - { n++; } - byte[] nb = new byte[n - oldn]; - Array.Copy(b, oldn, nb, 0, n - oldn); - try - { - string internalEnc = Encoding.ASCII.GetString(nb); - text = Encoding.GetEncoding(internalEnc).GetString(b); - return Encoding.GetEncoding(internalEnc); - } - catch { break; } // If C# doesn't recognize the name of the encoding, break. - } - } - - - // If all else fails, the encoding is probably (though certainly not - // definitely) the user's local codepage! One might present to the user a - // list of alternative encodings as shown here: https://stackoverflow.com/questions/8509339/what-is-the-most-common-encoding-of-each-language - // A full list can be found using Encoding.GetEncodings(); - text = Encoding.Default.GetString(b); - return Encoding.Default; - } - public static Encoding StringToEncoding(string name) - { - switch (name) - { - case "ANSI": - if (TryGetSystemDefaultANSIEncoding(out var systemDefaultANSIEncoding)) return systemDefaultANSIEncoding; - else return TryGetCurrentCultureANSIEncoding(out var currentCultureANSIEncoding) ? currentCultureANSIEncoding : new UTF8Encoding(false); - case "UTF-7": - return new UTF7Encoding(); - case "UTF-8": - return new UTF8Encoding(false); - case "UTF-8-BOM": - return new UTF8Encoding(true); - case "UTF-16 BE BOM": - return new UnicodeEncoding(true, true); - case "UTF-16 LE BOM": - return new UnicodeEncoding(false, true); - case "UTF-16 BE": - return new UnicodeEncoding(true, false); - case "UTF-16 LE": - return new UnicodeEncoding(false, false); - case "UTF-32 BE BOM": - return new UTF32Encoding(true, true); - case "UTF-32 LE BOM": - return new UTF32Encoding(false, true); - case "UTF-32 BE": - return new UTF32Encoding(true, false); - case "UTF-32 LE": - return new UTF32Encoding(false, false); - default: - return Encoding.Default; - } - } - public static Encoding IntToEncoding(int index) - { - switch (index) - { - case 11: - if (TryGetSystemDefaultANSIEncoding(out var systemDefaultANSIEncoding)) return systemDefaultANSIEncoding; - else return TryGetCurrentCultureANSIEncoding(out var currentCultureANSIEncoding) ? currentCultureANSIEncoding : new UTF8Encoding(false); - case 0: - return new UTF7Encoding(); - case 1: - return new UTF8Encoding(false); - case 2: - return new UTF8Encoding(true); - case 3: - return new UnicodeEncoding(true, true); - case 4: - return new UnicodeEncoding(false, true); - case 5: - return new UnicodeEncoding(true, false); - case 6: - return new UnicodeEncoding(false, false); - case 7: - return new UTF32Encoding(true, true); - case 8: - return new UTF32Encoding(false, true); - case 9: - return new UTF32Encoding(true, false); - case 10: - return new UTF32Encoding(false, false); - default: - return Encoding.Default; - } - } - public static string EncodingToString(Encoding encoding) - { - string encodingName; - - switch (encoding) - { - case UTF7Encoding _: - encodingName = "UTF-7"; - break; - case UTF8Encoding _ when Equals(encoding, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true)): - encodingName = "UTF-8-BOM"; - break; - case UTF8Encoding _ when Equals(encoding, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)): - encodingName = "UTF-8"; - break; - case UnicodeEncoding _ when Equals(encoding, new UnicodeEncoding(bigEndian: true, byteOrderMark: true)): - encodingName = "UTF-16 BE BOM"; - break; - case UnicodeEncoding _ when Equals(encoding, new UnicodeEncoding(bigEndian: false, byteOrderMark: true)): - encodingName = "UTF-16 LE BOM"; - break; - case UnicodeEncoding _ when Equals(encoding, new UnicodeEncoding(bigEndian: true, byteOrderMark: false)): - encodingName = "UTF-16 BE"; - break; - case UnicodeEncoding _ when Equals(encoding, new UnicodeEncoding(bigEndian: false, byteOrderMark: false)): - encodingName = "UTF-16 LE"; - break; - case UTF32Encoding _ when Equals(encoding, new UTF32Encoding(bigEndian: true, byteOrderMark: true)): - encodingName = "UTF-32 BE BOM"; - break; - case UTF32Encoding _ when Equals(encoding, new UTF32Encoding(bigEndian: false, byteOrderMark: true)): - encodingName = "UTF-32 LE BOM"; - break; - case UTF32Encoding _ when Equals(encoding, new UTF32Encoding(bigEndian: true, byteOrderMark: false)): - encodingName = "UTF-32 BE"; - break; - case UTF32Encoding _ when Equals(encoding, new UTF32Encoding(bigEndian: false, byteOrderMark: false)): - encodingName = "UTF-32 LE"; - break; - default: - encodingName = "ANSI"; - break; - } - - return encodingName; - } - public static int EncodingToInt(Encoding encoding) - { - switch (encoding) - { - case UTF7Encoding _: - return 0; - case UTF8Encoding _ when Equals(encoding, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)): - return 1; - case UTF8Encoding _ when Equals(encoding, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true)): - return 2; - case UnicodeEncoding _ when Equals(encoding, new UnicodeEncoding(bigEndian: true, byteOrderMark: true)): - return 3; - case UnicodeEncoding _ when Equals(encoding, new UnicodeEncoding(bigEndian: false, byteOrderMark: true)): - return 4; - case UnicodeEncoding _ when Equals(encoding, new UnicodeEncoding(bigEndian: true, byteOrderMark: false)): - return 5; - case UnicodeEncoding _ when Equals(encoding, new UnicodeEncoding(bigEndian: false, byteOrderMark: false)): - return 6; - case UTF32Encoding _ when Equals(encoding, new UTF32Encoding(bigEndian: true, byteOrderMark: true)): - return 7; - case UTF32Encoding _ when Equals(encoding, new UTF32Encoding(bigEndian: false, byteOrderMark: true)): - return 8; - case UTF32Encoding _ when Equals(encoding, new UTF32Encoding(bigEndian: true, byteOrderMark: false)): - return 9; - case UTF32Encoding _ when Equals(encoding, new UTF32Encoding(bigEndian: false, byteOrderMark: false)): - return 10; - default: - return 11; - } - } - public static bool TryGetSystemDefaultANSIEncoding(out Encoding encoding) - { - try - { - if (_systemDefaultANSIEncoding != null) - { - encoding = _systemDefaultANSIEncoding; - return true; - } - Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); - encoding = Encoding.GetEncoding(0); - _systemDefaultANSIEncoding = encoding; - return true; - } - catch - { - } - - encoding = null; - return false; - } - public static bool TryGetCurrentCultureANSIEncoding(out Encoding encoding) - { - try - { - if (_currentCultureANSIEncoding != null) - { - encoding = _currentCultureANSIEncoding; - return true; - } - Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); - encoding = Encoding.GetEncoding(Thread.CurrentThread.CurrentCulture.TextInfo.ANSICodePage); - _currentCultureANSIEncoding = encoding; - return true; - } - catch - { - } - - encoding = null; - return false; - } - } -} diff --git a/Fastedit/Extensions/Enum.cs b/Fastedit/Extensions/Enum.cs deleted file mode 100644 index 287f344..0000000 --- a/Fastedit/Extensions/Enum.cs +++ /dev/null @@ -1,51 +0,0 @@ -namespace Fastedit.Extensions -{ - public enum TabSaveMode - { - SaveAsTemp = 0, - SaveAsFile = 1, - SaveAsDragDrop = 2, - } - - public enum AccentColors - { - None, - Light2, - Default, - Dark2, - Light1, - Dark1, - } - - public class ScrollbarPositions - { - public double ScrollbarPositionHorizontal { get; set; } - public double ScrollbarPositionVertical { get; set; } - } - - public enum Axis - { - X, - Y - } - - public enum VerticalAxis - { - Up, - Down - } - - public enum KeyModifiers - { - Control = 0, - Windows = 1, - Menu = 2, - Shift = 3, - None = 4 - } - public enum WindowsVersion - { - Windows10 , - Windows11 , - } -} \ No newline at end of file diff --git a/Fastedit/Extensions/Extension.cs b/Fastedit/Extensions/Extension.cs deleted file mode 100644 index a06ad9c..0000000 --- a/Fastedit/Extensions/Extension.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Fastedit.Controls.Textbox; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Windows.UI.Composition; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Media; - -namespace Fastedit.Extensions -{ - public static class Extension - { - public static DependencyObject FindElementByName(this DependencyObject parent, string name) - { - int count = VisualTreeHelper.GetChildrenCount(parent); - for (int i = 0; i < count; i++) - { - var child = VisualTreeHelper.GetChild(parent, i); - if (child is FrameworkElement && ((FrameworkElement)child).Name == name) - return child; - - var findres = FindElementByName(child, name); - if (findres != null) - return findres; - } - return null; - } - } -} diff --git a/Fastedit/Extensions/FileExtensions.cs b/Fastedit/Extensions/FileExtensions.cs deleted file mode 100644 index f4ae3d8..0000000 --- a/Fastedit/Extensions/FileExtensions.cs +++ /dev/null @@ -1,163 +0,0 @@ -using System.Collections.Generic; - -namespace Fastedit.Extensions -{ - public class FileExtensions - { - public List FileExtentionList = new List(); - - public FileExtensions() - { - FileExtentionList.Add(Batch); //.bat - FileExtentionList.Add(C); //.c - FileExtentionList.Add(CPP); //.cpp - FileExtentionList.Add(CSharp); //.cs - FileExtentionList.Add(CSS); //.css - FileExtentionList.Add(HTML); //.html - FileExtentionList.Add(INI); //.ini - FileExtentionList.Add(Java); //.java - FileExtentionList.Add(Python); //.py - FileExtentionList.Add(Reg); //.reg - FileExtentionList.Add(Text); //.txt - FileExtentionList.Add(XAML); //.xaml - FileExtentionList.Add(XML); //.xml - FileExtentionList.Add(Json); //.json - FileExtentionList.Add(Gcode); //.gcode - FileExtentionList.Add(VisualBasic); //.vb - FileExtentionList.Add(ArduinoSketch); //.ino - FileExtentionList.Add(PHP); //.php - FileExtentionList.Add(Assembly); //.asm - FileExtentionList.Add(Kotlin); //.kt - FileExtentionList.Add(Markdown); //.md - - //Sort list aplhabatically - FileExtentionList.Sort((a, b) => a.ExtensionName.CompareTo(b.ExtensionName)); - } - public ExtensionList Markdown = new ExtensionList() - { - Extension = { ".md", ".markdown", ".mdown", ".markdn" }, - ExtensionName = "Markdown", - ExtensionLongName = "Markdown" - }; - public ExtensionList Json = new ExtensionList() - { - Extension = { ".json" }, - ExtensionName = "Json", - ExtensionLongName = "Json" - }; - public ExtensionList Gcode = new ExtensionList() - { - Extension = { ".gcode", ".ngc", ".tap" }, - ExtensionName = "G-Code", - ExtensionLongName = "G-Code" - }; - public ExtensionList VisualBasic = new ExtensionList() - { - Extension = { ".vb" }, - ExtensionName = "Visual Basic", - }; - public ExtensionList ArduinoSketch = new ExtensionList() - { - Extension = { ".ino" }, - ExtensionName = "Arduino sketch", - }; - public ExtensionList PHP = new ExtensionList() - { - Extension = { ".php" }, - ExtensionName = "Hypertext preprocessor", - }; - public ExtensionList Assembly = new ExtensionList() - { - Extension = { ".asm" }, - ExtensionName = "Assembly language", - }; - public ExtensionList Kotlin = new ExtensionList() - { - Extension = { ".kt" }, - ExtensionName = "Kotlin", - }; - public ExtensionList CSharp = new ExtensionList() - { - Extension = { ".cs" }, - ExtensionName = "C-Sharp" - }; - public ExtensionList CPP = new ExtensionList() - { - Extension = { ".cpp", ".cxx", ".cc", ".hpp" }, - ExtensionName = "C++" - }; - public ExtensionList Python = new ExtensionList() - { - Extension = { ".py", ".py3", ".pyt", ".rpy", ".pyw" }, - ExtensionName = "Python", - ExtensionLongName = "Python" - }; - public ExtensionList Batch = new ExtensionList() - { - Extension = { ".bat" }, - ExtensionName = "Batch", - ExtensionLongName = "Windows batch" - }; - public ExtensionList XAML = new ExtensionList() - { - Extension = { ".xaml" }, - ExtensionName = "Xaml", - ExtensionLongName = "Extensible Application Markup Language" - }; - public ExtensionList XML = new ExtensionList() - { - Extension = { ".xml" }, - ExtensionName = "XML", - ExtensionLongName = "Extensible Markup Language" - }; - public ExtensionList HTML = new ExtensionList() - { - Extension = { ".html", ".htm", ".xhtml" }, - ExtensionName = "HTML", - ExtensionLongName = "Hypertext Markup Language" - }; - public ExtensionList Text = new ExtensionList() - { - Extension = { ".txt", ".log" }, - ExtensionName = "Textfile", - ExtensionLongName = "Textfile" - }; - public ExtensionList Reg = new ExtensionList() - { - Extension = { ".reg" }, - ExtensionName = "Registration file", - ExtensionLongName = "Windows Registration file" - }; - public ExtensionList CSS = new ExtensionList() - { - Extension = { ".css" }, - ExtensionName = "Cascading Style Sheets", - ExtensionLongName = "Cascading Style Sheets" - }; - public ExtensionList Java = new ExtensionList() - { - Extension = { ".java", ".jav", ".j" }, - ExtensionName = "Java", - ExtensionLongName = "Java" - }; - public ExtensionList INI = new ExtensionList() - { - Extension = { ".ini" }, - ExtensionName = "Configuration file", - ExtensionLongName = "Configuration file" - }; - public ExtensionList C = new ExtensionList() - { - Extension = { ".c", ".h" }, - ExtensionName = "C", - ExtensionLongName = "C" - }; - } - - public class ExtensionList - { - public List Extension = new List(); - public string ExtensionName { get; set; } - public string ExtensionLongName { get; set; } - } -} \ No newline at end of file diff --git a/Fastedit/Extensions/KeyboardCommands.cs b/Fastedit/Extensions/KeyboardCommands.cs deleted file mode 100644 index 6d05c9c..0000000 --- a/Fastedit/Extensions/KeyboardCommands.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using Windows.System; - -namespace Fastedit.Extensions -{ - public class KeyboardCommands - { - public static void KeyboardCommand(VirtualKey PressedKey, VirtualKey KeyNeedForAction, Action action, T args) - { - if (PressedKey == KeyNeedForAction) - { - action?.Invoke(args); - } - } - - public static void KeyboardCommand(VirtualKey PressedKey, VirtualKey KeyNeedForAction, Action action) - { - if (PressedKey == KeyNeedForAction) - { - action?.Invoke(); - } - } - - } -} diff --git a/Fastedit/Extensions/StringBuilder.cs b/Fastedit/Extensions/StringBuilder.cs deleted file mode 100644 index 82be86d..0000000 --- a/Fastedit/Extensions/StringBuilder.cs +++ /dev/null @@ -1,181 +0,0 @@ -using Newtonsoft.Json.Linq; -using System; -using System.IO; -using System.Linq; -using System.Text.RegularExpressions; -using System.Data; -using System.Diagnostics; - -namespace Fastedit.Extensions -{ - public class StringBuilder - { - public static string CleanUp(string str) - { - return Regex.Replace(str, @"\t|\n|\r", ""); - } - - public static int ToNumber(string number, int defaultout = 0) - { - return Convert.ToInt(number, defaultout); - } - - public static bool IsAllLetter(string str) - { - for (int i = 0; i < str.Length; i++) - { - if (!char.IsLetter(str, i)) - { - return false; - } - } - - return true; - } - public static bool IsAllLetterOrDigit(string str) - { - for (int i = 0; i < str.Length; i++) - { - if (!char.IsLetterOrDigit(str, i)) - { - return false; - } - } - - return true; - } - public static bool IsAllNumber(string str) - { - for (int i = 0; i < str.Length; i++) - { - if (!char.IsNumber(str, i)) - { - return false; - } - } - - return true; - } - - public static string ReplaceFirstOccurenceInString(string text, string Find, string replace) - { - int pos = text.IndexOf(Find); - if (pos < 0) - { - return text; - } - - return text.Substring(0, pos) + replace + text.Substring(pos + Find.Length); - } - public static string ReplaceLastOccurenceInString(string txt, string Find, string Replace) - { - int place = txt.LastIndexOf(Find); - - if (place == -1) - { - return txt; - } - return txt.Remove(place, Find.Length).Insert(place, Replace); - } - - public static bool IsBool(string str) - { - return bool.TryParse(str, out bool res); - } - - public static string GetStringFromImportedData(string[] source, string find) - { - string item = String.Join("", source.Where(a => a.Contains(find + "=", StringComparison.Ordinal))); - var splitted = item.Split('='); - if (splitted.Length > 0) - { - return splitted[1]; - } - return ""; - } - - public static bool IsValidFilename(string str) - { - return !string.IsNullOrEmpty(str) && - str.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 && - !File.Exists(str); - } - - public static int IndexOfWholeWord(string Text, string Word, int StartIndex) - { - for (int j = StartIndex; j < Text.Length && - (j = Text.IndexOf(Word, j, StringComparison.Ordinal)) >= 0; j++) - { - if ((j == 0 || !char.IsLetterOrDigit(Text, j - 1)) && - (j + Word.Length == Text.Length || !char.IsLetterOrDigit(Text, j + Word.Length))) - { - return j; - } - } - - return -1; - } - public static int LastIndexOfWholeWord(string Text, string Word) - { - int StartIndex = Text.Length - 1; - while (StartIndex >= 0 && (StartIndex = Text.LastIndexOf(Word, StartIndex, StringComparison.Ordinal)) != -1) - { - if (StartIndex > 0) - { - if (!char.IsLetterOrDigit(Text[StartIndex - 1])) - { - return StartIndex; - } - } - - if (StartIndex + Text.Length < Text.Length) - { - if (!char.IsLetterOrDigit(Text[StartIndex + Word.Length])) - { - return StartIndex; - } - } - - StartIndex--; - } - return -1; - } - public static string GetAbsolutePath(string path, string dir) - { - if (path.StartsWith("\"") && path.Length > 1) - { - var index = path.IndexOf('\"', 1); - if (index == -1) - return null; - path = path.Substring(1, index - 1); - } - - path = path.Trim('/').Replace('/', Path.DirectorySeparatorChar); - - if (!String.IsNullOrWhiteSpace(path) - && path.IndexOfAny(Path.GetInvalidPathChars().ToArray()) == -1 - && Path.IsPathRooted(path) - && !Path.GetPathRoot(path).Equals(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)) - { - return path; - } - - if (path.StartsWith(".\\")) - path = dir + Path.DirectorySeparatorChar + path.Substring(2, path.Length - 2); - else if (path.StartsWith("..\\")) - path = GetAbsolutePath(dir, path); - else - path = dir + Path.DirectorySeparatorChar + path; - return path; - } - - } - public static class Extensions - { - public static int findIndex(this T[] array, T item) - { - return Array.IndexOf(array, item); - } - } - -} \ No newline at end of file diff --git a/Fastedit/Extensions/Utilities.cs b/Fastedit/Extensions/Utilities.cs deleted file mode 100644 index 9efd2ca..0000000 --- a/Fastedit/Extensions/Utilities.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.Diagnostics; -using Windows.UI.Core; -using Windows.UI.ViewManagement; -using Windows.UI.Xaml; - -namespace Fastedit.Extensions -{ - public static class Utilities - { - public static void SetCursor(CoreCursorType cursor) - { - Window.Current.CoreWindow.PointerCursor = new Windows.UI.Core.CoreCursor(cursor, 0); - } - - /// - /// Set the fullscreen mode - /// - /// - /// - /// whether the app entered Fullscreen or not - public static bool FullScreen(bool Fullscreen, AppSettings appsettings = null) - { - try - { - bool isinfullscreen = false; - if (!Fullscreen) - { - ApplicationView.GetForCurrentView().ExitFullScreenMode(); - isinfullscreen = false; - } - else - { - isinfullscreen = ApplicationView.GetForCurrentView().TryEnterFullScreenMode(); - } - if (appsettings != null) - appsettings.SaveSettings("FullScreen", isinfullscreen); - return isinfullscreen; - } - catch (Exception e) - { - Debug.WriteLine("Exception in MainPage --> Fullscreen:" + "\n" + e.Message); - return false; - } - } - public static bool ToggleFullscreen(AppSettings appsettings = null) - { - return FullScreen(!ApplicationView.GetForCurrentView().IsFullScreenMode, appsettings); - } - } -} diff --git a/Fastedit/ExternalData/CustomDesigns.cs b/Fastedit/ExternalData/CustomDesigns.cs deleted file mode 100644 index 1c7f6be..0000000 --- a/Fastedit/ExternalData/CustomDesigns.cs +++ /dev/null @@ -1,444 +0,0 @@ -using Fastedit.Core; -using Fastedit.Dialogs; -using Fastedit.Extensions; -using Microsoft.UI.Xaml.Controls; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Security.Cryptography; -using System.Threading.Tasks; -using Windows.Storage; -using Windows.Storage.Pickers; -using Windows.UI; -using Windows.UI.Popups; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Media; -using muxc = Microsoft.UI.Xaml.Controls; - -namespace Fastedit.ExternalData -{ - public class CustomDesigns - { - private readonly AppSettings appsettings = new AppSettings(); - private GridView DesignGridView = null; - private ContentDialog NameRenameDialog = null; - private readonly MainPage mainpage = null; - private readonly muxc.InfoBar infobar = null; - public StorageFolder DesignsFolder = null; - public static List DesignItemsForSettings = new List() - { - "ThemeIndex","TextSelectionColorIndex","TextColorIndex","TextBackgroundColorIndex", - "TextColor","TextBackgroundColor","TextSelectionColor","LineNumberBackgroundColorIndex","LineNumberBackgroundColor", - "LineNumberForegroundColorIndex", "LineNumberForegroundColor", "AppBackgroundColorIndex","AppBackgroundColor", - "TitleBarBackgroundColor", "TitleBarBackgroundColorIndex", - "TabColorNotFocusedIndex","TabColorFocusedIndex","TabColorFocused","TabColorNotFocused", - "DialogBackgroundColor","DialogBackgroundColorIndex", "StatusbarForegroundColorIndex", - "StatusbarBackgroundColorIndex","StatusbarForegroundColor","StatusbarBackgroundColor", "UseMica","AcrylicEnabled", - "LineHighlighterBackground", "LineHighlighterForeground", "LineHighlighterForegroundIndex", - "LineHighlighterBackgroundIndex" - }; - - public CustomDesigns(GridView gridview, MainPage mp, muxc.InfoBar infobar = null) - { - SetStorageFolder(); - DesignGridView = gridview; - mainpage = mp; - this.infobar = infobar; - } - - private async void SetStorageFolder() - { - if (DesignsFolder == null) - DesignsFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(DefaultValues.CustomDesigns_FolderName, CreationCollisionOption.OpenIfExists); - } - public async void ShowError(string Content, string Title = "", muxc.InfoBarSeverity severity = muxc.InfoBarSeverity.Error) - { - if (mainpage == null) - { - if(infobar != null) - { - infobar.Message = Content; - infobar.Title = Title; - infobar.Severity = severity; - infobar.IsOpen = true; - return; - } - await new MessageDialog(Content, Title).ShowAsync(); - return; - } - mainpage.ShowInfobar(Content, Title, severity); - } - - public DesignGridViewItem CreateGridViewItem(StorageFile file) - { - var FileContent = File.ReadAllText(file.Path).Split("\n"); - Color BackgroundColor = Extensions.Convert.ToColor(StringBuilder.GetStringFromImportedData(FileContent, "AppBackgroundColor"), DefaultValues.DefaultAppBackgroundColor); - Color TextColor = Extensions.Convert.ToColor(StringBuilder.GetStringFromImportedData(FileContent, "TextColor"), DefaultValues.DefaultTextColor); - Color TitlebarColor = Extensions.Convert.ToColor(StringBuilder.GetStringFromImportedData(FileContent, "TitleBarBackgroundColor"), DefaultValues.DefaultTitleBarBackgroundColor); - - return new DesignGridViewItem - { - FileName = file.Name, - Background = new SolidColorBrush(BackgroundColor), - TextColor = new SolidColorBrush(TextColor), - TitlebarColor = new SolidColorBrush(TitlebarColor), - File = file - }; - } - public async Task AddAllDesignsToGridView() - { - if (DesignsFolder == null) - DesignsFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(DefaultValues.CustomDesigns_FolderName, CreationCollisionOption.OpenIfExists); - - int LastSelectedIndex = DesignGridView.SelectedIndex; - - string[] filePaths = Directory.GetFiles(DesignsFolder.Path); - DesignGridView.Items.Clear(); - - for (int i = 0; i < filePaths.Length; i++) - { - StorageFile sf = await DesignsFolder.GetFileAsync(Path.GetFileName(filePaths[i])); - var item = CreateGridViewItem(sf); - DesignGridView.Items.Add(item); - } - DesignGridView.SelectedIndex = LastSelectedIndex; - } - public bool DesignIsValid(string content) - { - if (content.Length == 0) - return false; - string[] contentstr = content.Split("\n", StringSplitOptions.RemoveEmptyEntries); - - for (int i = 0; i < contentstr.Length; i++) - { - if (contentstr[i].Length == 0 || !contentstr[i].Contains("=")) - { - return false; - } - } - return true; - } - public string CreateDesignContent() - { - string output = ""; - for (int i = 0; i < DesignItemsForSettings.Count; i++) - { - string key = DesignItemsForSettings[i]; - output += $"{key}={appsettings.GetSettings(key)}\n"; - } - return output; - } - private void ShowDesignValidInfo(bool IsValid) - { - ShowError(IsValid ? "Design changed successfully" : "Design load failed, maybe something is wrong with your file.", "", IsValid ? muxc.InfoBarSeverity.Success : muxc.InfoBarSeverity.Error); - } - public async Task ShowRenameDesignUI(string recentname = "") - { - var RenameTextBox = new TextBox - { - PlaceholderText = appsettings.GetResourceString("RenameThemeDialog_NamePlaceholder/Text"), - Height = 30, - HorizontalAlignment = HorizontalAlignment.Stretch, - VerticalAlignment = VerticalAlignment.Center, - Margin = new Thickness(0, 20, 0, 0) - }; - RenameTextBox.Text = recentname.Replace(DefaultValues.Extension_FasteditDesign, ""); - RenameTextBox.SelectAll(); - RenameTextBox.TextChanged += delegate - { - bool res = RenameTextBox.Text.Length > 0 && StringBuilder.IsValidFilename(RenameTextBox.Text); - RenameTextBox.BorderBrush = - res ? DefaultValues.CorrectInput_Color : DefaultValues.WrongInput_Color; - NameRenameDialog.IsPrimaryButtonEnabled = res; - }; - - NameRenameDialog = new ContentDialog - { - Foreground = DefaultValues.ContentDialogForegroundColor(), - Background = DefaultValues.ContentDialogBackgroundColor(), - CornerRadius = DefaultValues.DefaultDialogCornerRadius, - Title = appsettings.GetResourceString("RenameThemeDialog_Title/Text"), - Content = RenameTextBox, - PrimaryButtonText = appsettings.GetResourceString("RenameThemeDialog_DoneButton/Text"), - IsPrimaryButtonEnabled = true, - CloseButtonText = appsettings.GetResourceString("RenameThemeDialog_CancelButton/Text") - }; - var dialogres = await NameRenameDialog.ShowAsync(); - - if (dialogres == ContentDialogResult.Primary) - { - string textboxtext = RenameTextBox.Text; - if (textboxtext.Length != 0 && StringBuilder.IsValidFilename(textboxtext)) - { - if (!await DesignExsists(RenameTextBox.Text + DefaultValues.Extension_FasteditDesign)) - { - RenameTextBox.BorderBrush = DefaultValues.CorrectInput_Color; - return Path.GetFileNameWithoutExtension(textboxtext); - } - else - { - ShowError("A design with the specified name already exists!", "", muxc.InfoBarSeverity.Warning); - } - } - } - return ""; - } - - //loading design - public async Task LoadDesignFromFile(StorageFile file) - { - if (file != null) - { - string designData = await FileIO.ReadTextAsync(file); - - if (DesignIsValid(designData) == true) - { - LoadDesignData(designData.Split("\n")); - return true; - } - } - return false; - } - public void LoadDesignData(string[] lines) - { - for (int i = 0; i < DesignItemsForSettings.Count; i++) - { - appsettings.SaveSettings(DesignItemsForSettings[i], StringBuilder.GetStringFromImportedData(lines, DesignItemsForSettings[i])); - } - } - public async Task DesignExsists(string filename) - { - try - { - if (filename.Length < 1) - return false; - if (await DesignsFolder.GetFileAsync(filename) != null) - return true; - } - catch (Exception e) - { - Debug.WriteLine("Exception in CustomDesigns --> DesignExsists:" + "\n" + e.Message); - } - return false; - } - - public async Task GetFileFromDesignsFolder(string FileName) - { - if (FileName.Length == 0) - return null; - return await DesignsFolder.GetFileAsync(FileName); - } - public static async Task> GetAllInstalledDesigns() - { - try - { - List lst = new List(); - StorageFolder folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(DefaultValues.CustomDesigns_FolderName, CreationCollisionOption.OpenIfExists); - string[] filePaths = Directory.GetFiles(folder.Path); - - for (int i = 0; i < filePaths.Length; i++) - { - lst.Add(await folder.GetFileAsync(Path.GetFileName(filePaths[i]))); - } - return lst; - } - catch (Exception e) - { - Debug.WriteLine("Exception in CustomDesigns --> GetAllInstalledDesigns:" + "\n" + e.Message); - return null; - } - } - - public async Task OnSelectionChange() - { - try - { - if (appsettings.GetSettingsAsInt("SelectedDesign", 0) != DesignGridView.SelectedIndex && DesignGridView.SelectedIndex > -1) - { - appsettings.SaveSettings("SelectedDesign", DesignGridView.SelectedIndex); - - if (DesignGridView.SelectedItem is DesignGridViewItem item) - { - var res = await LoadDesignFromFile( - await GetFileFromDesignsFolder(item.FileName)); - ShowDesignValidInfo(res); - } - else - ShowError("Could not change the design"); - } - } - catch (Exception ex) - { - ShowError("Error occured while changing the design\n" + ex.Message); - } - } - - //design actions: - public async Task ImportDesign() - { - var picker = new FileOpenPicker(); - picker.ViewMode = PickerViewMode.Thumbnail; - picker.SuggestedStartLocation = PickerLocationId.ComputerFolder; - picker.FileTypeFilter.Add(DefaultValues.Extension_FasteditDesign); - - IReadOnlyList files = await picker.PickMultipleFilesAsync(); - - if (files == null) - return false; - bool retval = false; - for (int i = 0; i < files.Count; i++) - { - var file = files[i]; - if (file != null) - { - string fileContent = await FileIO.ReadTextAsync(file); - - bool isvalid = DesignIsValid(fileContent); - ShowDesignValidInfo(isvalid); - if (isvalid) - { - await file.CopyAsync(DesignsFolder, file.Name, NameCollisionOption.ReplaceExisting); - await AddAllDesignsToGridView(); - retval = true; - } - else - retval = false; - } - else - retval = false; - } - return retval; - } - public async Task SaveCurrentAsDesign(DesignGridViewItem item, bool UpdateItems = true, string designcontent = "") - { - try - { - if (item == null) - return false; - StorageFile file = await DesignsFolder.CreateFileAsync(item.FileName, CreationCollisionOption.ReplaceExisting); - if (file != null) - { - await FileIO.WriteTextAsync(file, designcontent == "" ? CreateDesignContent() : designcontent); - if(UpdateItems) - await AddAllDesignsToGridView(); - return true; - } - } - catch (Exception ex) - { - ShowError("Could not save theme\n" + ex.Message); - } - return false; - } - public async Task CreateNewDesign() - { - try - { - //just use the renameTheme function to name it - string designname = await ShowRenameDesignUI(); - if (designname.Length != 0) - { - StorageFile file = await DesignsFolder.CreateFileAsync(designname + DefaultValues.Extension_FasteditDesign, CreationCollisionOption.OpenIfExists); - if(file != null) - { - await FileIO.WriteTextAsync(file, CreateDesignContent()); - var item = CreateGridViewItem(file); - DesignGridView.Items.Add(item); - DesignGridView.SelectedItem = item; - } - } - - } - catch (Exception ex) - { - ShowError("Couldn't create a new Design" + ex.Message); - } - } - public async Task ExportDesign(DesignGridViewItem item) - { - void ReportError(string content) - { - ShowError("Could not export item!\n" + content, "Export error"); - } - try - { - FileSavePicker savePicker = new FileSavePicker - { - SuggestedStartLocation = PickerLocationId.DocumentsLibrary - }; - savePicker.FileTypeChoices.Add("Fasteditdesign", new List() { DefaultValues.Extension_FasteditDesign }); - savePicker.SuggestedFileName = item.FileName; - - StorageFile saveto_file = await savePicker.PickSaveFileAsync(); - if (saveto_file != null) - { - if (item != null) - { - StorageFile file2 = await DesignsFolder.GetFileAsync(item.FileName); - string text = await FileIO.ReadTextAsync(file2); - await FileIO.WriteTextAsync(saveto_file, text); - ShowError("Successfully exported\n", saveto_file.DisplayName, muxc.InfoBarSeverity.Success); - } - else - ReportError(""); - } - //Cancel pressed, do nothing here - } - catch (Exception ex) - { - ReportError(ex.Message); - } - } - public async Task DeleteDesign(DesignGridViewItem item) - { - try - { - if (item != null) - { - await item.File.DeleteAsync(StorageDeleteOption.PermanentDelete); - DesignGridView.Items.Remove(item); - } - } - catch (Exception ex) - { - ShowError("Could not delete item!\n" + ex.Message, "Delete error"); - } - } - public async Task RenameDesign(DesignGridViewItem item) - { - try - { - if (item != null) - { - string newname = await ShowRenameDesignUI(item.File.DisplayName); - if (newname.Length > 0) - { - StorageFile file = await DesignsFolder.GetFileAsync(item.FileName); - if (file != null) - { - await file.RenameAsync(newname + DefaultValues.Extension_FasteditDesign, NameCollisionOption.FailIfExists); - item.FileName = newname + DefaultValues.Extension_FasteditDesign; - await AddAllDesignsToGridView(); - } - } - } - } - catch (Exception ex) - { - ShowError(ex.Message); - } - } - } - public class DesignGridViewItem - { - private string _FileName = ""; - public string FileName { get => _FileName; set { _FileName = value; DisplayName = value.Replace(DefaultValues.Extension_FasteditDesign, ""); } } - public StorageFile File { get; set; } - public SolidColorBrush Background { get; set; } - public SolidColorBrush TextColor { get; set; } - public SolidColorBrush TitlebarColor { get; set; } - public string DisplayName { private set; get; } - } -} diff --git a/Fastedit/ExternalData/DatabaseImportExport.cs b/Fastedit/ExternalData/DatabaseImportExport.cs deleted file mode 100644 index cb90d5e..0000000 --- a/Fastedit/ExternalData/DatabaseImportExport.cs +++ /dev/null @@ -1,67 +0,0 @@ -using Fastedit.Core; -using Fastedit.Core.Tab; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Windows.Storage; -using Windows.UI.Xaml.Controls; -using muxc = Microsoft.UI.Xaml.Controls; - -namespace Fastedit.ExternalData -{ - public class DatabaseImportExport - { - private MainPage mainpage = null; - private muxc.TabView TextTabControl = null; - private TabActions tabactions = null; - - public DatabaseImportExport(MainPage mainpage, muxc.TabView tabview) - { - this.mainpage = mainpage; - this.TextTabControl = tabview; - this.tabactions = new TabActions(tabview, mainpage); - } - - public async Task CreateDatabaseBackup() - { - if (await tabactions.SaveAllTabChanges()) - { - var databasefolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(DefaultValues.Database_FolderName, CreationCollisionOption.OpenIfExists); - var backupfolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(DefaultValues.Backup_FolderName, CreationCollisionOption.OpenIfExists); - if (databasefolder == null || backupfolder == null) - return false; - else - { - var backupedFiles = await backupfolder.GetFilesAsync(); - for (int i = 0; i < backupedFiles.Count; i++) - { - var sf = backupedFiles[i] as StorageFile; - if (sf != null) - { - await sf.DeleteAsync(StorageDeleteOption.PermanentDelete); - } - } - var files = await databasefolder.GetFilesAsync(); - for (int i = 0; i < files.Count; i++) - { - if (files[i] is StorageFile file) - { - if (file != null) - if (await file.CopyAsync(backupfolder, file.Name, NameCollisionOption.ReplaceExisting) == null) - return false; - } - } - return true; - } - } - return false; - } - public async Task LoadDatabaseFromBackup() - { - return await tabactions.LoadTabs(true); - } - } -} diff --git a/Fastedit/ExternalData/ExportImportSettings.cs b/Fastedit/ExternalData/ExportImportSettings.cs deleted file mode 100644 index 1b6ce44..0000000 --- a/Fastedit/ExternalData/ExportImportSettings.cs +++ /dev/null @@ -1,126 +0,0 @@ -using Fastedit.Extensions; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Threading.Tasks; -using Windows.Storage; -using Windows.Storage.Pickers; - -namespace Fastedit.ExternalData -{ - public class ExportImportSettings - { - private AppSettings appsettings = new AppSettings(); - - List SettingsItems = new List() - { - "FontSizeIndex", - "ShowLineNumbers", - "ShowDropdown", - "AppLanguage", - "TabSizeModeIndex", - "NewTabTitleName", - "LoadRecentTabs", - "HideGoToLineDialogAfterEntering", - "SelectLineAfterGoingToIt", - "SelectedDesign", - "ShowStatusbar", - "StatusbarInBoldFont", - "ShowLinenumberButtonOn_SBar", - "ShowRenameButtonOn_SBar", - "ShowZoomButtonOn_SBar", - "ShowEncodingButtonOn_SBar", - "ShowSaveStatusButtonOn_SBar", - "ShowWordCountButtonOn_SBar", - "ShowNavigateToNextTab", - "ShowNavigateToPreviousTab", - "DesignForLightMode", - "DesignForDarkMode", - "AutomaticThemeChange", - "TabIconId", - "TextboxShowSelectionFlyout", - "HandwritingEnabled", - "SearchPanelCenterAlign", - "LineHighlighter", - "MenuBarAlignment", - "ShowMenubar" - }; - List AllItems = new List(); - - public ExportImportSettings() - { - if(AllItems.Count == 0) - { - AllItems.AddRange(SettingsItems); - AllItems.AddRange(CustomDesigns.DesignItemsForSettings); - } - } - - public string SetExportData() - { - string output = ""; - for (int i = 0; i < AllItems.Count; i++) - { - output += $"{AllItems[i]}={appsettings.GetSettings(AllItems[i])}\n"; - } - - return output; - } - private void LoadImportedData(string[] lines) - { - for (int i = 0; i < AllItems.Count; i++) - { - string key = AllItems[i]; - appsettings.SaveSettings(key, StringBuilder.GetStringFromImportedData(lines, key)); - } - } - - public async Task ImportSettings() - { - try - { - var picker = new FileOpenPicker(); - picker.ViewMode = PickerViewMode.Thumbnail; - picker.SuggestedStartLocation = PickerLocationId.ComputerFolder; - picker.FileTypeFilter.Add(".fasteditsettings"); - - StorageFile file = await picker.PickSingleFileAsync(); - if (file != null) - { - string text = await FileIO.ReadTextAsync(file); - if (text.Length != 0) - { - string[] lines = text.Split("\n"); - LoadImportedData(lines); - return true; - } - } - } - catch (Exception ex) - { - Debug.WriteLine("Exception in ExportImportSettings -> ImportSettings\n" + ex.Message); - } - return false; - } - public async Task ExportSettings() - { - try - { - FileSavePicker savePicker = new FileSavePicker(); - savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; - savePicker.FileTypeChoices.Add("FasteditSettings", new List() { ".fasteditsettings" }); - StorageFile file = await savePicker.PickSaveFileAsync(); - if (file != null) - { - await FileIO.WriteTextAsync(file, SetExportData()); - return true; - } - } - catch (Exception ex) - { - Debug.WriteLine("Exception in ExportImportSettings --> ExportSettings:" + "\n" + ex.Message); - } - return false; - } - } -} \ No newline at end of file diff --git a/Fastedit/Fastedit.csproj b/Fastedit/Fastedit.csproj index ca3cfc7..cf8e73e 100644 --- a/Fastedit/Fastedit.csproj +++ b/Fastedit/Fastedit.csproj @@ -4,7 +4,7 @@ Debug x86 - {EFBC8478-DC04-4052-9C14-B98673911134} + {14A97288-EEEA-4786-8D35-704B6244C05A} AppContainerExe Properties Fastedit @@ -22,11 +22,11 @@ False False True - Always + Auto x86|x64|arm True 0 - 01FF34FCAB2E9004534BA39AA07EB89B5358CFAE + 060B3D422BFABBF8BDDED3DEC51487DBAD4CC468 SHA256 @@ -36,13 +36,21 @@ DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP ;2008 full - x64 + x86 + false + prompt + true + + + true + bin\x86\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + full + x86 false prompt true - true - false - C:\Users\juliu\AppData\Local\Temp\vsA7B9.tmp\x86\Debug\ bin\x86\Release\ @@ -55,7 +63,6 @@ prompt true true - C:\Users\juliu\AppData\Local\Temp\vsA7B9.tmp\x86\Release\ true @@ -67,7 +74,6 @@ false prompt true - C:\Users\juliu\AppData\Local\Temp\vsA7B9.tmp\ARM\Debug\ bin\ARM\Release\ @@ -80,7 +86,6 @@ prompt true true - C:\Users\juliu\AppData\Local\Temp\vsA7B9.tmp\ARM\Release\ true @@ -93,7 +98,6 @@ prompt true true - C:\Users\juliu\AppData\Local\Temp\vsA7B9.tmp\ARM64\Debug\ bin\ARM64\Release\ @@ -106,7 +110,6 @@ prompt true true - C:\Users\juliu\AppData\Local\Temp\vsA7B9.tmp\ARM64\Release\ true @@ -118,9 +121,6 @@ false prompt true - false - false - C:\Users\juliu\AppData\Local\Temp\vsA7B9.tmp\x64\Debug\ bin\x64\Release\ @@ -133,7 +133,6 @@ prompt true true - C:\Users\juliu\AppData\Local\Temp\vsA7B9.tmp\x64\Release\ PackageReference @@ -142,103 +141,88 @@ App.xaml - - ColorChooserButton.xaml + + + RunCommandWindow.xaml - - CustomizationControl.xaml + + SearchControl.xaml - - ShortCutInfo.xaml + + SetingsItemSeparator.xaml - - - Searchdialog.xaml + + SettingsControl.xaml - - - TextControlBox.xaml + + StatusbarItem.xaml - - - - - + + - - - FileInfoDialog.xaml - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + - - - - - + - - + + + + + + + AboutPage.xaml MainPage.xaml - - PrivacyPoliciesPage.xaml - + + + + + + + + + + + SettingsPage.xaml - - ChangelogPage.xaml - - - KeyPage.xaml - - - Page1.xaml - - - Page2.xaml - - - Page3.xaml + + + Settings_AppPage.xaml - - Page4.xaml + + Settings_Data.xaml - - Page5.xaml + + Settings_DesignPage.xaml - - Page6.xaml + + Settings_DocumentPage.xaml - - Page7.xaml + + Settings_TabControl.xaml - - Page8.xaml - - - - TextboxViewPage.xaml + + TabWindowPage.xaml @@ -247,58 +231,64 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -331,6 +321,7 @@ + @@ -341,152 +332,105 @@ - - - - - + - - Designer - - - Designer - + + + + + + + + MSBuild:Compile Designer - - MSBuild:Compile + Designer + MSBuild:Compile - + Designer MSBuild:Compile - - MSBuild:Compile + Designer + MSBuild:Compile - + Designer MSBuild:Compile - - MSBuild:Compile + Designer - - MSBuild:Compile - Designer - MSBuild:Compile Designer + MSBuild:Compile MSBuild:Compile Designer - - Designer - MSBuild:Compile - - MSBuild:Compile - Designer - - Designer MSBuild:Compile - - MSBuild:Compile + Designer - - MSBuild:Compile - Designer - - MSBuild:Compile + Designer + MSBuild:Compile - + Designer MSBuild:Compile - - MSBuild:Compile + Designer - - MSBuild:Compile - Designer - - MSBuild:Compile + Designer - - MSBuild:Compile - Designer - - MSBuild:Compile + Designer - - MSBuild:Compile - Designer - - 4.1.0 - - 6.2.13 - - - 10.1901.28001 - - - 7.1.2 + 6.2.14 - 2.7.1 + 2.8.2 - 13.0.1 + 13.0.2 - - 1.26.0 + + 1.4.2 - - Microsoft Engagement Framework - - - - - - - - - - - - - - + + + + + + + + - + 14.0 diff --git a/Fastedit/Helper/AppActivationHelper.cs b/Fastedit/Helper/AppActivationHelper.cs new file mode 100644 index 0000000..bb6c826 --- /dev/null +++ b/Fastedit/Helper/AppActivationHelper.cs @@ -0,0 +1,119 @@ +using Fastedit.Tab; +using Microsoft.UI.Xaml.Controls; +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Windows.ApplicationModel.Activation; +using Windows.Storage; +using Windows.UI.Popups; +using Windows.UI.Xaml.Navigation; + +namespace Fastedit.Helper +{ + public class AppActivationHelper + { + public static NavigationEventArgs NavigationEvent = null; + + public static async Task HandleAppActivation(TabView tabView) + { + if (NavigationEvent.Parameter == null) + return false; + + if (NavigationEvent.Parameter is IActivatedEventArgs args) + { + if (args.Kind == ActivationKind.Launch) + { + Debug.WriteLine("Launched app without special activation"); + return true; + } + /*else if (args.Kind == ActivationKind.CommandLineLaunch) + { + + return false; + var handler = args as CommandLineActivatedEventArgs; + if (handler != null) + { + await new MessageDialog(handler.Operation.Arguments + ":" + handler.Operation.CurrentDirectoryPath, "").ShowAsync(); + + //var file = await HandleCommandLineLaunch(handler.Operation); + //if (file == null) + // return false; + + return false; + //return await TabPageHelper.OpenFile(tabView, file); + } + }*/ + else if (args.Kind == ActivationKind.File) + { + var handler = args as FileActivatedEventArgs; + if (handler != null) + { + return await TabPageHelper.OpenFiles(tabView, handler.Files); + } + } + } + return false; + } + + //Handle the commandline parameters + public static async Task HandleCommandLineLaunch(CommandLineActivationOperation operation) + { + try + { + if (operation.Arguments.Length < 1) + return null; + + string path = GetAbsolutePath(operation.Arguments, operation.CurrentDirectoryPath); + if (path == null || path.Length < 1) + return null; + + return await StorageFile.GetFileFromPathAsync(path); + } + catch (FileNotFoundException) + { + //ShowInfobar(InfoBarMessages.FileNotFound, InfoBarMessages.FileNotFoundTitle, muxc.InfoBarSeverity.Error); + } + catch (UnauthorizedAccessException) + { + //ShowInfobar(InfoBarMessages.FileNoAccess, InfoBarMessages.FileNoAccessTitle, muxc.InfoBarSeverity.Error); + } + catch (ArgumentException) + { + //ShowInfobar(InfoBarMessages.FileInvalidPath, InfoBarMessages.FileInvalidPathTitle, muxc.InfoBarSeverity.Error); + } + return null; + } + + //Get the path from the commandline parameters + public static string GetAbsolutePath(string path, string dir) + { + if (path.StartsWith("\"") && path.Length > 1) + { + var index = path.IndexOf('\"', 1); + if (index == -1) + return null; + path = path.Substring(1, index - 1); + } + + path = path.Trim('/').Replace('/', Path.DirectorySeparatorChar); + + if (!String.IsNullOrWhiteSpace(path) + && path.IndexOfAny(Path.GetInvalidPathChars().ToArray()) == -1 + && Path.IsPathRooted(path) + && !Path.GetPathRoot(path).Equals(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)) + { + return path; + } + + if (path.StartsWith(".\\")) + path = dir + Path.DirectorySeparatorChar + path.Substring(2, path.Length - 2); + else if (path.StartsWith("..\\")) + path = GetAbsolutePath(dir, path); + else + path = dir + Path.DirectorySeparatorChar + path; + return path; + } + } +} diff --git a/Fastedit/Helper/AutoDatabaseSaveHelper.cs b/Fastedit/Helper/AutoDatabaseSaveHelper.cs new file mode 100644 index 0000000..975bbf3 --- /dev/null +++ b/Fastedit/Helper/AutoDatabaseSaveHelper.cs @@ -0,0 +1,24 @@ +using Fastedit.Tab; +using System; +using Windows.UI.Xaml; + +namespace Fastedit.Helper +{ + internal class AutoDatabaseSaveHelper + { + public static TimeSpan DatabaseBackupTime = new TimeSpan(0, 4, 0); + + public static void RegisterSave() + { + DispatcherTimer timer = new DispatcherTimer(); + timer.Interval = DatabaseBackupTime; + timer.Tick += SaveDatabaseTimer_Tick; + timer.Start(); + } + + private static async void SaveDatabaseTimer_Tick(object sender, object e) + { + await TabPageHelper.mainPage.SaveDatabase(false); + } + } +} diff --git a/Fastedit/Helper/BackgroundHelper.cs b/Fastedit/Helper/BackgroundHelper.cs deleted file mode 100644 index c544012..0000000 --- a/Fastedit/Helper/BackgroundHelper.cs +++ /dev/null @@ -1,27 +0,0 @@ -using Fastedit.Core; -using Windows.UI.Xaml.Controls; -using muxc = Microsoft.UI.Xaml.Controls; - -namespace Fastedit.Helper -{ - public class BackgroundHelper - { - public static void SetBackgroundToPage(Page page) - { - AppSettings appsettings = new AppSettings(); - //Use the Mica background system - if (appsettings.GetSettingsAsBool("UseMica", false)) - { - muxc.BackdropMaterial.SetApplyToRootOrPageBackground(page, true); - } - //Use the default background system - else - { - muxc.BackdropMaterial.SetApplyToRootOrPageBackground(page, false); - //App backgroundcolor - page.Background = appsettings.CreateBrushWithOrWithoutAcrylic( - appsettings.GetSettingsAsColorWithDefault("AppBackgroundColor", DefaultValues.DefaultAppBackgroundColor)); - } - } - } -} diff --git a/Fastedit/Helper/ConvertHelper.cs b/Fastedit/Helper/ConvertHelper.cs new file mode 100644 index 0000000..a634c97 --- /dev/null +++ b/Fastedit/Helper/ConvertHelper.cs @@ -0,0 +1,89 @@ +using Windows.UI; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Media; + +namespace Fastedit.Helper +{ + public class ConvertHelper + { + public static Visibility BoolToVisibility(bool visible) + { + return visible ? Visibility.Visible : Visibility.Collapsed; + } + public static double ToDouble(object value, double defaultValue = 0) + { + if (value != null) + { + if (double.TryParse(value.ToString(), out double Converted) == true) + return Converted; + } + return defaultValue; + } + + public static int ToInt(object value, int defaultValue = 0) + { + if (value != null) + { + if (int.TryParse(value.ToString(), out int converted) == true) + return converted; + } + return defaultValue; + } + + public static bool ToBoolean(object value, bool defaultValue = false) + { + if (value != null) + { + if (bool.TryParse(value.ToString(), out bool converted) == true) + return converted; + } + return defaultValue; + } + + public static float ToFloat(object value, float defaultValue = 0) + { + if (value != null) + { + if (float.TryParse(value.ToString(), out float converted) == true) + return converted; + } + return defaultValue; + } + + public static Color ToColor(SolidColorBrush clr) + { + if (clr == null) + return Color.FromArgb(0, 0, 0, 0); + return clr.Color; + } + + public static Color ToColor(Brush brush, Color? defaultValue = null) + { + if (brush == null) + return defaultValue ?? Color.FromArgb(0, 0, 0, 0); + + if (brush is SolidColorBrush sbr) + return sbr.Color; + else if (brush is AcrylicBrush abr) + return abr.TintColor; + return defaultValue ?? Color.FromArgb(0, 0, 0, 0); + } + public static Color ToColor(Color? color) + { + return color ?? Color.FromArgb(0, 0, 0, 0); + } + public static Color GetColorFromTheme(ElementTheme theme) + { + if (theme == ElementTheme.Dark) + return Color.FromArgb(255, 0, 0, 0); + else + return Color.FromArgb(255, 255, 255, 255); + } + public static string ToString(object value) + { + if (value == null) + return ""; + return value.ToString(); + } + } +} diff --git a/Fastedit/Helper/DesignGridViewHelper.cs b/Fastedit/Helper/DesignGridViewHelper.cs new file mode 100644 index 0000000..dde17ea --- /dev/null +++ b/Fastedit/Helper/DesignGridViewHelper.cs @@ -0,0 +1,80 @@ +using Fastedit.Settings; +using Fastedit.Tab; +using System.IO; +using Windows.UI.Xaml.Controls; +using Windows.UI.Xaml.Media; + +namespace Fastedit.Helper +{ + public class DesignGridViewHelper + { + //Manage the GridView with design items + public static DesignGridViewItem CreateItem(FasteditDesign design, string designName, int width = 200, int height = 130) + { + return new DesignGridViewItem + { + TextColor = new SolidColorBrush(ConvertHelper.ToColor(design.TextColor)), + AppBackground = design.BackgroundType == BackgroundType.Null ? null : new SolidColorBrush(design.BackgroundType == BackgroundType.Mica ? ConvertHelper.GetColorFromTheme(design.Theme) : ConvertHelper.ToColor(design.BackgroundColor)), + TabPageBackground = new SolidColorBrush(ConvertHelper.ToColor(design.SelectedTabPageHeaderBackground)), + DesignName = designName, + LineNumberBackground = new SolidColorBrush(ConvertHelper.ToColor(design.LineNumberBackground)), + LineNumberColor = new SolidColorBrush(ConvertHelper.ToColor(design.LineNumberColor)), + TextBoxBackground = new SolidColorBrush(ConvertHelper.ToColor(design.TextBoxBackground)), + Width = width, + Height = height + }; + } + public static void LoadItems(GridView designGridView, int width = 200, int height = 130) + { + if (!Directory.Exists(DefaultValues.DesignPath)) + { + AppSettings.SaveSettings(AppSettingsValues.DesignLoaded, "0"); + DesignHelper.CopyDefaultDesigns(); + return; + } + + var files = Directory.GetFiles(DefaultValues.DesignPath); + + for (int i = 0; i < files.Length; i++) + { + var design = DesignHelper.GetDesignFromFile(files[i]); + if (design != null) + { + string name = DesignHelper.GetDesingNameFromPath(files[i]); + designGridView.Items.Add(CreateItem(design, name, width, height)); + + if (AppSettings.GetSettings(AppSettingsValues.Settings_DesignName) == name) + { + designGridView.SelectedIndex = i >= designGridView.Items.Count ? 0 : i; + } + } + } + } + public static void GridViewClick(ItemClickEventArgs e) + { + if (e.ClickedItem is DesignGridViewItem item && item != null) + { + AppSettings.SaveSettings(AppSettingsValues.Settings_DesignName, item.DesignName); + TabPageHelper.mainPage.ApplySettings(); + } + } + public static void UpdateItems(GridView designGridView) + { + designGridView.Items.Clear(); + LoadItems(designGridView); + } + } + + public class DesignGridViewItem + { + public Brush AppBackground { get; set; } + public Brush TextColor { get; set; } + public Brush LineNumberColor { get; set; } + public Brush TextBoxBackground { get; set; } + public Brush LineNumberBackground { get; set; } + public Brush TabPageBackground { get; set; } + public string DesignName { get; set; } + public int Width { get; set; } + public int Height { get; set; } + } +} diff --git a/Fastedit/Helper/DesignHelper.cs b/Fastedit/Helper/DesignHelper.cs new file mode 100644 index 0000000..d388bcb --- /dev/null +++ b/Fastedit/Helper/DesignHelper.cs @@ -0,0 +1,170 @@ +using Fastedit.Dialogs; +using Fastedit.Settings; +using Microsoft.UI.Xaml.Controls; +using Newtonsoft.Json; +using System; +using System.Diagnostics; +using System.IO; +using Windows.UI; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; +using Windows.UI.Xaml.Media; + +namespace Fastedit.Helper +{ + public class DesignHelper + { + public static FasteditDesign CurrentDesign = null; + + public static void LoadDesign() + { + var designName = AppSettings.GetSettings(AppSettingsValues.Settings_DesignName, DefaultValues.DefaultDesignName); + string path = Path.Combine(DefaultValues.DesignPath, designName); + + if (File.Exists(path)) + { + CurrentDesign = GetDesignFromFile(path); + } + //When the design could not get loaded, load alternative design: + if (CurrentDesign == null) + { + Debug.WriteLine("Load default design"); + CurrentDesign = LoadDefaultDesign(); + } + } + public static void CopyDefaultDesigns() + { + if (AppSettings.GetSettingsAsInt(AppSettingsValues.DesignLoaded) == 0) + { + //the designs are not loaded into the folder + AppSettings.SaveSettings(AppSettingsValues.DesignLoaded, 1); + + //load them: + var destinationPath = DefaultValues.DesignPath; + + //Check whether the path exists and create it if not + if (!Directory.Exists(destinationPath)) + Directory.CreateDirectory(destinationPath); + + var files = Directory.GetFiles("Designs"); + for (int i = 0; i < files.Length; i++) + { + File.Copy(files[i], Path.Combine(destinationPath, Path.GetFileName(files[i])), true); + } + } + } + public static string GetDesingNameFromPath(string path) + { + return Path.GetFileName(path); + } + public static FasteditDesign GetDesignFromFile(string path) + { + if (Path.GetExtension(path).Equals(".json") && File.Exists(path)) + { + try + { + return JsonConvert.DeserializeObject(File.ReadAllText(path)); + } + catch (Exception ex) + { + InfoMessages.DesignLoadError(GetDesingNameFromPath(path), ex); + } + } + return null; + } + + public static FasteditDesign LoadDefaultDesign() + { + return JsonConvert.DeserializeObject(File.ReadAllText(Path.Combine("Designs" + DefaultValues.DefaultDesignName))); + } + + public static void SetBackground(Control element, Color color, BackgroundType type) + { + if (element == null) + return; + + //remove mica + if (BackdropMaterial.GetApplyToRootOrPageBackground(element) && type != BackgroundType.Mica) + BackdropMaterial.SetApplyToRootOrPageBackground(element, false); + + int transparency = color.A; + color.A = 255; + if (type == BackgroundType.Null) + { + element.Background = null; + } + else if (type == BackgroundType.Acrylic) + { + element.Background = new Windows.UI.Xaml.Media.AcrylicBrush + { + TintColor = color, + TintOpacity = transparency / 255.0, + FallbackColor = color, + BackgroundSource = Windows.UI.Xaml.Media.AcrylicBackgroundSource.HostBackdrop, + }; + } + else if (type == BackgroundType.Solid) + { + element.Background = new SolidColorBrush { Color = color }; + } + else if (type == BackgroundType.Mica) + { + BackdropMaterial.SetApplyToRootOrPageBackground(element, true); + } + } + public static Brush CreateBackgroundBrush(Color color, ControlBackgroundType type) + { + int transparency = color.A; + color.A = 255; + + if (type == ControlBackgroundType.Acrylic) + { + return new Windows.UI.Xaml.Media.AcrylicBrush + { + TintColor = color, + TintOpacity = transparency / 255.0, + FallbackColor = color, + BackgroundSource = Windows.UI.Xaml.Media.AcrylicBackgroundSource.Backdrop, + }; + } + else if (type == ControlBackgroundType.Solid) + { + return new SolidColorBrush { Color = color }; + } + return null; + } + } + public class FasteditDesign + { + public ElementTheme Theme { get; set; } + public Color? BackgroundColor { get; set; } + public Color? TextColor { get; set; } + public Color? SelectionColor { get; set; } + public BackgroundType BackgroundType { get; set; } + public Color? LineNumberColor { get; set; } + public Color? LineNumberBackground { get; set; } + public Color? LineHighlighterBackground { get; set; } + public Color? TextBoxBackground { get; set; } + public Color? CursorColor { get; set; } + public Color? SearchHighlightColor { get; set; } + public ControlBackgroundType TextboxBackgroundType { get; set; } + public Color? SelectedTabPageHeaderTextColor { get; set; } + public Color? UnSelectedTabPageHeaderTextColor { get; set; } + public Color? UnselectedTabPageHeaderBackground { get; set; } + public Color? SelectedTabPageHeaderBackground { get; set; } + public Color? StatusbarTextColor { get; set; } + public ControlBackgroundType StatusbarBackgroundType { get; set; } + public Color? StatusbarBackgroundColor { get; set; } + public Color? DialogBackgroundColor { get; set; } + public Color? DialogTextColor { get; set; } + public ControlBackgroundType DialogBackgroundType { get; set; } + } + public enum BackgroundType + { + Acrylic, Solid, Mica, Null + } + public enum ControlBackgroundType + { + Acrylic, Solid, Null + } +} diff --git a/Fastedit/Helper/EncodingHelper.cs b/Fastedit/Helper/EncodingHelper.cs new file mode 100644 index 0000000..7164806 --- /dev/null +++ b/Fastedit/Helper/EncodingHelper.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Fastedit.Helper +{ + public class EncodingHelper + { + public static EncodingItem[] AllEncodings = { + new EncodingItem(new UTF8Encoding(false), "UTF-8"), + new EncodingItem(new UTF8Encoding(true), "UTF-8 BOM"), + new EncodingItem(new UnicodeEncoding(bigEndian: false, byteOrderMark: false), "UTF-16 LE"), + new EncodingItem(new UnicodeEncoding(bigEndian: true, byteOrderMark: false), "UTF-16 BE"), + new EncodingItem(new UnicodeEncoding(bigEndian: false, byteOrderMark: true), "UTF-16 LE BOM"), + new EncodingItem(new UnicodeEncoding(bigEndian: true, byteOrderMark: true), "UTF-16 BE BOM") + }; + + public static IEnumerable AllEncodingNames => AllEncodings.Select(x => x.name); + + public static Encoding DetectTextEncoding(byte[] b, out string text, int taster = 1000) + { + //////////////// First check the low hanging fruit by checking if a + //////////////// BOM/signature exists (sourced from http://www.unicode.org/faq/utf_bom.html#bom4) + if (b.Length >= 4 && b[0] == 0x00 && b[1] == 0x00 && b[2] == 0xFE && b[3] == 0xFF) { text = Encoding.GetEncoding("utf-32BE").GetString(b, 4, b.Length - 4); return Encoding.GetEncoding("utf-32BE"); } // UTF-32, big-endian + else if (b.Length >= 4 && b[0] == 0xFF && b[1] == 0xFE && b[2] == 0x00 && b[3] == 0x00) { text = Encoding.UTF32.GetString(b, 4, b.Length - 4); return Encoding.UTF32; } // UTF-32, little-endian + else if (b.Length >= 2 && b[0] == 0xFE && b[1] == 0xFF) { text = Encoding.BigEndianUnicode.GetString(b, 2, b.Length - 2); return Encoding.BigEndianUnicode; } // UTF-16, big-endian + else if (b.Length >= 2 && b[0] == 0xFF && b[1] == 0xFE) { text = Encoding.Unicode.GetString(b, 2, b.Length - 2); return Encoding.Unicode; } // UTF-16, little-endian + else if (b.Length >= 3 && b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF) { text = Encoding.UTF8.GetString(b, 3, b.Length - 3); return Encoding.UTF8; } // UTF-8 + else if (b.Length >= 3 && b[0] == 0x2b && b[1] == 0x2f && b[2] == 0x76) { text = Encoding.UTF7.GetString(b, 3, b.Length - 3); return Encoding.UTF7; } // UTF-7 + + //////////// If the code reaches here, no BOM/signature was found, so now + //////////// we need to 'taste' the file to see if can manually discover + //////////// the encoding. A high taster value is desired for UTF-8 + if (taster == 0 || taster > b.Length) taster = b.Length; // Taster size can't be bigger than the filesize obviously. + + // Some text files are encoded in UTF8, but have no BOM/signature. Hence + // the below manually checks for a UTF8 pattern. This code is based off + // the top answer at: https://stackoverflow.com/questions/6555015/check-for-invalid-utf8 + // For our purposes, an unnecessarily strict (and terser/slower) + // implementation is shown at: https://stackoverflow.com/questions/1031645/how-to-detect-utf-8-in-plain-c + // For the below, false positives should be exceedingly rare (and would + // be either slightly malformed UTF-8 (which would suit our purposes + // anyway) or 8-bit extended ASCII/UTF-16/32 at a vanishingly long shot). + int i = 0; + bool utf8 = false; + while (i < taster - 4) + { + if (b[i] <= 0x7F) { i += 1; continue; } // If all characters are below 0x80, then it is valid UTF8, but UTF8 is not 'required' (and therefore the text is more desirable to be treated as the default codepage of the computer). Hence, there's no "utf8 = true;" code unlike the next three checks. + if (b[i] >= 0xC2 && b[i] < 0xE0 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0) { i += 2; utf8 = true; continue; } + if (b[i] >= 0xE0 && b[i] < 0xF0 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0 && b[i + 2] >= 0x80 && b[i + 2] < 0xC0) { i += 3; utf8 = true; continue; } + if (b[i] >= 0xF0 && b[i] < 0xF5 && b[i + 1] >= 0x80 && b[i + 1] < 0xC0 && b[i + 2] >= 0x80 && b[i + 2] < 0xC0 && b[i + 3] >= 0x80 && b[i + 3] < 0xC0) { i += 4; utf8 = true; continue; } + utf8 = false; break; + } + if (utf8 == true) + { + text = Encoding.UTF8.GetString(b); + return Encoding.UTF8; + } + + // The next check is a heuristic attempt to detect UTF-16 without a BOM. + // We simply look for zeroes in odd or even byte places, and if a certain + // threshold is reached, the code is 'probably' UF-16. + double threshold = 0.1; // proportion of chars step 2 which must be zeroed to be diagnosed as utf-16. 0.1 = 10% + int count = 0; + for (int n = 0; n < taster; n += 2) if (b[n] == 0) count++; + if (((double)count) / taster > threshold) { text = Encoding.BigEndianUnicode.GetString(b); return Encoding.BigEndianUnicode; } + count = 0; + for (int n = 1; n < taster; n += 2) if (b[n] == 0) count++; + if (((double)count) / taster > threshold) { text = Encoding.Unicode.GetString(b); return Encoding.Unicode; } // (little-endian) + + + // Finally, a long shot - let's see if we can find "charset=xyz" or + // "encoding=xyz" to identify the encoding: + for (int n = 0; n < taster - 9; n++) + { + if ( + ((b[n + 0] == 'c' || b[n + 0] == 'C') && (b[n + 1] == 'h' || b[n + 1] == 'H') && (b[n + 2] == 'a' || b[n + 2] == 'A') && (b[n + 3] == 'r' || b[n + 3] == 'R') && (b[n + 4] == 's' || b[n + 4] == 'S') && (b[n + 5] == 'e' || b[n + 5] == 'E') && (b[n + 6] == 't' || b[n + 6] == 'T') && (b[n + 7] == '=')) || + ((b[n + 0] == 'e' || b[n + 0] == 'E') && (b[n + 1] == 'n' || b[n + 1] == 'N') && (b[n + 2] == 'c' || b[n + 2] == 'C') && (b[n + 3] == 'o' || b[n + 3] == 'O') && (b[n + 4] == 'd' || b[n + 4] == 'D') && (b[n + 5] == 'i' || b[n + 5] == 'I') && (b[n + 6] == 'n' || b[n + 6] == 'N') && (b[n + 7] == 'g' || b[n + 7] == 'G') && (b[n + 8] == '=')) + ) + { + if (b[n + 0] == 'c' || b[n + 0] == 'C') n += 8; else n += 9; + if (b[n] == '"' || b[n] == '\'') n++; + int oldn = n; + while (n < taster && (b[n] == '_' || b[n] == '-' || (b[n] >= '0' && b[n] <= '9') || (b[n] >= 'a' && b[n] <= 'z') || (b[n] >= 'A' && b[n] <= 'Z'))) + { n++; } + byte[] nb = new byte[n - oldn]; + Array.Copy(b, oldn, nb, 0, n - oldn); + try + { + string internalEnc = Encoding.ASCII.GetString(nb); + text = Encoding.GetEncoding(internalEnc).GetString(b); + return Encoding.GetEncoding(internalEnc); + } + catch { break; } // If C# doesn't recognize the name of the encoding, break. + } + } + + + // If all else fails, the encoding is probably (though certainly not + // definitely) the user's local codepage! One might present to the user a + // list of alternative encodings as shown here: https://stackoverflow.com/questions/8509339/what-is-the-most-common-encoding-of-each-language + // A full list can be found using Encoding.GetEncodings(); + text = Encoding.Default.GetString(b); + return Encoding.Default; + } + + public static Encoding GetEncodingByIndex(int index) + { + return AllEncodings[index].encoding; + } + public static string GetEncodingName(Encoding currentEncoding) + { + if (currentEncoding == null) + return AllEncodings[0].name; + + var res = AllEncodings.Where(x => x.encoding.Equals(currentEncoding)); + return res.Count() > 0 ? res.First().name : "Unknown"; + } + public static int GetIndexByEncoding(Encoding currentEncoding) + { + if (currentEncoding == null) + return 0; + + var res = AllEncodings.Where(x => x.encoding.Equals(currentEncoding)); + return res.Count() > 0 ? Array.IndexOf(AllEncodings, res.First()) : -1; + } + } + public struct EncodingItem + { + public EncodingItem(Encoding encoding, string name) + { + this.encoding = encoding; + this.name = name; + } + public Encoding encoding; + public string name; + } + +} diff --git a/Fastedit/Helper/KeyEventHelper.cs b/Fastedit/Helper/KeyEventHelper.cs new file mode 100644 index 0000000..9d8af05 --- /dev/null +++ b/Fastedit/Helper/KeyEventHelper.cs @@ -0,0 +1,17 @@ +using System; +using Windows.System; +using Windows.UI.Core; + +namespace Fastedit.Helper +{ + public class KeyEventHelper + { + public static void KeyboardCommand(KeyEventArgs PressedKey, VirtualKey KeyNeedForAction, Action action) + { + if (PressedKey.VirtualKey == KeyNeedForAction) + { + action?.Invoke(); + } + } + } +} diff --git a/Fastedit/Helper/SaveFileHelper.cs b/Fastedit/Helper/SaveFileHelper.cs deleted file mode 100644 index 6fec328..0000000 --- a/Fastedit/Helper/SaveFileHelper.cs +++ /dev/null @@ -1,258 +0,0 @@ -using Fastedit.Controls.Textbox; -using Fastedit.Dialogs; -using Fastedit.Extensions; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Windows.Storage; -using Windows.Storage.AccessCache; -using Windows.Storage.Pickers; -using Windows.UI.Core; -using Windows.UI.Xaml.Controls; -using muxc = Microsoft.UI.Xaml.Controls; - -namespace Fastedit.Helper -{ - public class SaveFileHelper - { - private TabPageHelper tabpagehelper = new TabPageHelper(); - /// - /// Save the file with a filepicker - /// - /// Whether the file was saved successfully - /// - public async Task SaveFileAs(muxc.TabViewItem TabPage) - { - try - { - FileExtensions fileextentions = new FileExtensions(); - FileSavePicker savePicker = new FileSavePicker(); - bool ExtensionIsRequested = false; - - //Request a fileextension: - var Textbox = tabpagehelper.GetTextBoxFromTabPage(TabPage); - if (Textbox!=null) - { - if (Textbox.MarkdownPreview && tabpagehelper.GetTabSaveMode(TabPage) == TabSaveMode.SaveAsTemp) - { - savePicker.FileTypeChoices.Add("Markdown", new List() { ".md" }); - ExtensionIsRequested = true; - } - else if (tabpagehelper.GetFileExtension(TabPage).Length != 0) - { - savePicker.FileTypeChoices.Add("Current file extension", new List() { tabpagehelper.GetFileExtension(TabPage) }); - } - } - for (int i = 0; i < fileextentions.FileExtentionList.Count; i++) - { - var item = fileextentions.FileExtentionList[i]; - savePicker.FileTypeChoices.TryAdd(item.ExtensionName, item.Extension); - } - savePicker.SuggestedFileName = ExtensionIsRequested ? Path.GetFileNameWithoutExtension(tabpagehelper.GetTabHeader(TabPage)) : tabpagehelper.GetTabHeader(TabPage); - - StorageFile file = await savePicker.PickSaveFileAsync(); - if (file != null) - { - if (Path.GetExtension(file.DisplayName) != string.Empty) - { - await file.RenameAsync(file.DisplayName); - } - bool result = await WriteTextToFile(file, tabpagehelper.GetTabEncoding(TabPage), tabpagehelper.GetTabText(TabPage), TabSaveMode.SaveAsFile); - if (result) - { - Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file); - - if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) - { - string Token = StorageApplicationPermissions.FutureAccessList.Add(file); - - var textbox = tabpagehelper.GetTextBoxFromTabPage(TabPage); - textbox.ShowInfoToast(true); - textbox.TextBeforeLastSaved = textbox.GetText(); - textbox.FilePath = file.Path; - textbox.DataBaseName = file.Name; - textbox.TempFile = string.Empty; - textbox.Storagefile = file; - textbox.TabSaveMode = TabSaveMode.SaveAsFile; - textbox.FileToken = Token; - - tabpagehelper.SetTabHeader(TabPage, file.Name); - tabpagehelper.SetTabModified(TabPage, false); - return true; - } - else - { - ErrorDialogs.SaveFileError(tabpagehelper.GetTabHeader(TabPage)); - } - } - } - } - catch (Exception e) - { - var filepath = string.Empty; - if (TabPage.Content is TextControlBox tb) - { - filepath = tb.FilePath; - } - Debug.WriteLine("Exception in SaveFileHelper -> SaveFileAs\n" + e.Message); - ErrorDialogs.OpenErrorDialog(filepath); - } - return false; - } - - /// - /// Save a file, which was already saved - /// - /// The tabpage - /// Wheater the databse is updated or not - /// Wheather the file save succed - public async Task SaveFile(muxc.TabViewItem TabPage, bool SaveChangesToDataBase = true) - { - try - { - StorageFile file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(tabpagehelper.GetTabToken(TabPage)); - - if (file != null) - { - var result = await WriteTextToFile(file, tabpagehelper.GetTabEncoding(TabPage), tabpagehelper.GetTabText(TabPage), tabpagehelper.GetTabSaveMode(TabPage)); - if (result == true) - { - var textbox = tabpagehelper.GetTextBoxFromTabPage(TabPage); - textbox.ShowInfoToast(true); - textbox.TextBeforeLastSaved = textbox.GetText(); - textbox.FilePath = file.Path; - textbox.DataBaseName = file.Name; - textbox.TempFile = string.Empty; - textbox.Storagefile = file; - - tabpagehelper.SetTabModified(TabPage, false); - tabpagehelper.SetTabHeader(TabPage, file.Name); - return true; - } - } - } - catch - { - return await ShowAskSaveDialogForTab(TabPage, true, false); - } - return false; - } - - /// - /// Chooses whether SaveFileAs or SaveFile, depending on the TabSaveMode - /// - /// The tabpage, to save the content from - /// Wheter the file was saved or not - public async Task Save(muxc.TabViewItem TabPage) - { - if (TabPage != null) - { - if (tabpagehelper.GetTabSaveMode(TabPage) == TabSaveMode.SaveAsTemp) - { - return await SaveFileAs(TabPage); - } - else - { - return await SaveFile(TabPage); - } - } - return false; - } - - /// - /// Writes text to file - /// - /// The file to write to - /// The encoding to write with - /// The text to write - public async Task WriteTextToFile(StorageFile file, Encoding encoding, string Text, TabSaveMode savemode) - { - try - { - //Do this only when the file was Dragged - if (savemode == TabSaveMode.SaveAsDragDrop) - { - var bytestoWrite = encoding.GetBytes(Text); - var buffer = encoding.GetPreamble().Concat(bytestoWrite).ToArray(); - await PathIO.WriteBytesAsync(file.Path, buffer); - return true; - } - //Do this every time savemode != Dragdrop - else - { - if (file != null) - { - await FileIO.WriteTextAsync(file, ""); - using (var stream = await file.OpenStreamForWriteAsync()) - { - var writer = new StreamWriter(stream, encoding); - await writer.WriteAsync(Text); - writer.Close(); - writer.Dispose(); - } - return true; - } - } - } - catch (UnauthorizedAccessException e) - { - string filepath = string.Empty; - if (file != null) - { - filepath = file.Path; - } - - await new InfoBox(e.Message + "\nFile: " + tabpagehelper.GetPathFromStorageFile(file), "No access to write to this file").ShowAsync(); - } - catch (Exception e) - { - Debug.Write("Exception in SaveFileHelper -> WriteTextToFile\n" + e.Message); - - await new InfoBox(e.Message + "\nFile: " + tabpagehelper.GetPathFromStorageFile(file), "No access to write to this file").ShowAsync(); - } - return false; - } - - public async Task ShowAskSaveDialogForTab(muxc.TabViewItem Tab, bool ShowFileWasDeletedDialog, bool FileWasDeletetWithSecondaryButton = true) - { - if (!ShowFileWasDeletedDialog) - { - ContentDialogResult dlgres; - if (tabpagehelper.GetTabSaveMode(Tab) == TabSaveMode.SaveAsFile || tabpagehelper.GetTabSaveMode(Tab) == TabSaveMode.SaveAsDragDrop) - { - dlgres = await SaveDialogs.AskSaveDialog(Tab); - } - else - { - dlgres = await SaveDialogs.AskSaveDialogNeverSaved(Tab); - } - - if (dlgres == ContentDialogResult.Primary) - { - return await Save(Tab); - } - else if (dlgres == ContentDialogResult.Secondary) - { - return true; - } - } - else - { - var dlgres = await SaveDialogs.FileWasDeletedDialog(Tab, FileWasDeletetWithSecondaryButton); - if (dlgres == ContentDialogResult.Primary) - { - return await SaveFileAs(Tab); - } - else if (dlgres == ContentDialogResult.Secondary) - { - return true; - } - } - return false; - } - } -} diff --git a/Fastedit/Helper/SecondaryEditingInstance.cs b/Fastedit/Helper/SecondaryEditingInstance.cs deleted file mode 100644 index 10654b6..0000000 --- a/Fastedit/Helper/SecondaryEditingInstance.cs +++ /dev/null @@ -1,211 +0,0 @@ -using Fastedit.Core.Tab; -using Fastedit.Dialogs; -using Fastedit.Views; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; -using Windows.ApplicationModel.Core; -using Windows.UI.Core; -using Windows.UI.ViewManagement; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using muxc = Microsoft.UI.Xaml.Controls; - -namespace Fastedit.Helper -{ - public class SecondaryEditingInstance - { - public List OpenedSecondaryViews = new List(); - private TabActions tabactions = null; - private MainPage mainpage = null; - private muxc.TabView TextTabControl = null; - private TabPageHelper tabpagehelper = new TabPageHelper(); - - public SecondaryEditingInstance(MainPage mp, TabActions tabactions, muxc.TabView tabcontrol) - { - mainpage = mp; - this.tabactions = tabactions; - this.TextTabControl = tabcontrol; - } - - //Functions to handle the secondary windows - private async Task GetViewIndexFromAppView(int ViewId) - { - int returnval = -1; - for (int i = 0; i < OpenedSecondaryViews.Count; i++) - { - await OpenedSecondaryViews[i].CoreApplicationView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => - { - if (ApplicationView.GetForCurrentView().Id == ViewId) - { - returnval = i; - } - }); - } - return returnval; - } - public async Task ApplySettingToAllViews() - { - if (OpenedSecondaryViews.Count == 0) - return; - - for (int i = 0; i < OpenedSecondaryViews.Count; i++) -{ - var view = OpenedSecondaryViews[i]; - await view.CoreApplicationView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => - { - if (Window.Current.Content is Frame frame) - { - if (frame.Content is TextboxViewPage tbvp) - { - tbvp.SetSettingsToTextBox(); - } - } - }); - } - - } - - public async Task ExpandTabPageToNewView(muxc.TabViewItem TabPage) - { - var textcontrolbox = tabactions.GetTextBoxFromTabPage(TabPage); - - //Run code only if tabpage is a textbox: - if (textcontrolbox == null) return; - - string TabPageName = TabPage.Name; - string Header = textcontrolbox.Header; - string tbtext = textcontrolbox.GetText(); - double tbZoomFactor = textcontrolbox._zoomFactor; - TextWrapping wrapping = textcontrolbox.WordWrap; - bool IsReadOnly = textcontrolbox.IsReadOnly; - int SelectionStart = textcontrolbox.SelectionStart; - ApplicationView appview = null; - CoreApplicationView newView = CoreApplication.CreateNewView(); - int newViewId = 0; - await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => - { - Frame frame = new Frame(); - frame.Navigate(typeof(TextboxViewPage)); - Window.Current.Content = frame; - Window.Current.Activate(); - - if (frame.Content is TextboxViewPage tbviewpage) - { - tbviewpage.TabPageName = TabPageName; - tbviewpage.Title = Header; - tbviewpage.TextboxText = tbtext; - tbviewpage.SelectionStart = SelectionStart; - tbviewpage.Textwrapping = wrapping; - tbviewpage.ZoomFactor = tbZoomFactor; - tbviewpage.IsReadonly = IsReadOnly; - tbviewpage.SetSettingsToTextBox(); - } - - appview = ApplicationView.GetForCurrentView(); - newViewId = appview.Id; - appview.Consolidated += TextboxViewPage_Consolidated; - }); - - TabPage.Visibility = Visibility.Collapsed; - - //if all tabs are in a secondary view, create a new tab - if (tabactions.GetShownTabPagesCount() < 1) - { - muxc.TabViewItem tab = tabactions.NewTab(); - if (tab != null) - { - TextTabControl.SelectedItem = tab; - await tabactions.SaveAllTabChanges(); - mainpage.SetSettingsToTabPage(tab, mainpage.TextBoxMargin()); - } - } - - await tabactions.GetTextBoxFromTabPage(TabPage).SetText("Cleared the textbox"); - for (int i = 0; i < TextTabControl.TabItems.Count; i++) - { - if (TextTabControl.TabItems[i] is muxc.TabViewItem Tab) - { - if (Tab.Visibility == Visibility.Visible) - { - TextTabControl.SelectedItem = Tab; - break; - } - } - } - - if (!await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId)) - { - mainpage.ShowInfobar(InfoBarMessages.CouldNotOpenInNewView, InfoBarMessages.CouldNotOpenInNewViewTitle, muxc.InfoBarSeverity.Error); - return; - } - OpenedSecondaryViews.Add(new OpenedSecondaryViewItem - { - ApplicationView = appview, - CoreApplicationView = newView - }); - } - private async Task CloseExpandedView(ApplicationView sender, bool RemoveFromOpenedViewList = true) - { - int index = await GetViewIndexFromAppView(sender.Id); - if (index < 0 || index >= OpenedSecondaryViews.Count) - return false; - - TextboxViewPage tbvpage = null; - string TabPageName = ""; - - //Get the view by the index returned from the GetViewIndexFromAppView - var view = OpenedSecondaryViews[index]; - await view.CoreApplicationView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => - { - if (Window.Current.Content is Frame frame) - { - if (frame.Content is TextboxViewPage tbvp) - { - tbvpage = tbvp; - TabPageName = tbvpage.TabPageName; - } - } - }); - if (tbvpage == null) - return false; - double ZoomFactor = tbvpage.ZoomFactor; - bool IsReadOnly = tbvpage.IsReadonly; - string TextBoxText = tbvpage.TextboxText; - int SelectionStart = tbvpage.SelectionStart; - bool IsModified = tbvpage.IsModified; - - if (tbvpage != null) - { - await mainpage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => - { - if (TextTabControl.FindName(TabPageName) is muxc.TabViewItem tabpage) - { - var textbox = tabactions.GetTextBoxFromTabPage(tabpage); - if (textbox != null) - { - await textbox.SetText(TextBoxText); - textbox.SetFontZoomFactor(ZoomFactor); - textbox.IsReadOnly = IsReadOnly; - textbox.SelectionStart = SelectionStart; - tabpagehelper.SetTabModified(tabpage, IsModified); - } - tabpage.Visibility = Visibility.Visible; - TextTabControl.SelectedItem = tabpage; - } - }); - if (RemoveFromOpenedViewList) - return OpenedSecondaryViews.Remove(view); - return true; - } - return false; - } - private async void TextboxViewPage_Consolidated(ApplicationView sender, ApplicationViewConsolidatedEventArgs args) - { - await CloseExpandedView(sender); - } - } -} \ No newline at end of file diff --git a/Fastedit/Helper/SettingsTabPageHelper.cs b/Fastedit/Helper/SettingsTabPageHelper.cs new file mode 100644 index 0000000..cd1edb6 --- /dev/null +++ b/Fastedit/Helper/SettingsTabPageHelper.cs @@ -0,0 +1,77 @@ +using Fastedit.Tab; +using Fastedit.Views; +using Microsoft.UI.Xaml.Controls; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; + +namespace Fastedit.Helper +{ + public delegate void SettingsPageClosedEvent(); + + public class SettingsTabPageHelper + { + public static TabViewItem settingsPage = null; + public static bool SettingsSelected { get; set; } = false; + public static bool SettingsPageOpen = false; + + public static event SettingsPageClosedEvent SettingsTabClosed; + + public static void InitialiseTab(MainPage mainPage, TabView tabView, string page = null) + { + if (settingsPage == null) + settingsPage = new TabViewItem + { + Header = "Settings", + IconSource = new Microsoft.UI.Xaml.Controls.SymbolIconSource { Symbol = Symbol.Setting }, + Content = new SettingsPage(new SettingsNavigationParameter(mainPage, tabView, page)), + }; + } + + public static void HideControls() + { + if (TabPageHelper.mainPage != null) + { + for (int i = 0; i < TabPageHelper.mainPage.ControlsToHideInSettings.Count; i++) + { + TabPageHelper.mainPage.ControlsToHideInSettings[i].Visibility = Visibility.Collapsed; + } + } + } + + public static void OpenSettings(MainPage mainPage, TabView tabView, string page = null) + { + InitialiseTab(mainPage, tabView, page); + + if (!tabView.TabItems.Contains(settingsPage)) + { + tabView.TabItems.Add(settingsPage); + } + + SettingsPageOpen = true; + tabView.SelectedItem = settingsPage; + } + public static void CloseSettings(TabView tabView) + { + tabView.TabItems.Remove(settingsPage); + SettingsPageOpen = false; + SettingsTabClosed?.Invoke(); + } + public static bool IsSettingsPage(object item) + { + return item is TabViewItem tab && tab.Content is SettingsPage; + } + } + + public class SettingsNavigationParameter + { + public SettingsNavigationParameter(MainPage mainPage, TabView tabView, string page = null) + { + MainPage = mainPage; + TabView = tabView; + Page = page; + } + public MainPage MainPage { get; set; } + public TabView TabView { get; set; } + public string Page { get; set; } + } +} diff --git a/Fastedit/Helper/ShareFileHelper.cs b/Fastedit/Helper/ShareFileHelper.cs new file mode 100644 index 0000000..97d3d29 --- /dev/null +++ b/Fastedit/Helper/ShareFileHelper.cs @@ -0,0 +1,33 @@ +using Fastedit.Tab; +using System; +using System.Collections.Generic; +using Windows.ApplicationModel.DataTransfer; +using Windows.Storage; + +namespace Fastedit.Helper +{ + public class ShareFileHelper + { + private static TabPageItem TabPage = null; + + public static void ShowShareUI(TabPageItem tab) + { + TabPage = tab; + DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView(); + dataTransferManager.DataRequested += DataTransferManager_DataRequested; + DataTransferManager.ShowShareUI(); + } + + private static async void DataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args) + { + var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("ShareTemp.txt", CreationCollisionOption.OpenIfExists); + if (file != null) + { + await FileIO.WriteTextAsync(file, TabPage.textbox.GetText()); + DataRequest request = args.Request; + request.Data.SetStorageItems(new List { file }); + request.Data.Properties.Title = TabPage.DatabaseItem.FileName; + } + } + } +} diff --git a/Fastedit/Helper/SizeCalculationHelper.cs b/Fastedit/Helper/SizeCalculationHelper.cs new file mode 100644 index 0000000..01b1c0b --- /dev/null +++ b/Fastedit/Helper/SizeCalculationHelper.cs @@ -0,0 +1,31 @@ +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; + +namespace Fastedit.Helper +{ + internal class SizeCalculationHelper + { + public static string SplitSize(ulong size) + { + Debug.WriteLine("SIZE: " + size); + if (size < 1_000) + return size + "B"; + else if (size > 1_000 && size < 1_000_000) + return (size / 1_000) + "KB"; + else if (size > 1_000_000) + return (size / 1_000_000) + "MB"; + return ""; + } + + public static string CalculateFolderSize(string path) + { + if (path == null || path.Length == 0) + return ""; + + DirectoryInfo di = new DirectoryInfo(path); + return SplitSize((ulong)di.EnumerateFiles("*", SearchOption.AllDirectories).Sum(fi => fi.Length)); + } + } +} diff --git a/Fastedit/Helper/TabPageHelper.cs b/Fastedit/Helper/TabPageHelper.cs deleted file mode 100644 index a0b8010..0000000 --- a/Fastedit/Helper/TabPageHelper.cs +++ /dev/null @@ -1,314 +0,0 @@ -using Fastedit.Controls.Textbox; -using Fastedit.Core; -using Fastedit.Extensions; -using System.IO; -using System.Text; -using Windows.Storage; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Media; -using muxc = Microsoft.UI.Xaml.Controls; - -namespace Fastedit.Helper -{ - public class TabPageHelper - { - private AppSettings appsettings = new AppSettings(); - - public TextControlBox GetTextBoxFromTabPage(muxc.TabViewItem TabPage) - { - if (TabPage != null) - { - if (TabPage.Content is TextControlBox tb) - return tb; - } - return null; - } - - //SetTab Properties - public void SetTabPath(muxc.TabViewItem TabPage, string FilePath) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - GetTextBoxFromTabPage(TabPage).FilePath = FilePath; - } - } - public void SetTabDataBaseName(muxc.TabViewItem TabPage, string DataBaseName) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - GetTextBoxFromTabPage(TabPage).DataBaseName = DataBaseName; - } - } - public void SetTabHeader(muxc.TabViewItem TabPage, string newTitle) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - if (TabPage.Header.ToString().Contains("*")) - { - TabPage.Header = newTitle + "*"; - } - else - { - TabPage.Header = newTitle; - } - GetTextBoxFromTabPage(TabPage).Header = newTitle; - } - } - public void SetTabModified(muxc.TabViewItem TabPage, bool isModified, bool SetModified = true) - { - if (GetTextBoxFromTabPage(TabPage) is TextControlBox textbox) - { - if (SetModified) - { - textbox.IsModified = isModified; - } - - var TabHeader = TabPage.Header.ToString(); - - if (isModified) - { - if (!TabHeader.Contains("*")) - { - TabHeader += "*"; - } - } - else - { - TabHeader = TabHeader.Replace("*", ""); - } - - TabPage.Header = TabHeader; - } - } - public void SetTabStorageFile(muxc.TabViewItem TabPage, StorageFile file) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - GetTextBoxFromTabPage(TabPage).Storagefile = file; - } - } - public void SetTabToken(muxc.TabViewItem TabPage, string Token) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - GetTextBoxFromTabPage(TabPage).FileToken = Token; - } - } - public void SetTabTemp(muxc.TabViewItem TabPage, string TempFile) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - GetTextBoxFromTabPage(TabPage).TempFile = TempFile; - } - } - public void SetTabReadOnly(muxc.TabViewItem TabPage, bool Readonly) - { - var tb = GetTextBoxFromTabPage(TabPage); - if (tb != null) - { - tb.IsReadOnly = Readonly; - - if (tb.IsReadOnly) - TabPage.IconSource = new muxc.SymbolIconSource() { Symbol = Symbol.ProtectedDocument }; - else - { - TabPage.IconSource = new muxc.FontIconSource - { - FontFamily = new FontFamily("Segoe MDL2 Assets"), - Glyph = appsettings.GetSettingsAsString("TabIconId", DefaultValues.DefaultTabIconId) - }; - } - } - } - public void SetTabSaveMode(muxc.TabViewItem TabPage, TabSaveMode TabSaveMode) - { - var tb = GetTextBoxFromTabPage(TabPage); - if (tb != null) - { - tb.TabSaveMode = TabSaveMode; - } - } - public void SetTabEncoding(muxc.TabViewItem TabPage, Encoding encoding) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - GetTextBoxFromTabPage(TabPage).Encoding = encoding; - } - } - public async void SetTabText(muxc.TabViewItem TabPage, string text) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - await GetTextBoxFromTabPage(TabPage).SetText(text); - } - } - public void SetTextBoxTextBevoreLastSaved(muxc.TabViewItem TabPage, string text) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - GetTextBoxFromTabPage(TabPage).TextBeforeLastSaved = text; - } - } - - //GetTab Properties - public string GetTabName(muxc.TabViewItem TabPage) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - return GetTextBoxFromTabPage(TabPage).Name; - } - - return string.Empty; - } - public bool GetIsModified(muxc.TabViewItem TabPage) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - return GetTextBoxFromTabPage(TabPage).IsModified; - } - return false; - } - public string GetDataBaseName(muxc.TabViewItem TabPage) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - return GetTextBoxFromTabPage(TabPage).DataBaseName; - } - - return string.Empty; - } - public string GetTabFilepath(muxc.TabViewItem TabPage) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - return GetTextBoxFromTabPage(TabPage).FilePath; - } - return string.Empty; - } - public string GetTabTempfile(muxc.TabViewItem TabPage) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - return GetTextBoxFromTabPage(TabPage).TempFile; - } - - return string.Empty; - } - public bool GetTabReadOnly(muxc.TabViewItem TabPage) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - return GetTextBoxFromTabPage(TabPage).IsReadOnly; - } - return false; - } - public string GetTabToken(muxc.TabViewItem TabPage) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - return GetTextBoxFromTabPage(TabPage).FileToken; - } - return string.Empty; - } - public TabSaveMode GetTabSaveMode(muxc.TabViewItem TabPage) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - return GetTextBoxFromTabPage(TabPage).TabSaveMode; - } - return TabSaveMode.SaveAsTemp; - } - public string GetFileExtension(muxc.TabViewItem TabPage) - { - TextControlBox tb = GetTextBoxFromTabPage(TabPage); - if (tb != null) - { - if (tb.Storagefile != null) - { - if (tb.Storagefile.FileType.Length != 0) - return tb.Storagefile.FileType; - } - else if (tb.TempFile.Length > 0) - { - return Path.GetExtension(tb.TempFile); - } - return Path.GetExtension(tb.Header); - } - return string.Empty; - } - public string GetTabHeader(muxc.TabViewItem TabPage) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - return GetTextBoxFromTabPage(TabPage).Header; - } - - return string.Empty; - } - public Encoding GetTabEncoding(muxc.TabViewItem TabPage) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - return GetTextBoxFromTabPage(TabPage).Encoding; - } - return Encoding.Default; - } - public string GetTabText(muxc.TabViewItem TabPage) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - return GetTextBoxFromTabPage(TabPage).GetText(); - } - return string.Empty; - } - public StorageFile GetTabStorageFile(muxc.TabViewItem TabPage) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - return GetTextBoxFromTabPage(TabPage).Storagefile; - } - return null; - } - public string GetPathFromStorageFile(StorageFile file) - { - if (file != null) - { - return file.Path; - } - - return string.Empty; - } - public string GetTabFileName(muxc.TabViewItem TabPage) - { - if (TabPage.Content is TextControlBox textbox) - { - return textbox.Header; - } - - return string.Empty; - } - public void SetUnsetLockFile(muxc.TabViewItem Tab) - { - if (Tab != null) - { - SetTabReadOnly(Tab, !GetTabReadOnly(Tab)); - } - } - public void ZoomIn(muxc.TabViewItem TabPage) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - GetTextBoxFromTabPage(TabPage).ZoomIn(DefaultValues.DefaultZoomFactor); - } - } - public void ZoomOut(muxc.TabViewItem TabPage) - { - if (GetTextBoxFromTabPage(TabPage) != null) - { - GetTextBoxFromTabPage(TabPage).ZoomOut(DefaultValues.DefaultZoomFactor); - } - } - - - } -} diff --git a/Fastedit/Helper/ThemeHelper.cs b/Fastedit/Helper/ThemeHelper.cs index 41001fb..7b5ed5d 100644 --- a/Fastedit/Helper/ThemeHelper.cs +++ b/Fastedit/Helper/ThemeHelper.cs @@ -1,26 +1,23 @@ using Windows.UI.Xaml; -namespace Fastedit.Extensions +namespace Fastedit.Helper { - public static class ThemeHelper + public class ThemeHelper { - public static ElementTheme RootTheme + public static ElementTheme CurrentTheme { - get + set { if (Window.Current.Content is FrameworkElement rootElement) { - return rootElement.RequestedTheme; + rootElement.RequestedTheme = value; } - - return ElementTheme.Light; } - set + get { if (Window.Current.Content is FrameworkElement rootElement) - { - rootElement.RequestedTheme = value; - } + return rootElement.RequestedTheme; + return ElementTheme.Default; } } } diff --git a/Fastedit/Helper/TitlebarHelper.cs b/Fastedit/Helper/TitlebarHelper.cs new file mode 100644 index 0000000..c1598d3 --- /dev/null +++ b/Fastedit/Helper/TitlebarHelper.cs @@ -0,0 +1,55 @@ +using Windows.ApplicationModel.Core; +using Windows.UI; +using Windows.UI.ViewManagement; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; + +namespace Fastedit.Helper +{ + public class TitlebarHelper + { + Grid CustomDragRegion, ShellTitlebarInset = null; + FlowDirection flowDirection; + + public TitlebarHelper(Grid CustomDragRegion, Grid ShellTitlebarInset, FlowDirection flowDirection) + { + this.CustomDragRegion = CustomDragRegion; + this.ShellTitlebarInset = ShellTitlebarInset; + this.flowDirection = flowDirection; + } + + public void SetTitlebar() + { + var coreTitleBar = CoreApplication.GetCurrentView().TitleBar; + coreTitleBar.ExtendViewIntoTitleBar = true; + coreTitleBar.LayoutMetricsChanged += CoreTitleBar_LayoutMetricsChanged; + Window.Current.SetTitleBar(CustomDragRegion); + + ApplicationView appView = ApplicationView.GetForCurrentView(); + appView.TitleBar.ButtonBackgroundColor = Colors.Transparent; + appView.TitleBar.ButtonInactiveBackgroundColor = Colors.Transparent; + } + + private void CoreTitleBar_LayoutMetricsChanged(CoreApplicationViewTitleBar sender, object args) + { + if (flowDirection == FlowDirection.LeftToRight) + { + CustomDragRegion.MinWidth = sender.SystemOverlayRightInset; + if (ShellTitlebarInset != null) + ShellTitlebarInset.MinWidth = sender.SystemOverlayLeftInset; + } + else + { + CustomDragRegion.MinWidth = sender.SystemOverlayLeftInset; + if (ShellTitlebarInset != null) + ShellTitlebarInset.MinWidth = sender.SystemOverlayRightInset; + } + CustomDragRegion.Height = sender.Height; + + if (ShellTitlebarInset != null) + ShellTitlebarInset.Height = CustomDragRegion.Height; + + } + + } +} diff --git a/Fastedit/Helper/VersionHelper.cs b/Fastedit/Helper/VersionHelper.cs index 5bd224b..08d76ab 100644 --- a/Fastedit/Helper/VersionHelper.cs +++ b/Fastedit/Helper/VersionHelper.cs @@ -1,40 +1,43 @@ -using Fastedit.Extensions; +using Fastedit.Controls; +using Fastedit.Settings; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using Windows.ApplicationModel; +using Windows.UI.Xaml.Controls; namespace Fastedit.Helper { public class VersionHelper { - public static WindowsVersion GetWindowsVersion() + private static bool IsOnNewVersion(string version) { - try - { - string Version = Environment.OSVersion.ToString(); - if (Version.Length == 0) - return WindowsVersion.Windows10; + string lastSavedVersion = AppSettings.GetSettings(AppSettingsValues.App_Version); + AppSettings.SaveSettings(AppSettingsValues.App_Version, version); - Version = Version.Remove(0, 26); - if (Version.Length == 0) - return WindowsVersion.Windows10; + //no version saved -> first start + if (lastSavedVersion.Length == 0) + return false; - int indexof = Version.IndexOf("."); - if (indexof > -1) - Version = Version.Remove(indexof, Version.Length - indexof); - int res = 0; - int.TryParse(Version, out res); - if (res >= 22000) - return WindowsVersion.Windows11; - else - return WindowsVersion.Windows10; - } - catch (Exception ex) when (ex is ArgumentOutOfRangeException || ex is ArgumentNullException || ex is InvalidOperationException) + if (!version.Equals(lastSavedVersion, StringComparison.Ordinal)) + return true; + + return false; + } + + public static void CheckNewVersion(StackPanel infobarDisplay) + { + string version = Package.Current.Id.Version.Major + "." + + Package.Current.Id.Version.Minor + "." + + Package.Current.Id.Version.Build; + + if (IsOnNewVersion(version)) { - return WindowsVersion.Windows10; + ShowNewVersionInfo(infobarDisplay, version); } } + + private static void ShowNewVersionInfo(StackPanel infobarDisplay, string version) + { + infobarDisplay.Children.Add(new InfobarMessage("New version", "Welcome to Fastedit version " + version, Microsoft.UI.Xaml.Controls.InfoBarSeverity.Success)); + } } } diff --git a/Fastedit/Helper/WindowHelper.cs b/Fastedit/Helper/WindowHelper.cs new file mode 100644 index 0000000..44081c1 --- /dev/null +++ b/Fastedit/Helper/WindowHelper.cs @@ -0,0 +1,59 @@ +using System; +using Windows.UI.ViewManagement; +using Windows.UI.WindowManagement; + +namespace Fastedit.Helper +{ + internal class WindowHelper + { + private static bool FullScreen(bool Fullscreen) + { + try + { + if (Fullscreen) + return ApplicationView.GetForCurrentView().TryEnterFullScreenMode(); + else + ApplicationView.GetForCurrentView().ExitFullScreenMode(); + return true; + } + catch + { + return false; + } + } + public static bool ToggleFullscreen() + { + return FullScreen(!ApplicationView.GetForCurrentView().IsFullScreen); + } + + public static async void ToggleCompactOverlay() + { + await ApplicationView.GetForCurrentView().TryEnterViewModeAsync( + ApplicationView.GetForCurrentView().ViewMode == ApplicationViewMode.Default ? ApplicationViewMode.CompactOverlay : ApplicationViewMode.Default); + } + + public static void ToggleCompactOverlayForAppWindow(AppWindow window) + { + if (window.Presenter.GetConfiguration().Kind != AppWindowPresentationKind.CompactOverlay) + { + window.Presenter.RequestPresentation(AppWindowPresentationKind.CompactOverlay); + } + else + { + window.Presenter.RequestPresentation(AppWindowPresentationKind.Default); + } + } + + public static void ToggleFullscreenForAppWindow(AppWindow window) + { + if (window.Presenter.GetConfiguration().Kind != AppWindowPresentationKind.FullScreen) + { + window.Presenter.RequestPresentation(AppWindowPresentationKind.FullScreen); + } + else + { + window.Presenter.RequestPresentation(AppWindowPresentationKind.Default); + } + } + } +} diff --git a/Fastedit/Package.appxmanifest b/Fastedit/Package.appxmanifest index 1e447d5..27b4a15 100644 --- a/Fastedit/Package.appxmanifest +++ b/Fastedit/Package.appxmanifest @@ -4,60 +4,59 @@ xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" - xmlns:desktop4="http://schemas.microsoft.com/appx/manifest/desktop/windows10/4" - xmlns:iot2="http://schemas.microsoft.com/appx/manifest/iot/windows10/2" xmlns:uap5="http://schemas.microsoft.com/appx/manifest/uap/windows10/5" xmlns:uap10="http://schemas.microsoft.com/appx/manifest/uap/windows10/10" xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" - IgnorableNamespaces="uap mp uap5 uap10 desktop4 iot2 rescap"> + IgnorableNamespaces="uap mp uap5 uap10 rescap"> - + - + - - Fastedit - Julius Kirsch - Assets\App_Icon\Generated\StoreLogo.png - + + Fastedit + Julius Kirsch + Assets\AppIcon\Generated\StoreLogo.png + - - - + + + - - - - + + + + - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + - - - - Assembly - Assets\ExtensionIcons\asm\asm.png - - - .asm - - - - - - - .txt - .log - - Text - Assets\ExtensionIcons\TXT\txt.png - - - - - - - .randomextension - * - - - Assets\ExtensionIcons\any\any.png - Fastedit - - - - - - .c - .h - - GCC file - Assets\ExtensionIcons\C\C.png - - - - - - .cs - - C-Sharp - Assets\ExtensionIcons\C-Sharp\cs.png - - - - - - .js - - Java Script - - Assets\ExtensionIcons\JS\js.png - - - - - - .py - .py3 - .pyt - .rpy - .pyw - - Assets\ExtensionIcons\Python\py.png - Python - - - - - - - .html - .htm - .xhtml - - HTML - - Assets\ExtensionIcons\HTML\html.png - - - - - - .java - .jav - .j - - Assets\ExtensionIcons\Java\java.png - Java - - - - - - - .json - - JSON - Assets\ExtensionIcons\Json\json.png - - - - - - - .gcode - .ngc - .tap - - G-Code - Assets\ExtensionIcons\G-Code\gcode.png - - - - - - .vb - - Visual Basic - Assets\ExtensionIcons\VB\vb.png - - - - - - .ino - - Arduino sketch - Assets\ExtensionIcons\Ino\ino.png - - - - - - .php - - PHP - Assets\ExtensionIcons\PHP\php.png - - - - - - .kt - - Kotlin - Assets\ExtensionIcons\Kotlin\KT.png - - - - - - .cpp - .cc - .cxx - .hpp - - C++ - - Assets\ExtensionIcons\C++\cpp.png - - - - - - .xml - - XML - - Assets\ExtensionIcons\xml\xml.png - - - - - - .css - - Cascading Style Sheets - Assets\ExtensionIcons\CSS\css.png - - - - - - - .ini - - INI - Assets\ExtensionIcons\ini\ini.png - - - - - - .cfg - .properties - - - Assets\ExtensionIcons\Config\Config.png - Config - - - - - - .md - .markdown - .mdown - .markdn - - Markdown - Assets\ExtensionIcons\Markdown\MD.png - - - - - - - - - + + + Assembly + Assets\ExtensionIcons\asm\asm.png + + + .asm + + + + + + + + .txt + .log + + Text + Assets\ExtensionIcons\TXT\txt.png + + + + + + + .randomextension + * + + + Assets\ExtensionIcons\any\any.png + Fastedit + + + + + + .c + .h + + GCC file + Assets\ExtensionIcons\C\C.png + + + + + + .cs + + + C-Sharp + Assets\ExtensionIcons\C-Sharp\cs.png + + + + + + .js + + Java Script + + Assets\ExtensionIcons\JS\js.png + + + + + + .py + .py3 + .pyt + .rpy + .pyw + + Assets\ExtensionIcons\Python\py.png + Python + + + + + + + .html + .htm + .xhtml + + HTML + + Assets\ExtensionIcons\HTML\html.png + + + + + + .java + .jav + .j + + Assets\ExtensionIcons\Java\java.png + Java + + + + + + + .json + + JSON + Assets\ExtensionIcons\Json\json.png + + + + + + + .gcode + .ngc + .tap + + G-Code + Assets\ExtensionIcons\G-Code\gcode.png + + + + + + .vb + + Visual Basic + Assets\ExtensionIcons\VB\vb.png + + + + + + .ino + + Arduino sketch + Assets\ExtensionIcons\Ino\ino.png + + + + + + .php + + PHP + Assets\ExtensionIcons\PHP\php.png + + + + + + .kt + + Kotlin + Assets\ExtensionIcons\Kotlin\KT.png + + + + + + .cpp + .cc + .cxx + .hpp + + C++ + + Assets\ExtensionIcons\C++\cpp.png + + + + + + .xml + + XML + + Assets\ExtensionIcons\xml\xml.png + + + + + + .css + + Cascading Style Sheets + Assets\ExtensionIcons\CSS\css.png + + + + + + + .ini + + INI + Assets\ExtensionIcons\ini\ini.png + + + + + + .cfg + .properties + + + Assets\ExtensionIcons\Config\Config.png + Config + + + + + + .md + .markdown + .mdown + .markdn + + Markdown + Assets\ExtensionIcons\Markdown\MD.png + + + + + + + + + diff --git a/Fastedit/Properties/AssemblyInfo.cs b/Fastedit/Properties/AssemblyInfo.cs index f9ee74e..8a5690a 100644 --- a/Fastedit/Properties/AssemblyInfo.cs +++ b/Fastedit/Properties/AssemblyInfo.cs @@ -1,30 +1,30 @@ -using System.Reflection; -using System.Resources; +using System.Resources; +using System.Reflection; using System.Runtime.InteropServices; -// Allgemeine Informationen über eine Assembly werden über die folgenden -// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, -// die einer Assembly zugeordnet sind. +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. [assembly: AssemblyTitle("Fastedit")] -[assembly: AssemblyDescription("")] +[assembly: AssemblyDescription("A tabbed and fluent texteditor for windows")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Fastedit")] -[assembly: AssemblyCopyright("Copyright © 2022")] +[assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: +// Version information for an assembly consists of the following four values: // -// Hauptversion -// Nebenversion -// Buildnummer +// Major Version +// Minor Version +// Build Number // Revision // -// Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden, -// indem Sie "*" wie unten gezeigt eingeben: -// [Assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.6.2.0")] -[assembly: AssemblyFileVersion("1.6.2.0")] +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("2.0.0.0")] +[assembly: AssemblyFileVersion("2.0.0.0")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] diff --git a/Fastedit/Properties/Default.rd.xml b/Fastedit/Properties/Default.rd.xml index da99c84..af00722 100644 --- a/Fastedit/Properties/Default.rd.xml +++ b/Fastedit/Properties/Default.rd.xml @@ -1,30 +1,30 @@ - + diff --git a/Fastedit/Settings/AppSettings.cs b/Fastedit/Settings/AppSettings.cs index 98c8dd4..e7233ae 100644 --- a/Fastedit/Settings/AppSettings.cs +++ b/Fastedit/Settings/AppSettings.cs @@ -1,194 +1,44 @@ -using Fastedit.Core; -using Fastedit.Extensions; -using System; -using System.Collections.Generic; -using System.Diagnostics; -using Windows.ApplicationModel.Resources; +using Fastedit.Helper; using Windows.Storage; using Windows.UI; -using Windows.UI.Xaml; using Windows.UI.Xaml.Markup; -using Windows.UI.Xaml.Media; -using Convert = Fastedit.Extensions.Convert; -namespace Fastedit +namespace Fastedit.Settings { public class AppSettings { - //!! REPLACE "." WITH "/" !!// - public string GetResourceString(string keyStr) - { - var stringout = ResourceLoader.GetForCurrentView().GetString(keyStr); - return stringout.Length != 0 ? stringout : "NULL"; - } - public static string GetResourceStringStatic(string keyStr) - { - var stringout = ResourceLoader.GetForCurrentView().GetString(keyStr); - return stringout.Length != 0 ? stringout : "NULL"; - } - - public ElementTheme CurrentApplicationTheme - { - get - { - return (ElementTheme)Enum.Parse(typeof(ElementTheme), GetSettingsAsString("ThemeIndex", "0")); - } - } - - public Brush CreateBrushWithOrWithoutAcrylic(Color color) - { - if (GetSettingsAsBool("AcrylicEnabled", true) == false || color.A>=255) - { - return new SolidColorBrush(color); - } - else - { - return new AcrylicBrush - { - TintColor = color, - TintOpacity = (double)color.A / 2.55, - FallbackColor = color, - BackgroundSource = AcrylicBackgroundSource.HostBackdrop, - }; - } - } - - public void SaveSettings(string Value, object data) + public static void SaveSettings(string Value, object data) { if (data == null) return; //cancel if data is a type - if(data.ToString() == data.GetType().Name) + if (data.ToString() == data.GetType().Name) return; ApplicationData.Current.LocalSettings.Values[Value] = data.ToString(); } - public void SaveSettingsAsColor(string Value, Color Color, AccentColors accentcolor = AccentColors.None) - { - ApplicationData.Current.LocalSettings.Values[Value] = - accentcolor != AccentColors.None ? ((int)accentcolor).ToString() : Color.ToString(); - } - public float GetSettingsAsFloat(string Value, float defaultvalue = 0) - { - return Convert.ToFloat(ApplicationData.Current.LocalSettings.Values[Value] as string, defaultvalue); - } - public string GetSettings(string Value) - { - return ApplicationData.Current.LocalSettings.Values[Value] as string; - } - public int GetSettingsAsInt(string Value, int defaultvalue = 0) - { - return ApplicationData.Current.LocalSettings.Values[Value] is string value - ? Convert.ToInt(value, defaultvalue) : defaultvalue; - } - public double GetSettingsAsDouble(string Value, double defaultvalue = 0) - { - return Convert.ToDouble(ApplicationData.Current.LocalSettings.Values[Value] as string, defaultvalue); - } - public bool GetSettingsAsBool(string Value, bool defaultvalue = false) + public static string GetSettings(string value, string defaultValue = "") { - return Convert.ToBoolean(ApplicationData.Current.LocalSettings.Values[Value] as string, defaultvalue); + return ApplicationData.Current.LocalSettings.Values[value] as string ?? defaultValue; } - public string GetSettingsAsString(string Value, string Default = "") + public static int GetSettingsAsInt(string value, int defaultValue = 0) { - return ApplicationData.Current.LocalSettings.Values[Value] is string val && val.Length != 0 ? val : Default; + return ConvertHelper.ToInt(ApplicationData.Current.LocalSettings.Values[value] as string, defaultValue); } - public Color GetSettingsAsColorWithDefault(string Value, Color Default) + public static bool GetSettingsAsBool(string value, bool defaultValue = false) { - if (ApplicationData.Current.LocalSettings.Values[Value] is string readColor) - { - if (readColor.Length != 0) - { - try - { - if (readColor.Contains("#")) - return (Color)XamlBindingHelper.ConvertValue(typeof(Color), readColor); - else if (readColor.Length < 3) - { - AccentColors clr = (AccentColors)Enum.Parse(typeof(AccentColors), readColor.Trim()); - if (clr == AccentColors.Dark2) - return DefaultValues.SystemAccentColorDark2; - else if (clr == AccentColors.Default) - return DefaultValues.SystemAccentColor; - else if (clr == AccentColors.Light2) - return DefaultValues.SystemAccentColorLight2; - else if (clr == AccentColors.Light1) - return DefaultValues.SystemAccentColorLight1; - else if (clr == AccentColors.Dark1) - return DefaultValues.SystemAccentColorDark1; - } - } - catch (Exception ex) - { - Debug.WriteLine("Exception in AppSettings --> GetSettingsAsColorWithDefault\n" + ex.Message); - return Default; - } - } - return Default; - } - else - { - return Default; - } + return ConvertHelper.ToBoolean(ApplicationData.Current.LocalSettings.Values[value] as string, defaultValue); } - public Color GetSettingsAsColor(string Value) + public static Color GetSettingsAsColor(string value, Color? defaultValue) { - try - { - if (ApplicationData.Current.LocalSettings.Values[Value] is string readColor && readColor.Length != 0) - { - if (readColor.Contains("#")) - { - return (Color)XamlBindingHelper.ConvertValue(typeof(Color), readColor); - } - else if (readColor == "0" || readColor == "1" || readColor == "2" || readColor == "3") - { - AccentColors clr = (AccentColors)Enum.Parse(typeof(AccentColors), readColor.Trim()); - if (clr == AccentColors.Dark2) - { - return DefaultValues.SystemAccentColorDark2; - } - else if (clr == AccentColors.Default) - { - return DefaultValues.SystemAccentColor; - } - else if (clr == AccentColors.Light2) - { - return DefaultValues.SystemAccentColorLight2; - } - else if (clr == AccentColors.Light1) - { - return DefaultValues.SystemAccentColorLight1; - } - else if (clr == AccentColors.Dark1) - { - return DefaultValues.SystemAccentColorDark1; - } - else - { - return Color.FromArgb(255, 0, 0, 0); - } - } - else - { - return Color.FromArgb(255, 0, 0, 0); - } - } - else - { - return Color.FromArgb(255, 0, 0, 0); - } - } - catch (Exception ex) + string readColor = ApplicationData.Current.LocalSettings.Values[value] as string; + + if (readColor.Contains("#")) { - Debug.WriteLine("Exception in AppSettings --> GetSettingsAsColor\n" + ex.Message); - return Color.FromArgb(255, 0, 0, 0); + return (Color)XamlBindingHelper.ConvertValue(typeof(Color), readColor); } - } - public void ClearSettings() - { - ApplicationData.Current.LocalSettings.Values.Clear(); + return defaultValue ?? Color.FromArgb(0, 0, 0, 0); } } -} \ No newline at end of file +} diff --git a/Fastedit/Settings/AppSettingsValues.cs b/Fastedit/Settings/AppSettingsValues.cs new file mode 100644 index 0000000..a7f2d25 --- /dev/null +++ b/Fastedit/Settings/AppSettingsValues.cs @@ -0,0 +1,30 @@ +namespace Fastedit.Settings +{ + public static class AppSettingsValues + { + public const string DesignLoaded = "DesignLoaded"; + public const string App_FirstStart = "FirstStart"; + public const string App_Version = "AppVersion"; + + public const string Settings_FontSize = "FontSize"; + public const string Settings_FontFamily = "FontFamily"; + public const string Settings_ShowLineHighlighter = "ShowLineHighlighter"; + public const string Settings_ShowLineNumbers = "ShowLineNumbers"; + public const string Settings_Syntaxhighlighting = "Syntaxhighlighting"; + + public const string Settings_NewTabTitle = "NewTabTitle"; + public const string Settings_NewTabExtension = "NewTabExtension"; + + public const string Settings_UseSpacesInsteadTabs = "UseSpacesInsteadTabs"; + public const string Settings_SpacesPerTab = "SpacesPerTab"; + + public const string Settings_ShowStatusbar = "ShowStatusbar"; + public const string Settings_ShowMenubar = "ShowMenubar"; + public const string Settings_Language = "Language"; + + public const string Settings_TabViewWidthMode = "TabWidthMode"; + + //Design + public const string Settings_DesignName = "CurrentDesign"; + } +} diff --git a/Fastedit/Settings/DefaultValues.cs b/Fastedit/Settings/DefaultValues.cs new file mode 100644 index 0000000..b5131bc --- /dev/null +++ b/Fastedit/Settings/DefaultValues.cs @@ -0,0 +1,32 @@ +using System.IO; +using System.Text; +using Windows.Storage; +using Windows.UI; + +namespace Fastedit.Settings +{ + public class DefaultValues + { + public static string NewTabTitle = "Untitled"; + public static string NewTabExtension = ".txt"; + public static Encoding Encoding = Encoding.UTF8; + public static bool FastLoadTabs = true; + public static string DatabasePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "Database"); + public static string DesignPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "Designs"); + public static string RecycleBinPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "Trash"); + public static string TemporaryFilesPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "Temp"); + public static int ZoomSteps = 5; + public static string FontFamily = "Consolas"; + public static int FontSize = 18; + public static bool ShowLineHighlighter = true; + public static bool ShowLinenumbers = true; + public static bool UseSpacesInsteadTabs = false; + public static bool SyntaxHighlighting = true; + public static bool ShowMenubar = true; + public static bool ShowStatusbar = true; + public static int NumberOfSpacesPerTab = 4; + public static string DefaultDesignName = "Design4.json"; + public static Color wrongInputColor = Color.FromArgb(255, 255, 0, 0); + public static Color correctInputColor = Color.FromArgb(255, 0, 255, 0); + } +} diff --git a/Fastedit/Settings/SettingsImportExport.cs b/Fastedit/Settings/SettingsImportExport.cs new file mode 100644 index 0000000..a6434fd --- /dev/null +++ b/Fastedit/Settings/SettingsImportExport.cs @@ -0,0 +1,56 @@ +using Fastedit.Storage; +using Fastedit.Tab; +using System; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using Windows.Storage; + +namespace Fastedit.Settings +{ + internal class SettingsImportExport + { + public static async Task Export() + { + var file = await SaveFileHelper.PickFile("settings.fasteditsettings", ".fasteditsettings", "Fastedit settings"); + if (file == null) + return false; + + FieldInfo[] fieldInfos = typeof(AppSettingsValues).GetFields(BindingFlags.Public | + BindingFlags.Static | BindingFlags.FlattenHierarchy); + + StringBuilder data = new StringBuilder(); + foreach (var item in fieldInfos.Where(fi => fi.IsLiteral && !fi.IsInitOnly)) + { + data.AppendLine(item.GetValue(null) + "=" + AppSettings.GetSettings(item.GetValue(null).ToString())); + } + + await FileIO.WriteTextAsync(file, data.ToString()); + return true; + } + + public static async Task Import() + { + var file = await OpenFileHelper.PickFile(".fasteditsettings"); + if (file == null) + return false; + + foreach (var line in await FileIO.ReadLinesAsync(file)) + { + if (line.Length > 0) + { + var splitted = line.Split("=", StringSplitOptions.RemoveEmptyEntries); + if (splitted.Length > 1) + { + AppSettings.SaveSettings(splitted[0], splitted[1]); + } + } + } + + //Apply the imported settings + TabPageHelper.mainPage.ApplySettings(); + return true; + } + } +} diff --git a/Fastedit/Settings/SettingsUpdater.cs b/Fastedit/Settings/SettingsUpdater.cs new file mode 100644 index 0000000..f1cedf2 --- /dev/null +++ b/Fastedit/Settings/SettingsUpdater.cs @@ -0,0 +1,160 @@ +using Fastedit.Controls; +using Fastedit.Helper; +using Fastedit.Tab; +using Fastedit.Views; +using Microsoft.UI.Xaml.Controls; +using System; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; +using Windows.UI.Xaml.Media; + +namespace Fastedit.Settings +{ + public class SettingsUpdater + { + private static double GetHeightWithVisibility(FrameworkElement control) + { + return control.Visibility == Visibility.Visible ? control.ActualHeight : 0; + } + private static void SetTabViewSettings(TabView tabView, FasteditDesign design) + { + (tabView.Resources["TabViewItemHeaderBackground"] as SolidColorBrush).Color = ConvertHelper.ToColor(design.UnselectedTabPageHeaderBackground); + (tabView.Resources["TabViewItemHeaderBackgroundSelected"] as SolidColorBrush).Color = ConvertHelper.ToColor(design.SelectedTabPageHeaderBackground); + (tabView.Resources["TabViewItemHeaderForeground"] as SolidColorBrush).Color = ConvertHelper.ToColor(design.UnSelectedTabPageHeaderTextColor); + (tabView.Resources["TabViewItemHeaderForegroundSelected"] as SolidColorBrush).Color = ConvertHelper.ToColor(design.SelectedTabPageHeaderTextColor); + + tabView.TabWidthMode = (TabViewWidthMode)Enum.Parse(typeof(TabViewWidthMode), AppSettings.GetSettings(AppSettingsValues.Settings_TabViewWidthMode, "0")); + } + private static TextControlBox.TextControlBoxDesign CreateTextboxDesign(FasteditDesign currentDesign) + { + return new TextControlBox.TextControlBoxDesign( + DesignHelper.CreateBackgroundBrush(ConvertHelper.ToColor(currentDesign.TextBoxBackground), currentDesign.TextboxBackgroundType), + ConvertHelper.ToColor(currentDesign.TextColor), + ConvertHelper.ToColor(currentDesign.SelectionColor), + ConvertHelper.ToColor(currentDesign.CursorColor), + ConvertHelper.ToColor(currentDesign.LineHighlighterBackground), + ConvertHelper.ToColor(currentDesign.LineNumberColor), + ConvertHelper.ToColor(currentDesign.LineNumberBackground), + ConvertHelper.ToColor(currentDesign.SearchHighlightColor) + ); + } + + public static void UpdateTab(TabPageItem tab, bool setMargin = true) + { + UpdateTabSettings(tab, CreateTextboxDesign(DesignHelper.CurrentDesign), DesignHelper.CurrentDesign.Theme, setMargin); + } + + private static void UpdateTabSettings(TabPageItem tab, TextControlBox.TextControlBoxDesign textboxDesign, ElementTheme theme, bool setMargin = true) + { + tab.textbox.Design = textboxDesign; + + tab.textbox.FontSize = AppSettings.GetSettingsAsInt(AppSettingsValues.Settings_FontSize, DefaultValues.FontSize); + tab.textbox.FontFamily = new FontFamily(AppSettings.GetSettings(AppSettingsValues.Settings_FontFamily, DefaultValues.FontFamily)); + + tab.textbox.ShowLineHighlighter = AppSettings.GetSettingsAsBool(AppSettingsValues.Settings_ShowLineHighlighter, DefaultValues.ShowLineHighlighter); + tab.textbox.ShowLineNumbers = AppSettings.GetSettingsAsBool(AppSettingsValues.Settings_ShowLineNumbers, DefaultValues.ShowLinenumbers); + + tab.textbox.SyntaxHighlighting = AppSettings.GetSettingsAsBool(AppSettingsValues.Settings_Syntaxhighlighting, DefaultValues.SyntaxHighlighting); + + //tab.textbox.UseSpacesInsteadTabs = AppSettings.GetSettingsAsBool(AppSettingsValues.Settings_UseSpacesInsteadTabs, DefaultValues.UseSpacesInsteadTabs); + //tab.textbox.NumberOfSpacesForTab = AppSettings.GetSettingsAsInt(AppSettingsValues.Settings_SpacesPerTab, DefaultValues.NumberOfSpacesPerTab); + tab.textbox.RequestedTheme = theme; + + if (setMargin) + tab.textbox.Margin = TabPageHelper.TabMargin; + } + private static void UpdateTabPages(TabView tabView, FasteditDesign currentDesign) + { + var textboxDesign = CreateTextboxDesign(currentDesign); + for (int i = 0; i < tabView.TabItems.Count; i++) + { + if (tabView.TabItems[i] is TabPageItem tab && tab != null) + { + UpdateTabSettings(tab, textboxDesign, currentDesign.Theme); + } + else if (SettingsTabPageHelper.IsSettingsPage(tabView.TabItems[i])) + { + DesignHelper.SetBackground(tabView.TabItems[i] as TabViewItem, ConvertHelper.ToColor(currentDesign.BackgroundColor), currentDesign.BackgroundType); + } + } + + //Load tabs or spaces + object tag; + if (!AppSettings.GetSettingsAsBool(AppSettingsValues.Settings_UseSpacesInsteadTabs, DefaultValues.UseSpacesInsteadTabs)) + tag = "-1"; + else + tag = AppSettings.GetSettingsAsInt(AppSettingsValues.Settings_SpacesPerTab, DefaultValues.NumberOfSpacesPerTab); + + TabPageHelper.TabsOrSpaces(tabView, tag); + } + private static void SetSettingsToStatusbar(Grid statusbar, FasteditDesign design) + { + statusbar.Background = DesignHelper.CreateBackgroundBrush(ConvertHelper.ToColor(design.StatusbarBackgroundColor), design.StatusbarBackgroundType); + var foreground = new SolidColorBrush(ConvertHelper.ToColor(design.StatusbarTextColor)); + for (int i = 0; i < statusbar.Children.Count; i++) + { + if (statusbar.Children[i] is StatusbarItem item) + { + item.Foreground = foreground; + } + } + + } + public static void SetMainPageSettings(Page mainPage, FasteditDesign currentDesign) + { + DesignHelper.SetBackground(mainPage, ConvertHelper.ToColor(currentDesign.BackgroundColor), currentDesign.BackgroundType); + } + public static void SetControlsVisibility(TabView tabView, Microsoft.UI.Xaml.Controls.MenuBar menuBar, Grid statusbar) + { + //do not apply -> controls will be visible in settings + if (SettingsTabPageHelper.SettingsSelected) + return; + + statusbar.Visibility = ConvertHelper.BoolToVisibility(AppSettings.GetSettingsAsBool(AppSettingsValues.Settings_ShowStatusbar, DefaultValues.ShowStatusbar)); + menuBar.Visibility = ConvertHelper.BoolToVisibility(AppSettings.GetSettingsAsBool(AppSettingsValues.Settings_ShowMenubar, DefaultValues.ShowMenubar)); + + TabPageHelper.TabMargin.Top = GetHeightWithVisibility(menuBar); + TabPageHelper.TabMargin.Bottom = GetHeightWithVisibility(statusbar); + + //Update tab margin: + for (int i = 0; i < tabView.TabItems.Count; i++) + { + if (tabView.TabItems[i] is TabPageItem tab) + { + tab.textbox.Margin = TabPageHelper.TabMargin; + } + } + } + + public static void UpdateSettings(MainPage mainPage, TabView tabView, Microsoft.UI.Xaml.Controls.MenuBar menuBar, Grid statusbar, FasteditDesign currentDesign) + { + //Load the desing from file + if (currentDesign == null) + DesignHelper.LoadDesign(); + + //update the design + currentDesign = DesignHelper.CurrentDesign; + + //Apply the theme: + ThemeHelper.CurrentTheme = currentDesign.Theme; + + //Controls + SetControlsVisibility(tabView, menuBar, statusbar); + + //TabPages + UpdateTabPages(tabView, currentDesign); + + //TabControl + SetTabViewSettings(tabView, currentDesign); + + //MainPage + SetMainPageSettings(mainPage, currentDesign); + + //Statusbar + SetSettingsToStatusbar(statusbar, currentDesign); + + //TabWindows (tabs as own windows): + TabWindowHelper.UpdateSettings(); + } + } +} diff --git a/Fastedit/Storage/FileExtensions.cs b/Fastedit/Storage/FileExtensions.cs new file mode 100644 index 0000000..060fad2 --- /dev/null +++ b/Fastedit/Storage/FileExtensions.cs @@ -0,0 +1,153 @@ +using System.Collections.Generic; +using System.Linq; + +namespace Fastedit.Storage +{ + public class FileExtensions + { + public static ExtensionItem FindByExtension(string extension) + { + var res = FileExtentionList.Where(x => x.HasExtension(extension)); + if (res.Count() > 0) + return res.ElementAt(0); + return null; + } + + public static List FileExtentionList = new List + { + new ExtensionItem() + { + Extension = { ".md", ".markdown", ".mdown", ".markdn" }, + ExtensionName = "Markdown", + ExtensionLongName = "Markdown" + }, + new ExtensionItem() + { + Extension = { ".json" }, + ExtensionName = "Json", + }, + new ExtensionItem() + { + Extension = { ".gcode", ".ngc", ".tap" }, + ExtensionName = "G-Code", + ExtensionLongName = "G-Code" + }, + new ExtensionItem() + { + Extension = { ".vb" }, + ExtensionName = "Visual Basic", + }, + new ExtensionItem() + { + Extension = { ".ino" }, + ExtensionName = "Arduino sketch", + }, + new ExtensionItem() + { + Extension = { ".php" }, + ExtensionName = "Hypertext preprocessor", + }, + new ExtensionItem() + { + Extension = { ".asm" }, + ExtensionName = "Assembly language", + }, + new ExtensionItem() + { + Extension = { ".kt" }, + ExtensionName = "Kotlin", + }, + new ExtensionItem() + { + Extension = { ".cs" }, + ExtensionName = "CSharp" + }, + new ExtensionItem() + { + Extension = { ".cpp", ".cxx", ".cc", ".hpp" }, + ExtensionName = "C++" + }, + new ExtensionItem() + { + Extension = { ".py", ".py3", ".pyt", ".rpy", ".pyw" }, + ExtensionName = "Python", + ExtensionLongName = "Python" + }, + new ExtensionItem() + { + Extension = { ".bat" }, + ExtensionName = "Batch", + ExtensionLongName = "Windows batch" + }, + new ExtensionItem() + { + Extension = { ".xaml" }, + ExtensionName = "Xaml", + ExtensionLongName = "Extensible Application Markup Language" + }, + new ExtensionItem() + { + Extension = { ".xml" }, + ExtensionName = "XML", + ExtensionLongName = "Extensible Markup Language" + }, + new ExtensionItem() + { + Extension = { ".html", ".htm", ".xhtml" }, + ExtensionName = "HTML", + ExtensionLongName = "Hypertext Markup Language" + }, + new ExtensionItem() + { + Extension = { ".txt", ".log" }, + ExtensionName = "Textfile", + ExtensionLongName = "Textfile" + }, + new ExtensionItem() + { + Extension = { ".reg" }, + ExtensionName = "Registration file", + ExtensionLongName = "Windows Registration file" + }, + new ExtensionItem() + { + Extension = { ".css" }, + ExtensionName = "Cascading Style Sheets", + ExtensionLongName = "Cascading Style Sheets" + }, + new ExtensionItem() + { + Extension = { ".java", ".jav", ".j" }, + ExtensionName = "Java", + ExtensionLongName = "Java" + }, + new ExtensionItem() + { + Extension = { ".ini", ".config", ".inf" }, + ExtensionName = "Configuration file", + ExtensionLongName = "Configuration file" + }, + new ExtensionItem() + { + Extension = { ".c", ".h" }, + ExtensionName = "C language", + }, + new ExtensionItem() + { + Extension = { ".js", }, + ExtensionName = "JavaScript", + } + }; + } + public class ExtensionItem + { + public bool HasExtension(string extension) + { + return Extension.Contains(extension); + } + + public List Extension = new List(); + public string ExtensionName { get; set; } + public string ExtensionLongName { get; set; } + } +} \ No newline at end of file diff --git a/Fastedit/Storage/OpenFileHelper.cs b/Fastedit/Storage/OpenFileHelper.cs new file mode 100644 index 0000000..06b9c23 --- /dev/null +++ b/Fastedit/Storage/OpenFileHelper.cs @@ -0,0 +1,172 @@ +using Fastedit.Dialogs; +using Fastedit.Helper; +using Fastedit.Settings; +using Fastedit.Tab; +using Microsoft.UI.Xaml.Controls; +using System; +using System.IO; +using System.Text; +using System.Threading.Tasks; +using Windows.Storage; +using Windows.Storage.AccessCache; + +namespace Fastedit.Storage +{ + public class OpenFileHelper + { + private static async Task<(string Text, Encoding encoding, bool Succed)> ReadTextFromFileAsync(StorageFile file, Encoding encoding = null) + { + try + { + if (file == null) + return ("", Encoding.Default, false); + + using (var stream = (await file.OpenReadAsync()).AsStreamForRead()) + { + //Detect the encoding: + using (var reader = new StreamReader(stream, true)) + { + byte[] buffer = new byte[stream.Length]; + stream.Read(buffer, 0, buffer.Length); + + if (encoding == null) //Encoding gets detected + { + encoding = EncodingHelper.DetectTextEncoding(buffer, out string text); + return (text, encoding, true); + } + else //Encoding is predefined + { + return (encoding.GetString(buffer, 0, buffer.Length), encoding, true); + } + } + } + } + catch (UnauthorizedAccessException) + { + InfoMessages.NoAccesToReadFile(); + } + catch (Exception ex) + { + InfoMessages.UnhandledException(ex.Message); + } + return ("", Encoding.Default, false); + } + + private static async Task DoOpenTab(TabPageItem tab, StorageFile file, bool load = true) + { + if (file != null) + { + var res = await ReadTextFromFileAsync(file); + if (res.Succed) + { + tab.DatabaseItem.FilePath = file.Path; + tab.DatabaseItem.FileName = file.Name; + try + { + tab.DatabaseItem.FileToken = StorageApplicationPermissions.FutureAccessList.Add(file); + } + catch (Exception ex) + { + InfoMessages.UnhandledException(ex.Message); + return false; + } + tab.Encoding = res.encoding; + + if (load) + tab.textbox.LoadText(res.Text); + + TabPageHelper.SelectCodeLanguageByFile(tab, file); + + tab.textbox.GoToLine(0); + tab.textbox.ScrollLineIntoView(0); + tab.DataIsLoaded = load; + tab.DatabaseItem.IsModified = false; + tab.SetHeader(file.Name); + + if (!load) + { + var folder = await StorageFolder.GetFolderFromPathAsync(DefaultValues.DatabasePath); + var newFile = await file.CopyAsync(folder); + await newFile.RenameAsync(tab.DatabaseItem.Identifier); + } + + return true; + } + } + return false; + } + public static async Task DoOpen(TabView tabView, StorageFile file, bool load = true) + { + var tab = TabPageHelper.AddNewTab(tabView, false); + if (!await DoOpenTab(tab, file, load)) + { + tabView.TabItems.Remove(tab); + return null; + } + + return tab; + } + public static async Task OpenFile(TabView tabView) + { + var picker = new Windows.Storage.Pickers.FileOpenPicker(); + picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; + picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.ComputerFolder; + picker.FileTypeFilter.Add("*"); + + bool res = true; + var files = await picker.PickMultipleFilesAsync(); + foreach (var file in files) + { + var tab = await DoOpen(tabView, file); + if (tab != null) + tabView.SelectedItem = tab; + else + res = false; + } + return res; + } + + public static async Task ReopenWithEncoding(TabPageItem tab, Encoding encoding) + { + //File has not been saved: + if (tab.DatabaseItem.FileToken.Length == 0) + return false; + + StorageFile file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(tab.DatabaseItem.FileToken); + + var res = await ReadTextFromFileAsync(file, encoding); + if (res.Succed) + { + tab.Encoding = res.encoding; + tab.textbox.LoadText(res.Text); + return true; + } + return false; + } + + public static async Task OpenFileForTab(TabPageItem tab) + { + var picker = new Windows.Storage.Pickers.FileOpenPicker(); + picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; + picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.ComputerFolder; + picker.FileTypeFilter.Add("*"); + + var file = await picker.PickSingleFileAsync(); + if (file == null) + return false; + + await DoOpenTab(tab, file); + return tab != null; + } + + public static async Task PickFile(string extension) + { + var picker = new Windows.Storage.Pickers.FileOpenPicker(); + picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; + picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.ComputerFolder; + picker.FileTypeFilter.Add(extension); + + return await picker.PickSingleFileAsync(); + } + } +} diff --git a/Fastedit/Storage/SaveFileHelper.cs b/Fastedit/Storage/SaveFileHelper.cs new file mode 100644 index 0000000..460ebcb --- /dev/null +++ b/Fastedit/Storage/SaveFileHelper.cs @@ -0,0 +1,156 @@ +using Fastedit.Dialogs; +using Fastedit.Settings; +using Fastedit.Tab; +using Microsoft.UI.Xaml.Controls; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Windows.Storage; +using Windows.Storage.AccessCache; + +namespace Fastedit.Storage +{ + public class SaveFileHelper + { + private static async Task WriteTextToFileAsync(StorageFile file, string text, Encoding encoding) + { + try + { + if (file == null) + return false; + + using (var stream = await file.OpenStreamForWriteAsync()) + { + using (var writer = new StreamWriter(stream, encoding)) + { + await writer.WriteAsync(text); + return true; + } + } + } + catch (IOException) + { + try + { + var bytestoWrite = encoding.GetBytes(text); + var buffer = encoding.GetPreamble().Concat(bytestoWrite).ToArray(); + await PathIO.WriteBytesAsync(file.Path, buffer); + return true; + } + catch + { + InfoMessages.NoAccesToSaveFile(); + } + } + catch (Exception ex) + { + InfoMessages.UnhandledException(ex.Message); + } + return false; + } + public static async Task Save(TabPageItem tab) + { + if (tab == null) + return false; + + //file was already saved + if (tab.DatabaseItem.FileToken.Length > 0) + { + StorageFile file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(tab.DatabaseItem.FileToken); + if (file == null) + return await SaveFileAs(tab); + else + { + bool result = await WriteTextToFileAsync(file, tab.textbox.GetText(), tab.Encoding); + if (result) + { + TabPageHelper.UpdateSaveStatus(tab, false, tab.DatabaseItem.FileToken, file); + } + return result; + } + } + else + { + return await SaveFileAs(tab); + } + } + public static async Task SaveFileAs(TabPageItem tab) + { + if (tab == null) + return false; + + var savePicker = new Windows.Storage.Pickers.FileSavePicker(); + savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.ComputerFolder; + + StorageFile OpenedFile = null; + if (tab.DatabaseItem.FileToken.Length > 0) + OpenedFile = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(tab.DatabaseItem.FileToken); + + try + { + //Add the extension of the current file + savePicker.FileTypeChoices.Add("Current extension", new List() { OpenedFile != null ? OpenedFile.FileType : Path.GetExtension(tab.DatabaseItem.FileName) }); + } + catch (ArgumentException) //not a valid file name: + { + } + for (int i = 0; i < FileExtensions.FileExtentionList.Count; i++) + { + var item = FileExtensions.FileExtentionList[i]; + savePicker.FileTypeChoices.TryAdd(item.ExtensionName, item.Extension); + } + savePicker.SuggestedFileName = OpenedFile != null ? OpenedFile.DisplayName : tab.DatabaseItem.FileName; + + + StorageFile file = await savePicker.PickSaveFileAsync(); + if (file != null) + { + CachedFileManager.DeferUpdates(file); + await WriteTextToFileAsync(file, tab.textbox.GetText(), tab.Encoding); + Windows.Storage.Provider.FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file); + + if (status == Windows.Storage.Provider.FileUpdateStatus.Complete) + { + string token = StorageApplicationPermissions.FutureAccessList.Add(file); + TabPageHelper.UpdateSaveStatus(tab, false, token, file); + return true; + } + } + return false; + } + + public async static Task DragFileToPath(TabPageItem tab, TabViewTabDragStartingEventArgs args) + { + try + { + if (!Directory.Exists(DefaultValues.TemporaryFilesPath)) + Directory.CreateDirectory(DefaultValues.TemporaryFilesPath); + + StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(DefaultValues.TemporaryFilesPath); + + StorageFile file = await folder.CreateFileAsync(tab.DatabaseItem.FileName, CreationCollisionOption.OpenIfExists); + await FileIO.WriteTextAsync(file, tab.textbox.GetText()); + + args.Data.SetStorageItems(new IStorageItem[] { file }); + return true; + } + catch (Exception ex) + { + InfoMessages.UnhandledException(ex.Message); + return false; + } + } + + public async static Task PickFile(string fileName, string extension, string extensionDisplayName) + { + var savePicker = new Windows.Storage.Pickers.FileSavePicker(); + savePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.ComputerFolder; + savePicker.FileTypeChoices.Add(extensionDisplayName, new List() { extension }); + + return await savePicker.PickSaveFileAsync(); + } + } +} diff --git a/Fastedit/Storage/TemporaryFilesHandler.cs b/Fastedit/Storage/TemporaryFilesHandler.cs new file mode 100644 index 0000000..7839d8b --- /dev/null +++ b/Fastedit/Storage/TemporaryFilesHandler.cs @@ -0,0 +1,46 @@ +using Fastedit.Helper; +using Fastedit.Settings; +using System; +using System.IO; +using System.Threading.Tasks; +using Windows.Storage; + +namespace Fastedit.Storage +{ + internal class TemporaryFilesHandler + { + public static async Task Clear() + { + try + { + if (!Directory.Exists(DefaultValues.TemporaryFilesPath)) + Directory.CreateDirectory(DefaultValues.TemporaryFilesPath); + + StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(DefaultValues.TemporaryFilesPath); + var files = await folder.GetFilesAsync(); + for (int i = 0; i < files.Count; i++) + { + if (files[i] == null) + return false; + await files[i].DeleteAsync(); + } + + //check if all have been deleted + var files_2 = await folder.GetFilesAsync(); + return files_2.Count == 0; + } + catch + { + return false; + } + } + + public static string GetSize() + { + if (!Directory.Exists(DefaultValues.TemporaryFilesPath)) + Directory.CreateDirectory(DefaultValues.TemporaryFilesPath); + + return SizeCalculationHelper.CalculateFolderSize(DefaultValues.TemporaryFilesPath); + } + } +} diff --git a/Fastedit/Strings/de-DE/Resources.resw b/Fastedit/Strings/de-DE/Resources.resw deleted file mode 100644 index 5d4302e..0000000 --- a/Fastedit/Strings/de-DE/Resources.resw +++ /dev/null @@ -1,1176 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Kontakt - - - Du kannst mich über Email kontaktieren: - - - Entwickelt von: - DOPPELPUNKT - - - Verwendete Nuget-Pakete - - - Bug melden / Feature vorschlagen - - - Version: - DOPPELPUNKT - - - Möchtest du die Änderungen speichern? - Ask save content - - - Möchtest du die Datei speichern? - - - Abbrechen - Cancel button content - - - Nicht speichern - Don't save button content - - - Die Datei ist nicht mehr auf deinem PC gespeichert, möchtest du sie speichern? - - - Speichern? - The dialog title - - - Speichern - Save button content - - - Haftungsausschluss - - - Dienst - - - bezieht sich auf die Anwendung. - - - Sie - - - bezeichnet die Person, die auf den Dienst zugreift, oder das Unternehmen oder eine andere juristische Person, in deren Namen diese Person auf den Dienst zugreift oder ihn nutzt, soweit zutreffend. - - - Anwendung - - - bezeichnet das vom Unternehmen bereitgestellte Softwareprogramm, das von Ihnen auf ein elektronisches Gerät namens Fastedit heruntergeladen wird. - - - Haftungsausschluss - - - Die im Dienst enthaltenen Informationen dienen nur zu allgemeinen Informationszwecken. - - - Das Unternehmen übernimmt keine Verantwortung für Fehler oder Auslassungen in den Inhalten des Dienstes. - - - In keinem Fall haftet das Unternehmen für besondere, direkte, indirekte, Folge- oder Nebenschäden oder Schäden jeglicher Art, sei es aus einer Vertragshandlung, Fahrlässigkeit oder einer anderen unerlaubten Handlung, die sich aus oder im Zusammenhang mit der Nutzung des Dienstes oder des Inhalts des Dienstes ergeben. Das Unternehmen behält sich das Recht vor, jederzeit ohne vorherige Ankündigung Ergänzungen, Löschungen oder Änderungen an den Inhalten des Dienstes vorzunehmen. Dieser Haftungsausschluss wurde mit Hilfe des - - - Letzte Aktualisierung 14.01.2022 - - - Disclaimer Templates erstellt. - - - Das Unternehmen garantiert nicht, dass der Dienst frei von Viren oder anderen schädlichen Komponenten ist. - - - Haftungsausschluss für externe Links - - - Der Dienst kann Links zu externen Websites enthalten, die nicht vom Unternehmen bereitgestellt oder gepflegt werden oder in irgendeiner Weise mit dem Unternehmen verbunden sind. - - - Bitte beachten Sie, dass das Unternehmen keine Garantie für die Richtigkeit, Relevanz, Aktualität oder Vollständigkeit der Informationen auf diesen externen Websites übernimmt. - - - Haftungsausschluss für Fehler und Auslassungen - - - Die vom Dienst bereitgestellten Informationen dienen nur der allgemeinen Orientierung in Angelegenheiten von Interesse. Selbst wenn das Unternehmen alle Vorsichtsmaßnahmen trifft, um sicherzustellen, dass der Inhalt des Dienstes sowohl aktuell als auch genau ist, können Fehler auftreten. Darüber hinaus kann es angesichts der sich ändernden Gesetze, Regeln und Vorschriften zu Verzögerungen, Auslassungen oder Ungenauigkeiten in denen im Service enthaltenen Informationen kommen. - - - Das Unternehmen ist nicht verantwortlich für Fehler, Auslassungen oder für die Ergebnisse, die durch die Verwendung dieser Informationen erzielt werden. - - - Haftungsausschluss für faire Nutzung - - - Das Unternehmen kann urheberrechtlich geschütztes Material verwenden, das nicht immer ausdrücklich vom Urheberrechtsinhaber genehmigt wurde. Das Unternehmen stellt solches Material für Kritik, Kommentare, Nachrichtenberichterstattung, Lehre, Wissenschaft oder Forschung zur Verfügung. - - - Interpretation und Definition - - - Das Unternehmen ist der Ansicht, dass dies eine "faire Nutzung" von urheberrechtlich geschütztem Material gemäß Abschnitt 107 des Urheberrechtsgesetzes der Vereinigten Staaten darstellt. - - - Wenn Sie urheberrechtlich geschütztes Material aus dem Dienst für Ihre eigenen Zwecke verwenden möchten, die über die faire Nutzung hinausgehen, müssen Sie die Erlaubnis des Urheberrechtsinhabers einholen. - - - Geäußerte Ansichten Haftungsausschluss - - - Der Dienst kann Ansichten und Meinungen enthalten, die denen der Autoren entsprechen und nicht unbedingt die offizielle Politik oder Position eines anderen Autors, einer Agentur, einer Organisation, eines Arbeitgebers oder eines Unternehmens, einschließlich des Unternehmens, widerspiegeln. - - - Kommentare, die von Benutzern veröffentlicht werden, liegen in ihrer alleinigen Verantwortung und die Benutzer übernehmen die volle Verantwortung, Haftung und Schuld für verleumdungen oder rechtsstreitigkeiten, die sich aus etwas ergeben, das in oder als direkte Folge von etwas in einem Kommentar geschrieben wurde. Das Unternehmen haftet nicht für Kommentare, die von Benutzern veröffentlicht werden, und behält sich das Recht vor, Kommentare aus irgendeinem Grund zu löschen. - - - Haftungsausschluss für keine Verantwortung - - - Die Informationen über den Dienst werden unter dem Verständnis bereitgestellt, dass das Unternehmen hierin nicht in der Erbringung von rechtlichen, buchhalterischen, steuerlichen oder anderen professionellen Ratschlägen und Dienstleistungen tätig ist. Als solches sollte es nicht als Ersatz für die Beratung mit professionellen Buchhaltungs-, Steuer-, Rechts- oder anderen kompetenten Beratern verwendet werden. - - - In keinem Fall haftet das Unternehmen für besondere, zufällige, indirekte oder Folgeschäden, die sich aus oder im Zusammenhang mit Ihrem Zugriff oder Ihrer Nutzung oder der Unfähigkeit, auf den Dienst zuzugreifen oder ihn zu nutzen, ergeben. - - - Haftungsausschluss "Nutzung auf eigene Gefahr" - - - Alle Informationen im Dienst werden "wie besehen" zur Verfügung gestellt, ohne Garantie für Vollständigkeit, Genauigkeit, Aktualität oder der Ergebnisse, die durch die Verwendung dieser Informationen erzielt werden, und ohne jegliche ausdrückliche oder stillschweigende Gewährleistung, einschließlich, aber nicht beschränkt auf Garantien der Leistung, Marktgängigkeit und Eignung für einen bestimmten Zweck. - - - Interpretation - - - Das Unternehmen haftet Ihnen oder anderen gegenüber nicht für Entscheidungen oder Maßnahmen, die im Vertrauen auf die vom Dienst bereitgestellten Informationen getroffen werden, oder für Folgeschäden, besondere oder ähnliche Schäden, selbst wenn auf die Möglichkeit solcher Schäden hingewiesen wurde. - - - Kontaktieren Sie uns - - - Wenn Sie Fragen zu diesem Haftungsausschluss haben, können Sie uns kontaktieren: - - - Die Wörter, von denen der Anfangsbuchstabe groß geschrieben wird, haben Bedeutungen, die unter den folgenden Bedingungen definiert sind. Die folgenden Definitionen haben die gleiche Bedeutung, unabhängig davon, ob sie im Singular oder im Plural erscheinen. - - - Definition - - - Für die Zwecke dieses Haftungsausschlusses: - - - Firma - - - (in diesem Haftungsausschluss entweder als "das Unternehmen", "wir", "uns" oder "unser" bezeichnet) bezieht sich auf Fastedit. - - - Kopieren - - - Ausschneiden - - - Kodierung - - - Datei Info - - - Teilen - - - Code formatieren - - - Gehe zu - - - Bearbeitung sperren - - - Neu - - - Öffnen - - - Einfügen - - - Papierkorb - - - Schritt vor - - - Ersetzen - - - Speichern - - - Speichern unter - - - Suchen - - - Alles auswählen - - - Einstellungen - - - Rechtschreibprüfung - - - Dialoge - - - Tab - - - Fenster - - - Erweitert - - - Dokument - - - Bearbeiten - - - Datei - - - Ansicht - - - Schritt zurück - - - Schließen - - - Vollbild - - - Markdown umschalten - - - Kompakter Modus - - - Umschließen mit - - - Zeilenumbruch - - - Vergrößern - - - Verkleinern - - - Abbrechen - - - Fertig - - - Kodierung: - DOPPELPUNKT - - - Konnte den temporär gespeicherten Tab nicht laden, warcheinlich wurde die Datei von deinem PC gelöscht - - - Konnte den Tab nicht schließen - - - Fehler beim erstellen des Tabs - - - Fehler beim öffnen der Datei - - - Bei der Umwandlung des Tabs ist ein fehler aufgetreten - - - Fehler - - - Beim Laden der Tabs ist ein Fehler aufgetreten - - - Konnte die Datei nicht öffnen - - - Fehler beim Versuch die Datenbank zu speichern - - - Abbrechen - - - Schließe trotzdem - - - Nochmal - - - Konnte nicht in die Datei schreiben - - - Datei konnte nicht gespeichert werden - - - Datenbank fehler - - - Zeichen: - DOPPELPUNKT - - - Kopieren - - - Erstelldatum: - DOPPELPUNKT - - - Endung: - DOPPELPUNKT - - - Datei Informationen - - - Name: - DOPPELPUNKT - - - Pfad: - DOPPELPUNKT - - - Größe auf Datenträger: - - - Zuletzt geändert: - DOPPELPUNKT - - - Ok - - - Wörter: - DOPPELPUNKT - - - Der angegebene Pfad ist ungültig - - - Ungültiger Pfad - - - Du hast keine Berechtigung, um diese Datei zu öffnen - - - Keine Berechtigung - - - Die Datei konnte nich gefunden werden - - - Datei nicht gefunden - - - Öffnet die Datei - - - View Changelog - - - Wilkommen zu Fastedit version - - - Beim öffnen des Dokuments in einem neuen Fenster ist ein Fehler aufgetreten - - - Fehler - - - wurde nicht gefunden - - - Aktualisiert die Kodierung, dies könnte einen Weile dauern - - - Bitte schließe alle geöffneten Instanzen von Fastedit - - - Schließen - - - Gehe zu Zeile - - - Zeile... - - - Suche - - - Suchen... - - - Ersetzen... - - - Ganzes Wort - - - Alles ersetzen - - - Gespeichert - - - Ungespeichert - - - Wörter - - - Durch die Nutzung der App Fastedit stimmen Sie unseren Richtlinien bezüglich der Erfassung, Verwendung und Offenlegung personenbezogener Daten zu, die in dieser Datenschutzerklärung dargelegt sind. - - - Wir sammeln, speichern, verwenden oder teilen keine persönlichen Daten oder sonstigen Informationen. - - - Wenn Sie dem Entwickler eine E-Mail für Support, Feedback oder anderes senden, werden die E-Mails mit E-Mail-Adressen zu Qualitätssicherungszwecken aufbewahrt. Die E-Mail-Adressen werden nur verwendet, um auf geäußertes Feedback, Support oder andere zu antworten, und werden niemals für Marketingzwecke verwendet. - - - Wir werden Ihre Daten nicht an Drittanbieter weitergeben, es sei denn, Sie stimmen ausdrücklich zu oder wenn dies gesetzlich vorgeschrieben ist. - - - Wenn Sie Fragen zu dieser Datenschutzerklärung haben, können Sie uns eine E-Mail senden. - - - Datenschutzerklärung - - - Erfassung personenbezogener Daten - - - E-Mail - - - Offenlegung personenbezogener Daten - - - Kontaktieren Sie uns - - - Abbrechen - - - Fertig - - - Benennen - - - Benennen / Umbenennen - - - Ausschneiden - - - Schriftart - - - Textbox Hintergrundfarbe - - - Schriftfarbe - - - Schriftgröße - - - Zeilennummern Hintergrundfarbe - - - Zeilennummern Schriftfarbe - - - Textauswahlfarbe - - - Stift im Editor - - - Wenn du einen Stift benutzt, kannst du direkt in das Textfeld schreiben - - - Editor: - - - Zeilennummern - - - Zeilennummern - - - Menü bei Auswahl - - - Zeigt ein Menü, mit Ausschneiden, Kopieren, Sucehn und Teilen button, wenn du einen Text auswählst - - - Du kannst das Design ändern lassen, wenn Windows das Thema wechselt. - - - App Hintergrund - - - Sprache - - - Thema - - - Steuerelemente anzeigen/ausschalten - - - Design für den Darkmode - - - Acryl Darstellung - - - Acryl Darstellung - - - Acryl-Darstellung lässt die Fensterhintergrundfarben durchscheinen, kann aber zu schlechterer Performance führen. Falls Acryl-Design aktiviert ist aber nicht funktioniert prüf ob es in Windows aktiviert wurde. - - - Info: Diese Funktion ist in der Beta und könnte bugs beinhalten - - - App: - DOPPELPUNKT - - - Titelleiste - - - Sprache - - - Design für den Lightmode - - - Dropdown-Menü anzeigen - - - Dropdown-Menü anzeigen - - - Nächster Tab-Button - - - Nächster Tab-Button - - - Vorheriger Tab-Button - - - Vorheriger Tab-Button - - - Thema - - - Dunkel - - - System Standard - - - Hell - - - Titelleisten Hintergrundfarbe - - - Benutze Mica als Hintergrund - - - Benutze Mica als Hintergrund - - - Mica ist ein System, welches den Hintergrund der app dem Desktophintergrund anpasst. Funktioniert aktuell aber erst bei Windows 11 - - - Neuen Tab erstellen - - - Letzte Tabs wiederherstellen - - - Hintergrundfarbe von ausgewähltem Tab - - - Hintergrundfarbe von nicht ausgewähltem Tab - - - Tab größe - - - Kompakt - - - Gleich - - - An Text anpasssen - - - Beim Start: - DOPPELPUNKT - - - Tab-Steuerelement: - - - Tab Symbol - - - Title eines neu erstellten Tabs - - - Dialog Deckkraft: - DOPPELPUNKT - - - Dialog Hintergrundfarbe: - DOPPELPUNKT - - - Dialog: - DOPPELPUNKT - - - Gehe zu Zeilen Dialog: - DOPPELPUNKT - - - Schließe Dialog nachdem zur Linie gegangen wurde - - - Ganze Linie auswählen - - - Automatisch Backup von Database erstellen nach: (0 = aus) - - - Dateien automatisch speichern nach: (0 = aus) - - - Backup erstellen - - - Backup exportieren - - - Einstellungen exportieren - - - Backup laden - - - Einstellungen laden - - - Letztes Backup laden - - - Ja, Lösche alle Dateien - - - Alle Dateien in dem Papierkorb werden gelöscht , möchtest du fortfahren? - - - Lösche Papierkorb - - - Datenbank backup: - DOPPELPUNKT - - - App-Einstellungen: - DOPPELPUNKT - - - Papierkorb - - - App Transparenz - - - Importieren - - - Neu - - - Du kannst das Design nicht ändern, weil die automatische Änderung aktiviert ist. Du kannst sie unter App -> Thema ausschalten - - - Designs sind deaktiviert - - - Eigene Designs - - - Statusleiste Hintergrundfarbe - - - Statusleiste Schriftfarbe - - - Kodierung - - - Kodierung - - - Zeilennummer - - - Zeilennummer - - - Umbenennen - - - Umbenennen - - - Speicher-Status - - - Speicher-Status - - - Aktiviere Farben - - - Aktiviere Farben - - - Wörterzahl - - - Wörterzahl - - - Zoom - - - Zoom - - - Items ein/ausblenden - - - Statusleiste - - - Schrift in Fett - - - Einstellungen anwenden - - - Akzentfarbe - - - Benutzerdefiniert - - - Standard - - - Schriftfarbe - - - Transparent - - - Aussehen: - DOPPELPUNKT - - - Allgemein: - DOPPELPUNKT - - - Über Fastedit - - - App - - - Änderungsliste - - - Daten - - - Designs - - - Dialog - - - Editor - - - Datenschutzerklärung - - - Tastenkürzel - - - Statusleiste - - - Tab-Steuerelement - - - Datei schließen - - - Kopieren - - - Neue Datei erstellen - - - Ausschneiden - - - Zeile duplizieren - - - Nächstes suchen - - - Vollbild - - - Gehe zu Zeile - - - Datei öffnen - - - Einstellungen öffnen - - - Einfügen - - - Schritt vor - - - Ersetzen - - - Datei speichern - - - Datei speichern unter - - - Nach unten scrollen - - - Nach oben scrollen - - - Suchen - - - Alles auswählen - - - Letzten Tab auswählen - - - Tab 1 - 8 auswählen - - - Schritt zurück - - - Text vergrößern - - - Text verkleinern - - - Spalte: - DOPPELPUNKT - - - Zeile: - DOPPELPUNKT - - - Zoom: - DOPPELPUNKT - - - Kodierung - - - Ok - - - Gehe zu Zeile: - DOPPELPUNKT - - - Umbenennen: - DOPPELPUNKT - - - Umbenennen - - - Speichern - - - Schließen - - - Alle Schließen - - - Alle außer diesem schließen - - - Schließe alle linken - - - Schließe alle rechten - - - Schließe alle ohne speichern - - - Datei Informationen - - - Sperren - - - In neuem Fenster öffnen - - - Speichern - - - Teilen - - - Entsperren - - - Kopieren - - - Ausschneiden - - - Suchen - - - Einfügen - - - Alles auswählen - - - Schritt zurück - - - Schließen - - - Links-Rechts / Oben-Unten umschalten - - - Um 90° drehen - - - Löschen - - - Exportieren - - - Umbenennen - - - Überschreiben - - - Gespeichert! - - - Zeilen: - - - Groß/Kleinschreibung - - - Bug melden | Feature vorschlagen - - - Andere - - \ No newline at end of file diff --git a/Fastedit/Strings/en-US/Resources.resw b/Fastedit/Strings/en-US/Resources.resw index 330be9f..be4e5a9 100644 --- a/Fastedit/Strings/en-US/Resources.resw +++ b/Fastedit/Strings/en-US/Resources.resw @@ -1,1108 +1,42 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Contact - - - You can contact us via email: - - - Developed by: - DOPPELPUNKT - - - Nuget-packages used - - - Report bug/submit feature - - - Version: - DOPPELPUNKT - - - Do you want save changes of - Ask save content - - - Do you want save file - - - Cancel - Cancel button content - - - Don't save - Don't save button content - - - The file was deleted from your PC, do you want save it? - - - Save? - The dialog title - - - Save - Save button content - - - Disclaimer - - - Service - - - refers to the Application. - - - You - - - means the individual accessing the Service, or the company, or other legal entity on behalf of which such individual is accessing or using the Service, as applicable. - - - Application - - - means the software program provided by the Company downloaded by You on any electronic device named Fastedit. - - - Disclaimer - - - The information contained on the Service is for general information purposes only. - - - The Company assumes no responsibility for errors or omissions in the contents of the Service. - - - In no event shall the Company be liable for any special, direct, indirect, consequential, or incidental damages or any damages whatsoever, whether in an action of contract, negligence or other tort, arising out of or in connection with the use of the Service or the contents of the Service. The Company reserves the right to make additions, deletions, or modifications to the contents on the Service at any time without prior notice. This Disclaimer has been created with the help of the - - - Last updated: January 14, 2022 - - - Disclaimer Template - - - The Company does not warrant that the Service is free of viruses or other harmful components. - - - External Links Disclaimer - - - The Service may contain links to external websites that are not provided or maintained by or in any way affiliated with the Company. - - - Please note that the Company does not guarantee the accuracy, relevance, timeliness, or completeness of any information on these external websites. - - - Errors and Omissions Disclaimer - - - The information given by the Service is for general guidance on matters of interest only. Even if the Company takes every precaution to insure that the content of the Service is both current and accurate, errors can occur. Plus, given the changing nature of laws, rules and regulations, there may be delays, omissions or inaccuracies in the information contained on the Service. - - - The Company is not responsible for any errors or omissions, or for the results obtained from the use of this information. - - - Fair Use Disclaimer - - - The Company may use copyrighted material which has not always been specifically authorized by the copyright owner. The Company is making such material available for criticism, comment, news reporting, teaching, scholarship, or research. - - - Interpretation and Definitions - - - The Company believes this constitutes a "fair use" of any such copyrighted material as provided for in section 107 of the United States Copyright law. - - - If You wish to use copyrighted material from the Service for your own purposes that go beyond fair use, You must obtain permission from the copyright owner. - - - Views Expressed Disclaimer - - - The Service may contain views and opinions which are those of the authors and do not necessarily reflect the official policy or position of any other author, agency, organization, employer or company, including the Company. - - - Comments published by users are their sole responsibility and the users will take full responsibility, liability and blame for any libel or litigation that results from something written in or as a direct result of something written in a comment. The Company is not liable for any comment published by users and reserves the right to delete any comment for any reason whatsoever. - - - No Responsibility Disclaimer - - - The information on the Service is provided with the understanding that the Company is not herein engaged in rendering legal, accounting, tax, or other professional advice and services. As such, it should not be used as a substitute for consultation with professional accounting, tax, legal or other competent advisers. - - - In no event shall the Company or its suppliers be liable for any special, incidental, indirect, or consequential damages whatsoever arising out of or in connection with your access or use or inability to access or use the Service. - - - "Use at Your Own Risk" Disclaimer - - - All information in the Service is provided "as is", with no guarantee of completeness, accuracy, timeliness or of the results obtained from the use of this information, and without warranty of any kind, express or implied, including, but not limited to warranties of performance, merchantability and fitness for a particular purpose. - - - Interpretation - - - The Company will not be liable to You or anyone else for any decision made or action taken in reliance on the information given by the Service or for any consequential, special or similar damages, even if advised of the possibility of such damages. - - - Contact Us - - - If you have any questions about this Disclaimer, You can contact Us: - - - The words of which the initial letter is capitalized have meanings defined under the following conditions. The following definitions shall have the same meaning regardless of whether they appear in singular or in plural. - - - Definitions - - - For the purposes of this Disclaimer: - - - Company - - - (referred to as either "the Company", "We", "Us" or "Our" in this Disclaimer) refers to Fastedit. - - - Copy - - - Cut - - - Encoding - - - File info - - - Share - - - Format code - - - Go to - - - Lock editing - - - New - - - Open - - - Paste - - - Recycle bin - - - Redo - - - Replace - - - Save - - - Save as - - - Search - - - Select all - - - Settings - - - Spellchecking - - - Dialogs - - - Tab - - - Window - - - Advanced - - - Document - - - Edit - - - File - - - View - - - Undo - - - Close - - - Fullscreen - - - Toggle Markdown - - - Minimode - - - Surround with - - - Wordwrap - - - Zoom in - - - Zoom out - - - Cancel - - - Done - - - Encoding: - DOPPELPUNKT - - - Couldn't load temporary saved tab, maybe the file was deletet from your pc? - - - Couldn't close tab! - - - Error while creating new tab! - - - Error occured while opening dragged file - - - There was an error, while getting current tab - - - Error - - - Error occured while trying to load tabs - - - Couldn't open file - - - Error occured while saving database - - - Close - - - Close anyway - - - Retry - - - Couldn't write to file! - - - File couldn't be saved: - DOPPELPUNKT - - - Database error - - - Characters: - DOPPELPUNKT - - - Copy - - - Created: - DOPPELPUNKT - - - Extension: - DOPPELPUNKT - - - Fileinfo - - - Name: - DOPPELPUNKT - - - Path: - DOPPELPUNKT - - - Size on disk: - - - Last modified: - DOPPELPUNKT - - - Ok - - - Words: - DOPPELPUNKT - - - The specified path is invalid - - - Invalid path - - - You do not have access to open this file - - - No access - - - The file could not be found - - - File not found - - - Opening file - - - View Changelog - - - Welcome to Fastedit version - - - There was an error, while trying to open this document in a new window - - - New Window error - - - was not found - - - Updating encoding, this might take some time - - - Please close all instances of Fastedit - - - Close - - - Go to line - - - Line... - - - Search - - - Find... - - - Replace... - - - Whole word - - - Replace all - - - Saved - - - Unsaved - - - Words - - - By using the app Fastedit you are consenting to our policies regarding the collection, use and disclosure of personal information set out in this privacy policy. - - - We do not collect, store, use or share any information, personal or otherwise. - - - If you email the developer for support or other feedback, the emails with email addresses will be retained for quality assurance purposes. The email addresses will be used only to reply to the concerns or suggestions raised and will never be used for any marketing purpose. - - - We will not disclose your information to any third party except if you expressly consent or where required by law. - - - If you have any questions regarding this privacy policy, you can email - - - Privacy Policy - - - Collection of Personal Information - - - Email - - - Disclosure of Personal Information - - - Contacting Us - - - Cancel - - - Done - - - Name... - - - Name/Rename - - - Cut - - - Font - - - Textbox backgroundcolor - - - Fontcolor - - - Fontsize - - - Linenumber backgroundcolor - - - Linenumber foregroundcolor - - - Text selectioncolor - - - Handwriting in Editor - - - When using a pen you can directly write into the textbox - - - Editor: - - - Linenumbers: - DOPPELPUNKT - - - Linenumbers - - - Show selection-flyout - - - Shows a flyout with Cut, Copy, Find and Share button, when you select a text - - - You can automatically change the design if Windows changes the theme - - - App background - - - Language - - - Theme - - - Show/hide controls - - - Theme for Darkmode - - - Acrylic design - - - Acrylic design - - - Acrylic lets the window to be translucent. But it could lead to poorer performance; When acrylic is enabled, but doesn't work check your windows settings to have acrylic enabled. - - - Note: This feature is in Beta and could contain bugs - - - App: - DOPPELPUNKT - - - Titlebar - - - Language - - - Theme for Lightmode - - - Show dropdownmenu - - - Show dropdownmenu - - - Next tab-button - - - Next tab-button - - - Previous tab-button - - - Previous tab-button - - - Theme - - - Dark - - - System default - - - Light - - - Titlebar backgroundcolor - - - Use Mica as background - - - Use Mica as background - - - Mica is a system, which uses your desktop wallpaper as the app background. It is currently only available for windows 11 - - - Create a new tab - - - Recover recent tabs - - - Selected tabcolor - - - Titlebar backgroundcolor - - - Unselected tabcolor - - - Tab size - - - Compact - - - Equal - - - Size to content - - - On start: - DOPPELPUNKT - - - Tabcontrol: - - - TabIcon - - - New tab title - - - Dialog opacity: - DOPPELPUNKT - - - Dialog backgroundcolor - - - Dialogs: - - - Go to line dialog - - - Hide dialog after going to line - - - Select the whole line - - - Automatically backup database after: (0 = off) - - - Automatically save files after: (0 = off) - - - Backup now - - - Export backup - - - Export settings - - - Import backup - - - Import settings - - - Load last backup - - - Yes, delete all files - - - All files in the recyclebin will be deleted, do you want to continue? - - - Clear recyclebin - - - Database backup: - DOPPELPUNKT - - - App-settings: - - - Recyclebin - - - App transparency - - - Import - - - New - - - You can not change the Design because the automatic designchange is activated. To deactivate go to App -> Theme - - - Designs are disabled - - - Custom designs: - DOPPELPUNKT - - - Statusbar background - - - Statusbar foreground - - - Encoding - - - Encoding - - - Linenumber - - - Linenumber - - - Rename - - - Rename - - - Savestatus - - - Savestatus - - - Enable colors - - - Enable colors - - - Wordcount - - - Wordcount - - - Zoom - - - Zoom - - - Show/hide items: - DOPPELPUNKT - - - Statusbar - - - Bold font - - - Apply Settings - - - Accentcolor - - - Custom - - - Default - - - Fontcolor - - - Transparent - - - Appearance: - DOPPELPUNKT - - - General: - DOPPELPUNKT - - - About Fastedit - - - App - - - Changelog - - - Data - - - Designs - - - Dialogs - - - Editor - - - Privacy Policy - - - Shortcuts - - - Statusbar - - - Tabcontrol - - - Column: - DOPPELPUNKT - - - Line: - DOPPELPUNKT - - - Zoom: - DOPPELPUNKT - - - Encoding: - DOPPELPUNKT - - - Ok - - - Go to line: - DOPPELPUNKT - - - Rename: - DOPPELPUNKT - - - Rename - - - Save - - - Close - - - Close all - - - Close all but this - - - Close all left - - - Close all right - - - Close all without save - - - Info - - - Lock - - - Open in new window - - - Save - - - Share - - - Unlock - - - Copy - - - Cut - - - Find - - - Paste - - - Select all - - - Undo - - - Close - - - Toggle Left-Right / Top-Bottom - - - Rotate 90° - - - Delete - - - Export - - - Rename - - - Overwrite - - - Saved! - - - Lines: - - - Match case - - - Report bug | submit feature - - - Other - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 1.3 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3500.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + \ No newline at end of file diff --git a/Fastedit/Tab/AllTabsFlyout.cs b/Fastedit/Tab/AllTabsFlyout.cs new file mode 100644 index 0000000..bd97264 --- /dev/null +++ b/Fastedit/Tab/AllTabsFlyout.cs @@ -0,0 +1,97 @@ +using Microsoft.UI.Xaml.Controls; +using System; +using System.Diagnostics; +using System.Linq; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; + +namespace Fastedit.Tab +{ + public class AllTabsFlyout + { + private static string typedString = ""; + private static DispatcherTimer timer; + + public static void UpdateFlyout(TabView tabView, ListView listView) + { + //remove items that are not getting used + while (listView.Items.Count > tabView.TabItems.Count) + { + listView.Items.RemoveAt(listView.Items.Count - 1); + } + + //only update the names on same length + if (listView.Items.Count == tabView.TabItems.Count) + { + for (int i = 0; i < tabView.TabItems.Count; i++) + { + if (tabView.TabItems[i] is TabPageItem tab && listView.Items[i] is TabFlyoutItem tabFlyoutItem) + { + tabFlyoutItem.Tab = tab; + } + } + } + else if (listView.Items.Count < tabView.TabItems.Count) + { + //replace all possible ones + for (int i = 0; i < listView.Items.Count; i++) + { + if (tabView.TabItems[i] is TabPageItem tab && listView.Items[i] is TabFlyoutItem tabFlyoutItem) + { + tabFlyoutItem.Tab = tab; + } + } + + //create new ones + for (int i = listView.Items.Count; i < tabView.TabItems.Count; i++) + { + if (tabView.TabItems[i] is TabPageItem tab) + { + listView.Items.Add(new TabFlyoutItem + { + Tab = tab + }); + } + } + } + } + //type to search + public static void Flyout_CharacterReceived(char character, ListView listView) + { + if (timer == null) + { + timer = new DispatcherTimer(); + timer.Interval = new TimeSpan(0, 0, 0, 0, 800); + timer.Start(); + timer.Tick += Timer_Tick; + } + + if (!timer.IsEnabled) + timer.Start(); + typedString += character; + + Debug.WriteLine(typedString); + + var matches = listView.Items.Where(e => (e as TabFlyoutItem).Matches(typedString)); + if (matches.Count() > 0) + { + //set the tag to NOT null so in the event it can be identified to not select any tab + listView.Tag = ""; + listView.SelectedItem = matches.First(); + } + } + + private static void Timer_Tick(object sender, object e) + { + timer.Stop(); + typedString = ""; + } + } + + public class TabFlyoutItem + { + public bool Matches(string FileName) => Tab.DatabaseItem.FileName.Contains(FileName, StringComparison.OrdinalIgnoreCase); + + public TabPageItem Tab { get; set; } + } +} diff --git a/Fastedit/Tab/EditActions.cs b/Fastedit/Tab/EditActions.cs new file mode 100644 index 0000000..0f71473 --- /dev/null +++ b/Fastedit/Tab/EditActions.cs @@ -0,0 +1,79 @@ +using Fastedit.Settings; + +namespace Fastedit.Tab +{ + public class EditActions + { + public static void Copy(TabPageItem tab) + { + if (tab == null) + return; + + tab.textbox.Copy(); + } + public static void Paste(TabPageItem tab) + { + if (tab == null) + return; + + tab.textbox.Paste(); + } + public static void Cut(TabPageItem tab) + { + if (tab == null) + return; + + tab.textbox.Cut(); + } + public static void SelectAll(TabPageItem tab) + { + if (tab == null) + return; + tab.textbox.SelectAll(); + } + public static void Undo(TabPageItem tab) + { + if (tab == null) + return; + + tab.textbox.Undo(); + } + public static void Redo(TabPageItem tab) + { + if (tab == null) + return; + + tab.textbox.Redo(); + } + public static void DuplicateLine(TabPageItem tab) + { + if (tab == null) + return; + + tab.textbox.DuplicateLine(tab.textbox.CursorPosition.LineNumber); + } + public static void ZoomIn(TabPageItem tab) + { + if (tab == null) + return; + tab.textbox.ZoomFactor += DefaultValues.ZoomSteps; + } + public static void ZoomOut(TabPageItem tab) + { + if (tab == null) + return; + + tab.textbox.ZoomFactor -= DefaultValues.ZoomSteps; + } + + public static void GoToLine(TabPageItem tab, int line) + { + if (tab == null) + return; + + tab.textbox.GoToLine(line); + tab.textbox.ScrollLineIntoView(line); + tab.textbox.Focus(Windows.UI.Xaml.FocusState.Programmatic); + } + } +} diff --git a/Fastedit/Tab/TabDatabase.cs b/Fastedit/Tab/TabDatabase.cs new file mode 100644 index 0000000..4763e3a --- /dev/null +++ b/Fastedit/Tab/TabDatabase.cs @@ -0,0 +1,162 @@ +using Fastedit.Settings; +using Microsoft.UI.Xaml.Controls; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Text; +using System.Threading.Tasks; +using Windows.Storage; + +namespace Fastedit.Tab +{ + public class TabDatabase + { + string DatabaseName = "database.db"; + + //Migrate the old database to the new one: + public static TabPageItem[] CheckOlddatabase(TabView tabView) + { + string path = Path.Combine(DefaultValues.DatabasePath, "Tabs.tdb"); + if (File.Exists(path)) + { + var lines = File.ReadAllLines(path); + TabPageItem[] newItems = new TabPageItem[lines.Length]; + for (int i = 0; i < lines.Length; i++) + { + try + { + var oldItem = JsonConvert.DeserializeObject(lines[i]); + var resultItem = new TabItemDatabaseItem + { + FileToken = oldItem.TabToken, + FileName = oldItem.TabHeader, + IsModified = oldItem.TabModified, + FilePath = oldItem.TabPath, + Identifier = oldItem.TabName, + ZoomFactor = (int)oldItem.ZoomFactor, + SelectedIndex = oldItem.CurrentSelectedTabIndex, + }; + + newItems[i] = new TabPageItem(tabView) + { + DatabaseItem = resultItem, + }; + } + catch + { + Debug.WriteLine("Database migration -> item parse exception"); + } + } + File.Delete(path); + return newItems; + } + + return null; + } + + public void SaveData(IList TabItems, int SelectedIndex) + { + StringBuilder databaseBuilder = new StringBuilder(); + for (int i = 0; i < TabItems.Count; i++) + { + if (TabItems[i] is TabPageItem tab) + { + tab.DatabaseItem.SelectedIndex = SelectedIndex; + databaseBuilder.AppendLine(JsonConvert.SerializeObject(tab.DatabaseItem)); + } + } + + string path = Path.Combine(DefaultValues.DatabasePath, DatabaseName); + if (!File.Exists(path)) + { + Directory.CreateDirectory(DefaultValues.DatabasePath); + } + + Debug.WriteLine("Saving database..."); + File.WriteAllText(path, databaseBuilder.ToString()); + Debug.WriteLine("Database saved"); + } + public IEnumerable LoadData(TabView tabView) + { + string databaseContent = ""; + string path = Path.Combine(DefaultValues.DatabasePath, DatabaseName); + + if (File.Exists(path)) + databaseContent = File.ReadAllText(path); + + var lines = databaseContent.Split("\n", StringSplitOptions.RemoveEmptyEntries); + + for (int i = 0; i < lines.Length; i++) + { + yield return new TabPageItem(tabView) + { + DatabaseItem = JsonConvert.DeserializeObject(lines[i]), + }; + } + } + + public static async Task SaveTempFile(StorageFolder folder, TabPageItem tab) + { + Debug.WriteLine("SaveTempFile: " + tab.DatabaseItem.FileName); + var file = await folder.CreateFileAsync(tab.DatabaseItem.Identifier, CreationCollisionOption.OpenIfExists); + await FileIO.WriteTextAsync(file, tab.textbox.GetText()); + } + public static void DeleteTempFile(TabPageItem tab) + { + string path = Path.Combine(DefaultValues.DatabasePath, tab.DatabaseItem.Identifier); + if (File.Exists(path)) + File.Delete(path); + } + public static async Task ReadTempFile(TabPageItem tab) + { + string path = Path.Combine(DefaultValues.DatabasePath, tab.DatabaseItem.Identifier); + if (File.Exists(path)) + { + StorageFile file = await StorageFile.GetFileFromPathAsync(path); + return await FileIO.ReadTextAsync(file); + } + return ""; + } + } + public class TabItemDatabaseItem + { + public TabItemDatabaseItem() { } + public TabItemDatabaseItem(TabItemDatabaseItem item) + { + this.IsModified = item.IsModified; + this.ZoomFactor = item.ZoomFactor; + this.SelectedIndex = item.SelectedIndex; + this.Identifier = item.Identifier; + this.CodeLanguage = item.CodeLanguage; + this.FileName = item.FileName; + this.FilePath = item.FilePath; + this.FileToken = item.FileToken; + this.SaveMode = item.SaveMode; + this.Encoding = item.Encoding; + } + public bool IsModified { get; set; } + public string FilePath { get; set; } + public string FileName { get; set; } + public string Identifier { get; set; } + public int SelectedIndex { get; set; } + public int SaveMode { get; set; } + public string FileToken { get; set; } + public int ZoomFactor { get; set; } + public string CodeLanguage { get; set; } + public int Encoding { get; set; } + + public bool HasOwnWindow { get; set; } + } + public class OldDBItem + { + public string TabName { get; set; } + public bool TabModified { get; set; } + public string TabHeader { get; set; } + public string TabToken { get; set; } + public string TabPath { get; set; } + public double ZoomFactor { get; set; } + public int CurrentSelectedTabIndex { get; set; } + } +} diff --git a/Fastedit/Tab/TabFlyout.cs b/Fastedit/Tab/TabFlyout.cs new file mode 100644 index 0000000..7b7f9bd --- /dev/null +++ b/Fastedit/Tab/TabFlyout.cs @@ -0,0 +1,109 @@ +using Fastedit.Dialogs; +using Fastedit.Helper; +using Fastedit.Storage; +using Microsoft.UI.Xaml.Controls; +using Windows.System; +using Windows.UI.Xaml.Controls; +using Windows.UI.Xaml.Input; + +namespace Fastedit.Tab +{ + public class TabFlyout + { + public static MenuFlyout CreateFlyout(TabPageItem tab, TabView tabView) + { + var flyout = new MenuFlyout(); + flyout.Items.Add(CreateItem(tab, tabView, "Close", "\uE8BB", TabPageFlyoutItem.Close, VirtualKeyModifiers.Control, VirtualKey.W)); + flyout.Items.Add(new MenuFlyoutSeparator()); + flyout.Items.Add(CreateItem(tab, tabView, "Info", "\uE946", TabPageFlyoutItem.FileInfo, VirtualKeyModifiers.Control, VirtualKey.J)); + flyout.Items.Add(CreateItem(tab, tabView, "Share", Symbol.Share, TabPageFlyoutItem.Share)); + flyout.Items.Add(CreateItem(tab, tabView, "Save", Symbol.Save, TabPageFlyoutItem.Save, VirtualKeyModifiers.Control, VirtualKey.S)); + + return flyout; + } + private static MenuFlyoutItem CreateItem(TabPageItem tab, TabView tabView, string Text, Symbol symbol, TabPageFlyoutItem type, VirtualKeyModifiers modifier = VirtualKeyModifiers.None, VirtualKey key = VirtualKey.None) + { + var item = CreateItem(tab, tabView, Text, type); + item.Icon = new SymbolIcon { Symbol = symbol }; + + //prevent adding a keyboard accelerator + if (key == VirtualKey.None) + return item; + + item.KeyboardAccelerators.Add(new KeyboardAccelerator + { + Key = key, + Modifiers = modifier, + IsEnabled = false + }); + + return item; + } + private static MenuFlyoutItem CreateItem(TabPageItem tab, TabView tabView, string Text, string glyph, TabPageFlyoutItem type, VirtualKeyModifiers modifier, VirtualKey key = VirtualKey.None) + { + var item = CreateItem(tab, tabView, Text, type); + item.Icon = new FontIcon { FontFamily = new Windows.UI.Xaml.Media.FontFamily("Segoe MDL2 Assets"), Glyph = glyph }; + + //prevent adding a keyboard accelerator + if (key == VirtualKey.None) + return item; + + item.KeyboardAccelerators.Add(new KeyboardAccelerator + { + Key = key, + Modifiers = modifier, + IsEnabled = false + }); + return item; + } + + private static MenuFlyoutItem CreateItem(TabPageItem tab, TabView tabView, string Text, TabPageFlyoutItem type) + { + var item = new MenuFlyoutItem + { + Text = Text, + Tag = new TabFlyoutItemData(tab, tabView, type), + }; + item.Click += Item_Click; + return item; + } + + private static async void Item_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) + { + if (sender is MenuFlyoutItem item && item.Tag is TabFlyoutItemData data) + { + switch (data.Item) + { + case TabPageFlyoutItem.Save: + await SaveFileHelper.Save(data.Tab); + break; + case TabPageFlyoutItem.Close: + await TabPageHelper.CloseTab(data.TabView, data.Tab); + break; + case TabPageFlyoutItem.FileInfo: + await FileInfoDialog.Show(data.Tab); + break; + case TabPageFlyoutItem.Share: + ShareFileHelper.ShowShareUI(data.Tab); + break; + } + } + } + } + public enum TabPageFlyoutItem + { + Save, Close, Share, FileInfo + } + public class TabFlyoutItemData + { + public TabFlyoutItemData(TabPageItem tab, TabView tabView, TabPageFlyoutItem item) + { + this.Item = item; + this.Tab = tab; + this.TabView = tabView; + } + public TabPageFlyoutItem Item { get; set; } + public TabPageItem Tab { get; set; } + public TabView TabView { get; set; } + } +} diff --git a/Fastedit/Tab/TabPageHelper.cs b/Fastedit/Tab/TabPageHelper.cs new file mode 100644 index 0000000..9e36672 --- /dev/null +++ b/Fastedit/Tab/TabPageHelper.cs @@ -0,0 +1,366 @@ +using Fastedit.Dialogs; +using Fastedit.Helper; +using Fastedit.Settings; +using Fastedit.Storage; +using Microsoft.UI.Xaml.Controls; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Windows.Storage; +using Windows.UI.Xaml; + +namespace Fastedit.Tab +{ + public static class TabPageHelper + { + public static MainPage mainPage = null; + public static Thickness TabMargin = new Thickness(0); + + public static TextControlBox.TextControlBox CreateTextBox() + { + var textbox = new TextControlBox.TextControlBox + { + HorizontalAlignment = HorizontalAlignment.Stretch, + VerticalAlignment = VerticalAlignment.Stretch, + Margin = TabMargin + }; + textbox.TextChanged += Textbox_TextChanged; + textbox.ZoomChanged += Textbox_ZoomChanged; + textbox.SelectionChanged += Textbox_SelectionChanged; + return textbox; + } + + //textbox events: + private static void Textbox_SelectionChanged(TextControlBox.TextControlBox sender, TextControlBox.Text.SelectionChangedEventHandler args) + { + mainPage.UpdateStatubar(); + } + private static void Textbox_ZoomChanged(TextControlBox.TextControlBox sender, int zoomFactor) + { + //apply the zoomfactor to the databaseitem + if (sender.Tag is TabPageItem tab) + { + tab.DatabaseItem.ZoomFactor = zoomFactor; + mainPage.UpdateStatubar(); + } + } + private static void Textbox_TextChanged(TextControlBox.TextControlBox sender) + { + if (sender.Tag is TabPageItem tab) + { + if (!tab.DatabaseItem.IsModified) + { + tab.DatabaseItem.IsModified = true; + tab.UpdateHeader(); + } + } + } + + /// + /// Check and load the tab if it has not loaded the text from the file into the textbox + /// + /// + /// + /// + public static async Task LoadUnloadedTab(TabPageItem tab, ProgressWindowItem progressWindow = null) + { + if (!tab.DataIsLoaded && tab != null) + { + progressWindow?.ShowProgress(); + progressWindow?.SetText("Loading file " + tab.DatabaseItem.FileName + "..."); + tab.textbox.LoadText(await TabDatabase.ReadTempFile(tab)); + progressWindow?.HideProgress(); + tab.DataIsLoaded = true; + } + } + public static TabPageItem AddNewTab(TabView tabView, bool Select) + { + var tab = new TabPageItem(tabView); + tab.SetHeader(GenerateUniqueHeader(tabView)); + tab.DatabaseItem.Identifier = GenerateUniqueIdentifier(tabView); + tab.DataIsLoaded = true; + tabView.TabItems.Add(tab); + + SettingsUpdater.UpdateTab(tab); + + if (Select) + tabView.SelectedItem = tab; + return tab; + } + public static async Task LoadTabDatabase(TabView tabView, TabDatabase tabdatabase) + { + IEnumerable tabData; + var res = TabDatabase.CheckOlddatabase(tabView); + if (res != null) + tabData = res; + else + { + tabData = tabdatabase.LoadData(tabView); + if (tabData.Count() == 0) + { + AddNewTab(tabView, true); + return; + } + } + + int currentCount = 0; + using (var sequence = tabData.GetEnumerator()) + { + while (sequence.MoveNext()) + { + currentCount++; + var tab = sequence.Current; + //Either load all tabs or only the selected + if (tab.DatabaseItem.HasOwnWindow || + currentCount == tab.DatabaseItem.SelectedIndex || + !DefaultValues.FastLoadTabs) + { + tab.textbox.LoadText(await TabDatabase.ReadTempFile(tab)); + tab.Encoding = EncodingHelper.GetEncodingByIndex(tab.DatabaseItem.Encoding); + tab.DataIsLoaded = true; + } + + //Show tab in his own window or add it to the tabView: + if (tab.DatabaseItem.HasOwnWindow) + await TabWindowHelper.ShowInNewWindow(tabView, tab); + else + tabView.TabItems.Add(tab); + } + + tabView.SelectedIndex = -1; + await Task.Delay(5); //textbox does not load without the delay + int selectingIndex = tabData.ElementAt(0).DatabaseItem.SelectedIndex; + tabView.SelectedIndex = selectingIndex < 0 ? 0 : selectingIndex >= tabView.TabItems.Count ? tabView.TabItems.Count - 1 : selectingIndex; + } + } + public static async Task SaveTabDatabase(TabDatabase tabDatabase, TabView tabView, ProgressWindowItem progressWindow = null) + { + progressWindow?.ShowProgress(); + + //Close all windows to get the tabs back to the tabcontrol: + await TabWindowHelper.CloseAllWindows(); + + Debug.WriteLine("nbrOfTabs: " + tabView.TabItems.Count); + + //Create the file with the tab data: + tabDatabase.SaveData(tabView.TabItems, tabView.SelectedIndex); + + //save the individual files + var folder = await StorageFolder.GetFolderFromPathAsync(DefaultValues.DatabasePath); + for (int i = 0; i < tabView.TabItems.Count; i++) + { + if (tabView.TabItems[i] is TabPageItem tab) + { + if (tab.DataIsLoaded) + { + progressWindow?.SetText("Saving database " + tab.DatabaseItem.FileName + "..."); + await TabDatabase.SaveTempFile(folder, tab); + } + } + } + Debug.WriteLine("Database saved"); + + progressWindow?.HideProgress(); + } + /// + /// Generate a unique tab header + /// + /// + /// + public static string GenerateUniqueHeader(TabView tabView) + { + int TabIndex = 0; + string title = AppSettings.GetSettings(AppSettingsValues.Settings_NewTabTitle, DefaultValues.NewTabTitle); + string extension = AppSettings.GetSettings(AppSettingsValues.Settings_NewTabExtension, DefaultValues.NewTabExtension); + + //check for any equal tab + for (int i = 0; i < tabView.TabItems.Count; i++) + { + foreach (var window in TabWindowHelper.AppWindows) + { + if (window.Value.HasHeader(title + TabIndex + extension)) + { + TabIndex++; + } + } + + if (tabView.TabItems[i] is TabPageItem tab) + { + if (tab.HasHeader(title + TabIndex + extension)) + { + TabIndex++; + i = -1; //go through the loop again + } + } + } + + return title + TabIndex + extension; + } + /// + /// Generate an unique id for every tabpage + /// + /// + /// The id generated + public static string GenerateUniqueIdentifier(TabView tabView) + { + int TabIndex = 0; + + //check for any equal tab + for (int i = 0; i < tabView.TabItems.Count; i++) + { + foreach (var window in TabWindowHelper.AppWindows) + { + if (window.Value.DatabaseItem.Identifier.Equals("Tab" + TabIndex, StringComparison.Ordinal)) + { + TabIndex++; + } + } + + if (tabView.TabItems[i] is TabPageItem tab) + { + if (tab.DatabaseItem.Identifier.Equals("Tab" + TabIndex, StringComparison.Ordinal)) + { + TabIndex++; + i = -1; //go through the loop again + } + } + } + return "Tab" + TabIndex; + } + public static async Task CloseTab(TabView tabView, object tabItem) + { + if (tabItem is TabPageItem tab) + { + if (!tab.DatabaseItem.IsModified || await AskSaveDialog.Show(tab)) + { + await RemoveTab(tabView, tab); + } + } + else if (SettingsTabPageHelper.IsSettingsPage(tabItem)) + SettingsTabPageHelper.CloseSettings(tabView); + + return false; + } + private static async Task RemoveTab(TabView tabView, TabPageItem tab) + { + if (!await RecycleBinDialog.MoveFileToRecycleBin(tab)) + return false; + + tab.textbox.Unload(); + tabView.TabItems.Remove(tab); + TabDatabase.DeleteTempFile(tab); + return !tabView.TabItems.Contains(tab); + } + + public static void TabsOrSpaces(TabView tabView, object tag) + { + if (tag == null) + return; + + int number = ConvertHelper.ToInt(tag); + for (int i = 0; i < tabView.TabItems.Count; i++) + { + if (tabView.TabItems[i] is TabPageItem tab) + { + tab.textbox.UseSpacesInsteadTabs = number != -1; + if (number != -1) + { + tab.textbox.NumberOfSpacesForTab = number; + } + } + } + + AppSettings.SaveSettings(AppSettingsValues.Settings_SpacesPerTab, number); + AppSettings.SaveSettings(AppSettingsValues.Settings_UseSpacesInsteadTabs, number != -1); + } + public static void UpdateSaveStatus(TabPageItem tab, bool IsModified, string FileToken = "", StorageFile file = null) + { + tab.DatabaseItem.IsModified = IsModified; + tab.DatabaseItem.FileToken = FileToken; + + if (file != null) + { + tab.DatabaseItem.FilePath = file.Path; + tab.SetHeader(file.Name); + SelectCodeLanguageByFile(tab, file); + return; + } + + tab.UpdateHeader(); + } + public static async Task SaveFile(TabPageItem tab) + { + if (tab == null) + return false; + + return await SaveFileHelper.Save(tab); + } + public static async Task SaveFileAs(TabPageItem tab) + { + if (tab == null) + return false; + + return await SaveFileHelper.SaveFileAs(tab); + } + public static async Task OpenFile(TabView tabView) + { + return await OpenFileHelper.OpenFile(tabView); + } + + public static async Task OpenFiles(TabView tabView, IReadOnlyList files) + { + if (files.Count == 0) + return false; + + for (int i = 0; i < files.Count; i++) + { + //Only load the last tab, the others will be saved as temporary files and loaded when needed + var tab = await OpenFileHelper.DoOpen(tabView, files[i] as StorageFile, i == files.Count - 1); + if (tab == null) + return false; + + //select the last tab + if (i == files.Count - 1) + tabView.SelectedItem = tab; + } + return true; + } + public static void SelectCodeLanguageByFile(TabPageItem tab, StorageFile file) + { + if (tab == null) + return; + + string extension = Path.GetExtension(file.Path).ToLower(); + + //search through the dictionary of codelanguages in the textbox + foreach (var item in TextControlBox.TextControlBox.CodeLanguages) + { + for (int i = 0; i < item.Value.Filter.Length; i++) + { + if (item.Value.Filter[i].Equals(extension, StringComparison.OrdinalIgnoreCase)) + { + tab.CodeLanguage = item.Value; + return; + } + } + } + } + public static void SelectNextTab(TabView tabView) + { + if (tabView.SelectedIndex < tabView.TabItems.Count - 1) + { + tabView.SelectedIndex++; + } + } + public static void SelectPreviousTab(TabView tabView) + { + if (tabView.SelectedIndex > 0) + { + tabView.SelectedIndex--; + } + } + } +} \ No newline at end of file diff --git a/Fastedit/Tab/TabPageItem.cs b/Fastedit/Tab/TabPageItem.cs new file mode 100644 index 0000000..c075dc3 --- /dev/null +++ b/Fastedit/Tab/TabPageItem.cs @@ -0,0 +1,142 @@ +using Fastedit.Helper; +using Fastedit.Settings; +using Microsoft.UI.Xaml.Controls; +using System; +using System.Text; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; + +namespace Fastedit.Tab +{ + public class TabPageItem : TabViewItem + { + public delegate void TabPageHeaderChangedEvent(string header); + public event TabPageHeaderChangedEvent TabPageHeaderChanged; + + public TextControlBox.TextControlBox textbox { get; private set; } + + public TabPageItem(TabView tabView) + { + Initialise(tabView); + } + + //Remove the textbox from the current Grid: + public void RemoveTextbox() + { + if (this.Content is Grid grd) + { + textbox.Margin = new Thickness(0, 0, 0, 0); + grd.Children.Clear(); + } + } + //add the textbox back to the current Grid: + public void AddTextbox() + { + if (this.Content is Grid grd) + { + grd.Children.Add(textbox); + } + } + + + private void Initialise(TabView tabView) + { + textbox = TabPageHelper.CreateTextBox(); + //add a reference to the tabitem to the textbox + textbox.Tag = this; + + var grid = new Grid(); + + this.IconSource = new Microsoft.UI.Xaml.Controls.SymbolIconSource() { Symbol = Symbol.Page2 }; + + this.ContextFlyout = TabFlyout.CreateFlyout(this, tabView); + this.Content = grid; + grid.Children.Add(textbox); + + Encoding = DefaultValues.Encoding; + DatabaseItem = new TabItemDatabaseItem + { + FilePath = "", + FileToken = "", + IsModified = false, + ZoomFactor = 100, + }; + } + + public bool DataIsLoaded = false; + + public TextControlBox.Renderer.CodeLanguage CodeLanguage + { + get => textbox.CodeLanguage; + set + { + textbox.CodeLanguage = value; + DatabaseItem.CodeLanguage = value == null ? null : value.Name; + } + } + + public int CountWords() + { + return textbox.GetText().Split(new char[] { '\n', ' ', '\r' }, StringSplitOptions.RemoveEmptyEntries).Length; + } + public bool HasHeader(string header) + { + if (this.DatabaseItem.FileName == null) + return false; + + return this.DatabaseItem.FileName.Equals(header, StringComparison.Ordinal); + } + public void SetHeader(string header) + { + if (DatabaseItem.IsModified) + { + + if (this.Header == null) + this.Header = header ?? ""; + + string currentHeader = this.Header.ToString(); + if (currentHeader.Length > 0) + { + this.Header = header + (currentHeader[currentHeader.Length - 1] == '*' ? "" : "*"); + } + } + else + this.Header = header; + + TabPageHeaderChanged?.Invoke(header); + + DatabaseItem.FileName = header; + } + //Ensure the save status of the file to be displayed in the header + public void UpdateHeader() + { + SetHeader(DatabaseItem.FileName); + } + + private void ApplyDatabaseItemToTextbox() + { + if (DatabaseItem == null) + return; + + textbox.ZoomFactor = _DataBaseItem.ZoomFactor; + SetHeader(_DataBaseItem.FileName); + textbox.CodeLanguage = TextControlBox.TextControlBox.GetCodeLanguageFromId(_DataBaseItem.CodeLanguage ?? ""); + } + + private TabItemDatabaseItem _DataBaseItem; + public TabItemDatabaseItem DatabaseItem { get => _DataBaseItem; set { _DataBaseItem = value; ApplyDatabaseItemToTextbox(); } } + private Encoding _Encoding; + public Encoding Encoding + { + get => _Encoding; + set + { + _Encoding = value; + + if (_DataBaseItem == null) + return; + _DataBaseItem.Encoding = EncodingHelper.GetIndexByEncoding(value); + } + } + } +} diff --git a/Fastedit/Tab/TabWindowHelper.cs b/Fastedit/Tab/TabWindowHelper.cs new file mode 100644 index 0000000..dba6c52 --- /dev/null +++ b/Fastedit/Tab/TabWindowHelper.cs @@ -0,0 +1,135 @@ +using Fastedit.Helper; +using Fastedit.Settings; +using Fastedit.Views; +using Microsoft.UI.Xaml.Controls; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Windows.UI; +using Windows.UI.WindowManagement; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Hosting; +using Windows.UI.Xaml.Media; + +namespace Fastedit.Tab +{ + internal class TabWindowHelper + { + private static TabView tabView = null; + private static bool closeWithoutChanging = true; + + public static Dictionary AppWindows { get; set; } = new Dictionary(); + + public static async Task ShowInNewWindow(TabView tabView, TabPageItem tab) + { + TabWindowHelper.tabView = tabView; + + if (tab == null) + return false; + + tabView.TabItems.Remove(tab); + + tab.RemoveTextbox(); + tab.DatabaseItem.HasOwnWindow = true; + var window = await CreateWindow(); + window.Title = tab.DatabaseItem.FileName; + window.TitleBar.ExtendsContentIntoTitleBar = true; + window.TitleBar.ButtonBackgroundColor = Colors.Transparent; + + ElementCompositionPreview.SetAppWindowContent(window, new TabWindowPage(tab, window)); + + window.Closed += Window_Closed; + if (await window.TryShowAsync()) + { + AppWindows.Add(window, tab); + UpdateSettings(); + tab.textbox.ClearSelection(); + + //Delay to prevent holding down the key + await Task.Delay(400); + + return true; + } + return false; + } + + public static async Task CloseAllWindows(bool closeForSave = true) + { + closeWithoutChanging = !closeForSave; + + int count = AppWindows.Count; + for (int i = 0; i < count; i++) + { + await AppWindows.Keys.ElementAt(0).CloseAsync(); + } + } + + /*public static async Task CloseWindow(TabPageItem tab) + { + Debug.WriteLine("CLose Window: " + tab.DatabaseItem.FileName); + //Find the AppWindow that matches to the tab + var res = AppWindows.Where(x => x.Value == tab); + if(res.Count() <= 0) return false; + + await res.ElementAt(0).Key.CloseAsync(); + return true; + }*/ + + public static void UpdateSettings() + { + var gridBackground = new SolidColorBrush(ConvertHelper.ToColor(DesignHelper.CurrentDesign.SelectedTabPageHeaderBackground)); + foreach (var item in TabWindowHelper.AppWindows) + { + var window = item.Key; + if (ElementCompositionPreview.GetAppWindowContent(window) is TabWindowPage page) + { + //Fix for mica not working in appwindow: + if (DesignHelper.CurrentDesign.BackgroundType == BackgroundType.Mica) + { + Color bg = ThemeHelper.CurrentTheme == ElementTheme.Dark ? Color.FromArgb(255, 25, 25, 25) : Color.FromArgb(255, 255, 255, 255); + page.Background = new SolidColorBrush(bg); + } + else + SettingsUpdater.SetMainPageSettings(page, DesignHelper.CurrentDesign); + + //apply settings to textbox without updating the margin: + SettingsUpdater.UpdateTab(item.Value, false); + + //apply to tab: + page.MainGrid.Background = gridBackground; + } + } + } + + private static void Window_Closed(AppWindow sender, AppWindowClosedEventArgs args) + { + AppWindows.TryGetValue(sender, out var tab); + AppWindows.Remove(sender); + + //remove the textbox from the window and add it back to the tab: + if (ElementCompositionPreview.GetAppWindowContent(sender) is TabWindowPage page) + { + page.Close(); + tab.AddTextbox(); + + //Add the tab back + tabView.TabItems.Add(tab); + + if (closeWithoutChanging) + { + tab.DatabaseItem.HasOwnWindow = false; + closeWithoutChanging = true; + } + + //apply settings to tab + SettingsUpdater.UpdateTab(tab, false); + } + } + + private static async Task CreateWindow() + { + return await AppWindow.TryCreateAsync(); + } + } +} diff --git a/Fastedit/Views/AboutPage.xaml b/Fastedit/Views/AboutPage.xaml index cca63b2..cd6fbf1 100644 --- a/Fastedit/Views/AboutPage.xaml +++ b/Fastedit/Views/AboutPage.xaml @@ -4,252 +4,140 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:Fastedit.Views" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" - xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" + xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:controls="using:Fastedit.Controls" xmlns:muxc="using:Microsoft.UI.Xaml.Controls" mc:Ignorable="d"> - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - + + + + - - - - - - + + + + + + + + + + + + + + + - - - - - - - - - - Disclaimer - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - Last updated: January 14, 2022 + By using the app you are consenting to our policies regarding the collection, use and disclosure of personal information set out in this privacy policy. - - - Interpretation and Definitions + + Collection of Personal Information - - - Interpretation - - - - The words of which the initial letter is capitalized have meanings defined under the following conditions. The following definitions shall have the same meaning regardless of whether they appear in singular or in plural. - - - - Definitions - - - - For the purposes of this Disclaimer: + + We do not collect, store, use or share any information, personal or otherwise. - - • - Company - (referred to as either "the Company", "We", "Us" or "Our" in this Disclaimer) refers to Fastedit. + + Email - - • - Service - refers to the Application. + + If you email the developer for support or other feedback, the emails with email addresses will be retained for quality assurance purposes. The email addresses will be used only to reply to the concerns or suggestions raised and will never be used for any marketing purpose. - - • - You - - means the individual accessing the Service, or the company, or other legal entity on behalf of which such individual is accessing or using the Service, as applicable. - + + Disclosure of Personal Information - - • - Application - - means the software program provided by the Company downloaded by You on any electronic device named Fastedit. - + + We will not disclose your information to any third party except if you expressly consent or where required by law. - - - Disclaimer + + Contacting Us - - - - The information contained on the Service is for general information purposes only. - + + If you have any questions regarding this privacy policy, you can email - - - - The Company assumes no responsibility for errors or omissions in the contents of the Service. - + + fasteditsoftware@gmail.com + + - - - In no event shall the Company be liable for any special, direct, indirect, consequential, or incidental damages or any damages whatsoever, whether in an action of contract, negligence or other tort, arising out of or in connection with the use of the Service or the contents of the Service. The Company reserves the right to make additions, deletions, or modifications to the contents on the Service at any time without prior notice. This Disclaimer has been created with the help of the + + + + + + + + + + + We are doing our best to prepare the content of this app. However, Fastedit cannot warranty the expressions and suggestions of the contents, as well as its accuracy. In addition, to the extent permitted by the law, Fastedit shall not be responsible for any losses and/or damages due to the usage of the information on our app. Our Disclaimer was generated with the help of the App Disclaimer Generator from App-Privacy-Policy.com - - Disclaimer Template - . - - - - The Company does not warrant that the Service is free of viruses or other harmful components. + + + By using our app, you hereby consent to our disclaimer and agree to its terms. - - - - External Links Disclaimer + + + Any links contained in our app may lead to external sites are provided for convenience only. Any information or statements that appeared in these sites or app are not sponsored, endorsed, or otherwise approved by Fastedit. For these external sites, Fastedit cannot be held liable for the availability of, or the content located on or through it. Plus, any losses or damages occurred from using these contents or the internet generally. - - - - The Service may contain links to external websites that are not provided or maintained by or in any way affiliated with the Company. - - - - - Please note that the Company does not guarantee the accuracy, relevance, timeliness, or completeness of any information on these external websites. - - - - Errors and Omissions Disclaimer - - - - - The information given by the Service is for general guidance on matters of interest only. Even if the Company takes every precaution to insure that the content of the Service is both current and accurate, errors can occur. Plus, given the changing nature of laws, rules and regulations, there may be delays, omissions or inaccuracies in the information contained on the Service. - - - - The Company is not responsible for any errors or omissions, or for the results obtained from the use of this information. - - - - Fair Use Disclaimer - - - - - The Company may use copyrighted material which has not always been specifically authorized by the copyright owner. The Company is making such material available for criticism, comment, news reporting, teaching, scholarship, or research. - - - - The Company believes this constitutes a "fair use" of any such copyrighted material as provided for in section 107 of the United States Copyright law. - - - - If You wish to use copyrighted material from the Service for your own purposes that go beyond fair use, You must obtain permission from the copyright owner. - - - - - Views Expressed Disclaimer - - - - The Service may contain views and opinions which are those of the authors and do not necessarily reflect the official policy or position of any other author, agency, organization, employer or company, including the Company. - - - - Comments published by users are their sole responsibility and the users will take full responsibility, liability and blame for any libel or litigation that results from something written in or as a direct result of something written in a comment. The Company is not liable for any comment published by users and reserves the right to delete any comment for any reason whatsoever. - - - - - No Responsibility Disclaimer - - - - The information on the Service is provided with the understanding that the Company is not herein engaged in rendering legal, accounting, tax, or other professional advice and services. As such, it should not be used as a substitute for consultation with professional accounting, tax, legal or other competent advisers. - - - - In no event shall the Company or its suppliers be liable for any special, incidental, indirect, or consequential damages whatsoever arising out of or in connection with your access or use or inability to access or use the Service. - - - - - "Use at Your Own Risk" Disclaimer - - - - All information in the Service is provided "as is", with no guarantee of completeness, accuracy, timeliness or of the results obtained from the use of this information, and without warranty of any kind, express or implied, including, but not limited to warranties of performance, merchantability and fitness for a particular purpose. - - - - The Company will not be liable to You or anyone else for any decision made or action taken in reliance on the information given by the Service or for any consequential, special or similar damages, even if advised of the possibility of such damages. - - - - - Contact Us - - - If you have any questions about this Disclaimer, You can contact Us: - - - - - - - - - - - + + + + + - - - - + - - - - - - + + + + + + - - - - - + + + - + - + - + - + - - - - + + - + - - + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - + - + - - - + - + - - - - - + - - - - - + + + + + + + + + + + + - - - - + - + - - - - - + + - + - + - + - + + + + + + + + + + - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + - - - - - - - - - - + + + + - - - - - - - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + \ No newline at end of file diff --git a/Fastedit/Views/MainPage.xaml.cs b/Fastedit/Views/MainPage.xaml.cs index 31d1008..70b9a32 100644 --- a/Fastedit/Views/MainPage.xaml.cs +++ b/Fastedit/Views/MainPage.xaml.cs @@ -1,2095 +1,604 @@ -using Fastedit.Controls.Textbox; -using Fastedit.Core; -using Fastedit.Core.Tab; +using Fastedit.Controls; using Fastedit.Dialogs; -using Fastedit.Extensions; -using Fastedit.ExternalData; using Fastedit.Helper; -using Fastedit.Views; -using Microsoft.Toolkit.Uwp.UI.Helpers; +using Fastedit.Settings; +using Fastedit.Storage; +using Fastedit.Tab; using Microsoft.UI.Xaml.Controls; -using Microsoft.UI.Xaml.Controls.Primitives; using System; using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Text; using System.Threading.Tasks; -using Windows.ApplicationModel; -using Windows.ApplicationModel.Activation; -using Windows.ApplicationModel.Core; using Windows.ApplicationModel.DataTransfer; -using Windows.Foundation; -using Windows.Storage; using Windows.System; -using Windows.UI; -using Windows.UI.Core; using Windows.UI.Core.Preview; -using Windows.UI.Popups; -using Windows.UI.Text; -using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Input; -using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; -using Convert = Fastedit.Extensions.Convert; -using MenuBarItem = Microsoft.UI.Xaml.Controls.MenuBarItem; -using muxc = Microsoft.UI.Xaml.Controls; -using StringBuilder = Fastedit.Extensions.StringBuilder; namespace Fastedit { public sealed partial class MainPage : Page { - //Other Classes - private TabActions tabactions = null; - private readonly AppSettings appsettings = new AppSettings(); - private readonly SaveFileHelper savefilehelper = new SaveFileHelper(); - private readonly TabPageHelper tabpagehelper = new TabPageHelper(); - private readonly CustomDesigns customdesigns = null; - private readonly DatabaseImportExport databaseimportexport = null; - public readonly SecondaryEditingInstance secondaryeditinginstance = null; - - //Settings entrys: - private FontFamily TextBoxFontfamily = new FontFamily(DefaultValues.DefaultFontFamily); - private int TextBoxFontSize = DefaultValues.DefaultFontsize; - private Color TextBoxBackgroundcolor = Colors.Transparent; - private Color TextColor = Colors.Transparent; - private Color TitleBarBackgroundColor = Colors.Transparent; - private Color TextSelectionColor = Colors.Transparent; - private Color TabColorNotFocused = Colors.Transparent; - private Color TabColorFocused = Colors.Transparent; - private Color LineNumberForegroundColor = Colors.Transparent; - private Color LineNumberBackgroundColor = Colors.Transparent; - private Color StatusbarBackgroundColor = Colors.Transparent; - private Color StatusbarForegroundColor = Colors.Transparent; - private Color LineHighlighterForeground = Colors.Blue; - private Color LineHighlighterBackground = Colors.Blue; - private bool ShowLineNumbers = true; - private bool ShowStatusBar = true; - private bool IsHandWritingEnabled = DefaultValues.HandWritingEnabled; - private bool ShowSelectionFlyout = false; - private bool ShowMenubar - { - get => MainMenuBar != null; - set - { - if (value && MainMenuBar == null) - { - MainMenuBar = FindName("MainMenuBar") as muxc.MenuBar; - } - else if (value == false && MainMenuBar != null) - { - UnloadObject(MainMenuBar); - } - } - } - private bool ShowLineHighlighter = true; - private readonly Searchdialog searchdialog = null; - - //Variables - private bool HasAlreadyNavigatedTo = false; - private bool SettingsWindowSelected = false; - private bool preventZoomOnFactorChanged = false; - - //Controls and Objects - private readonly DispatcherTimer newTabSaveTime = new DispatcherTimer(); - private TextControlBox CurrentlySelectedTabPage_Textbox = null; - private muxc.TabViewItem CurrentlySelectedTabPage = null; - private muxc.FontIconSource TabPageFontIconSource = null; - private muxc.TabViewItem SettingsTabPage = null; - private NavigationEventArgs navigaionEvent = null; - private TabViewListView tabviewlistview = null; + TitlebarHelper titlebarhelper; + TabDatabase tabdatabase = new TabDatabase(); + public TabPageItem currentlySelectedTabPage = null; + bool FirstLoaded = false; + bool TabsLoaded = false; + public List ControlsToHideInSettings = new List(); + Flyout ShowAllTabsFlyout = null; + ProgressWindowItem progressWindow; public MainPage() { this.InitializeComponent(); - if (tabactions == null) - tabactions = new TabActions(TextTabControl, this); - if (customdesigns == null) - customdesigns = new CustomDesigns(null, this); - if (databaseimportexport == null) - databaseimportexport = new DatabaseImportExport(this, TextTabControl); - if (secondaryeditinginstance == null) - secondaryeditinginstance = new SecondaryEditingInstance(this, tabactions, TextTabControl); - if (searchdialog == null) - { - searchdialog = new Searchdialog(CurrentlySelectedTabPage_Textbox); - searchdialog.Visibility = Visibility.Collapsed; - SearchReplaceWindowDisplay.Children.Add(searchdialog); - } - - //Subscribe to the events: - SizeChanged += MainPage_SizeChanged; - SystemNavigationManagerPreview.GetForCurrentView().CloseRequested += Application_OnCloseRequest; - new ThemeListener().ThemeChanged += Application_ThemeChanged; - } - - //Initialisation - private async Task Initialisation() - { - //Only if application has started the very first time - bool IsFirstStart = false; - if (appsettings.GetSettingsAsBool("FirstStart", true)) - { - IsFirstStart = true; - await CopyThemesToFolder(); - appsettings.SaveSettings("FirstStart", false); - } - - await SetSettings(false); - - //Prevent repeated call of this functions: - if (HasAlreadyNavigatedTo == false) - { - HasAlreadyNavigatedTo = true; - //Only load the tabs from the database - if (appsettings.GetSettingsAsBool("LoadRecentTabs", DefaultValues.LoadRecentTabsOnStart)) - { - await tabactions.LoadTabs(false); - } - - //Check if it is running on a new version and it is not the first start - //If yes show the infobar which leads to the changelog - if (IsOnNewVersion() && !IsFirstStart) - ShowNewVersionInfobar(); - } - } - private void AfterInitialisation() - { - SetTitlebar(); - ApplySettingsToAllTabPages(); - AutoBackupDataBaseTimer(); - TextTabControl_SelectionChanged(null, null); - //Add the buttons with encoding to the Statusbar - AddEncodingButtonsToStatusbar(); - } - private async Task CopyThemesToFolder() - { - try - { - string root = Windows.ApplicationModel.Package.Current.InstalledLocation.Path; - StorageFolder sourceFolder = await StorageFolder.GetFolderFromPathAsync($"{root}\\Assets\\Designs"); - - var files = await sourceFolder.GetFilesAsync(); - for (int i = 0; i < files.Count; i++) - { - StorageFile file = files[i]; - if (file != null) - { - await file.CopyAsync(customdesigns.DesignsFolder, file.Name, NameCollisionOption.ReplaceExisting); - } - } - - //Decide to either load a theme with Mica or Acrylic - if(VersionHelper.GetWindowsVersion() == WindowsVersion.Windows11) - { - appsettings.SaveSettings("SelectedDesign", 5); - await customdesigns.LoadDesignFromFile( - await customdesigns.GetFileFromDesignsFolder(DefaultValues.DefaultWindows11ThemeName)); - } - else - { - appsettings.SaveSettings("SelectedDesign", 1); - await customdesigns.LoadDesignFromFile( - await customdesigns.GetFileFromDesignsFolder(DefaultValues.DefaultThemeName)); - } - } - catch (Exception e) - { - ShowInfobar("Could not load Themes to the folder\n" + e.Message, "", muxc.InfoBarSeverity.Error); - } - } - private async Task LoadTabs(NavigationEventArgs e, bool LoadTabs = true) - { - if(LoadTabs) - await Initialisation(); - - //If the app was started by the fileactivationevent: - if (e != null && e.Parameter is FileActivatedEventArgs fae) - { - //Dont create a new Tab cause a file is opened on start - if (e != null) - { - await tabactions.OpenFilesFromEvent(fae); - } - } - else if (e.Parameter is CommandLineLaunchNavigationParameter args) - { - try - { - await tabactions.OpenFileFromCommandLine(args); - } - catch (Exception ex) - { - await new MessageDialog(ex.Message).ShowAsync(); - } - } - - - if (LoadTabs && tabactions.GetTabItemCount() < 1) - tabactions.NewTab(); - - if(LoadTabs) - AfterInitialisation(); - } - protected override async void OnNavigatedTo(NavigationEventArgs e) - { - this.navigaionEvent = e; - //If the event is called,because another file - //wants to get opened after the app is already running - if (HasAlreadyNavigatedTo) - { - await LoadTabs(e, false); - } - base.OnNavigatedTo(e); - } - - //MainPage-Events: - private void MainPage_DragOver(object sender, DragEventArgs e) - { - DragOver(e); - } - private async void MainPage_Drop(object sender, DragEventArgs e) - { - await DropFile(sender, e); - } - private void MainPage_SizeChanged(object sender, SizeChangedEventArgs e) - { - TextTabControl.Width = Statusbar.Width = e.NewSize.Width; - if (e.NewSize.Width < 700 && WordCountDisplay.Margin.Left != 3) - { - WordCountDisplay.Margin = SaveStatusDisplay.Margin = - EncodingDisplay.Margin = LineNumberDisplay.Margin = - ZoomDisplay.Margin = FileNameDisplay.Margin = new Thickness(0, 0, 0, 0); - } - else if (e.NewSize.Width >= 700 && WordCountDisplay.Margin.Left == 0) - { - WordCountDisplay.Margin = SaveStatusDisplay.Margin = - EncodingDisplay.Margin = LineNumberDisplay.Margin = - ZoomDisplay.Margin = FileNameDisplay.Margin = new Thickness(10, 0, 10, 0); - } - } - private async void MainPage_KeyDown(object sender, KeyRoutedEventArgs e) - { - var ctrl = Window.Current.CoreWindow.GetKeyState(VirtualKey.Control); - var shift = Window.Current.CoreWindow.GetKeyState(VirtualKey.Shift); - var alt = Window.Current.CoreWindow.GetKeyState(VirtualKey.Menu); - - //Commands without modifierkey: - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.F11, Fullscreen_Action); - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.F1, OpenSettings_Action); - - //Call everytime control is pressed: - if (ctrl.HasFlag(CoreVirtualKeyStates.Down) && !alt.HasFlag(CoreVirtualKeyStates.Down)) - { - if (!SettingsWindowSelected) - { - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.N, NewTab_Action); - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.T, NewTab_Action); - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.O, Open_Action); - } - } - - //Call only if a tab exists and the settingswindow is not opened: - if (tabactions.GetTabItemCount() > 0 && !SettingsWindowSelected) - { - if (e.Key == VirtualKey.Escape) - { - if (GoToLineWindowIsOpen && !searchdialog.SearchIsOpen) - { - CloseGoToLineDialog(); - } - - if (searchdialog.SearchIsOpen && !GoToLineWindowIsOpen) - { - searchdialog.Close(); - } - - if (searchdialog.SearchIsOpen && GoToLineWindowIsOpen) - { - searchdialog.Close(); - CloseGoToLineDialog(); - } - - tabactions.GetTextBoxFromSelectedTabPage().Focus(FocusState.Programmatic); - } - - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.F3, searchdialog.Find, false); - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.F2, OpenRenameFlyout); - - //Call every time the shortcut is pressed - if (ctrl.HasFlag(CoreVirtualKeyStates.Down) && !alt.HasFlag(CoreVirtualKeyStates.Down)) - { - muxc.TabViewItem Tab = tabactions.GetSelectedTabPage(); - if (Tab != null) - { - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.G, ShowGoToLineWindow); - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.F, searchdialog.Toggle, false); - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.R, searchdialog.Toggle, true); - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.W, CloseSelectedTab_SaveDatabase); - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.J, ShowFileInfoDialog); - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.E, ShowEncodingDialog); - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.B, ExpandTabToNewWindow_Action); - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.M, ToggleMarkdown_Action); - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.Q, SurroundWithText_Action); - - //Ctrl + S - if (e.Key == VirtualKey.S) - { - try - { - if (shift.HasFlag(CoreVirtualKeyStates.Down)) - { - await savefilehelper.SaveFileAs(Tab); - } - else - { - await savefilehelper.Save(Tab); - } - - } - catch (Exception ex) - { - Debug.WriteLine("Exception in MainPage --> Page_KeyDown --> e.Key == VirtualKey.S :\n" + ex.Message); - } - } - } - - //Select tabs - int tabtoselect = 0; - switch (e.Key) - { - case VirtualKey.Number1: - tabtoselect = 1; - break; - case VirtualKey.Number2: - tabtoselect = 2; - break; - case VirtualKey.Number3: - tabtoselect = 3; - break; - case VirtualKey.Number4: - tabtoselect = 4; - break; - case VirtualKey.Number5: - tabtoselect = 5; - break; - case VirtualKey.Number6: - tabtoselect = 6; - break; - case VirtualKey.Number7: - tabtoselect = 7; - break; - case VirtualKey.Number8: - tabtoselect = 8; - break; - case VirtualKey.Number9: - tabtoselect = tabactions.GetTabItemCount(); - break; - } - if (tabtoselect != 0 && tabactions.GetTabItemCount() >= tabtoselect) - { - TextTabControl.SelectedIndex = tabtoselect - 1; - } - } - } - - //Call only if a tab exists - if (tabactions.GetTabItemCount() > 0) - { - if (ctrl.HasFlag(CoreVirtualKeyStates.Down)) - { - if (alt.HasFlag(CoreVirtualKeyStates.Down)) - { - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.Left, NavigateToPreviousTab_Action); - KeyboardCommands.KeyboardCommand(e.Key, VirtualKey.Right, NavigateToNextTab_Action); - } - if (e.Key == VirtualKey.Tab) - { - if (shift.HasFlag(CoreVirtualKeyStates.Down)) - { - NavigateToPreviousTab_Action(); - } - else - { - NavigateToNextTab_Action(); - } - } - } - } - } - private async void Application_OnCloseRequest(object sender, SystemNavigationCloseRequestedPreviewEventArgs e) - { - var deferral = e.GetDeferral(); - - if (IsContentDialogOpen()) - e.Handled = true; + TabPageHelper.mainPage = this; - if (secondaryeditinginstance.OpenedSecondaryViews.Count > 0) - { - ShowInfobar(InfoBarMessages.CloseAllInstances, InfoBarMessages.CloseAllInstances_Title, muxc.InfoBarSeverity.Warning); - e.Handled = true; - } - else - { - if (tabactions != null) - { - if (await tabactions.CloseTabs() == false) - e.Handled = true; - } - else - Debug.WriteLine("MainPage -> Application_OnCloseRequest : TabActions is null"); - } + //DesignHelper.LoadDesign(Path.Combine(DefaultValues.DesignPath, "temp.json")); - if (IsContentDialogOpen()) - e.Handled = true; + //events: + Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown; + SystemNavigationManagerPreview.GetForCurrentView().CloseRequested += MainPage_CloseRequested; + SettingsTabPageHelper.SettingsTabClosed += SettingsUpdater_SettingsTabClosed; - deferral.Complete(); - } - private async void Application_ThemeChanged(ThemeListener sender) - { - await ChangeDesign(sender.CurrentTheme); - await SetSettings(true); - } - private async Task ChangeDesign(ApplicationTheme sender) - { - void ReportError() - { - ShowInfobar(ErrorDialogs.LoadDesignError()); - } - - string DesignName; - StorageFolder outputFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(DefaultValues.CustomDesigns_FolderName, CreationCollisionOption.OpenIfExists); - if (outputFolder == null) - { - ReportError(); - return; - } + //classes + if (titlebarhelper == null) + titlebarhelper = new TitlebarHelper(CustomDragRegion, ShellTitlebarInset, FlowDirection); - if (sender == ApplicationTheme.Dark) - { - DesignName = appsettings.GetSettingsAsString("DesignForDarkMode", DefaultValues.DefaultThemeName); - } - else - { - DesignName = appsettings.GetSettingsAsString("DesignForLightMode", DefaultValues.DefaultThemeName); - } - if (await customdesigns.LoadDesignFromFile( - await customdesigns.GetFileFromDesignsFolder(DesignName)) == false) - { - ReportError(); - } - } + if (progressWindow == null) + progressWindow = new ProgressWindowItem(progressBar, progressInfo); - //TextTabControl-Events: - private async void TextTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e) - { - //If tabitems equals zero, disable all items: - if (TextTabControl.TabItems.Count == 0) - { - for (int i = 0; i < ToolbarFlyout.Items.Count; i++) - { - if (ToolbarFlyout.Items[i] is MenuFlyoutItem item) - { - if (item.Name != "DropDownMenu_New" && item.Name != "DropDownMenu_Open" && item.Name != "DropDownMenu_Settings") - { - item.IsEnabled = false; - } - } - if (ToolbarFlyout.Items[i] is MenuFlyoutSubItem subitem) - { - subitem.IsEnabled = false; - } - } - } - - var tabpage = tabactions.GetSelectedTabPage(); - if (tabpage != null && tabpage.Content is TextControlBox textbox) - { - if (!textbox.TextLoaded) - await tabactions.SetTextFromBuffer(tabpage); - - ShowHideControlsOnSelectionChanged(true); - CurrentlySelectedTabPage = tabpage; - CurrentlySelectedTabPage_Textbox = textbox; - searchdialog.textbox = textbox; - - SettingsWindowSelected = false; - - if (ShowMenubar && MainMenuBar != null) - { - MainMenuBar.Visibility = Visibility.Visible; - } - - if (ShowStatusBar) - { - Statusbar.Visibility = Visibility.Visible; - } - searchdialog.SearchIsOpen = appsettings.GetSettingsAsBool("SearchOpen", false); - GoToLineWindowIsOpen = appsettings.GetSettingsAsBool("GoToLineWindowOpened", false); + InfoMessages.InfoMessagePanel = infobarDisplay; - if (textbox.TabSaveMode == TabSaveMode.SaveAsFile || textbox.TabSaveMode == TabSaveMode.SaveAsTemp) - { - if (IsControlNOTNull(CanNotRenameFileInfo)) - { - CanNotRenameFileInfo.Visibility = Visibility.Collapsed; - RenameTextBox.IsEnabled = true; - RenameFileButton.IsEnabled = true; - } - } - else if (textbox.TabSaveMode == TabSaveMode.SaveAsDragDrop) - { - CanNotRenameFileInfo.Visibility = Visibility.Visible; - RenameTextBox.IsEnabled = false; - RenameFileButton.IsEnabled = false; - } - - //Show /hide the OpenWithEncoding Button when the file was not even saved - OpenWithEncodingButton.IsEnabled = textbox.TabSaveMode == TabSaveMode.SaveAsTemp ? false : true; - - TextControlBox_ZoomChangedEvent(textbox, textbox._zoomFactor); - TextControlBox_LineNumberchangedEvent(textbox, textbox.GetCurrentLineNumber); - TextControlBox_DocumentTitleChangedEvent(textbox, textbox.Header); - Content_EncodingChangedEvent(textbox, textbox.Encoding); - Textbox_WordCountChangedEvent(textbox, textbox.CountWords()); - //Content_ColumnChangedEvent(textbox, textbox.GetCurrentColumn); - Content_SaveStatusChangedEvent(textbox, textbox.IsModified); + //Enable auto save database + AutoDatabaseSaveHelper.RegisterSave(); - SetTitlebarText(tabpagehelper.GetTabFileName(tabpage)); - - EncodingButton_Click(FindName(Encodings.EncodingToString(textbox.Encoding).Replace("-", "_") + "_EncodingButton"), null); - //Check wordwrapbutton - DropDownMenu_WordWrap.IsChecked = textbox.WordWrap == TextWrapping.Wrap; - } - else - { - ShowHideControlsOnSelectionChanged(false); - CurrentlySelectedTabPage = null; - CurrentlySelectedTabPage_Textbox = null; - SettingsWindowSelected = true; - - if (tabpage != null && tabpage.Content is Frame) - { - if (ShowMenubar) - { - MainMenuBar.Visibility = Visibility.Collapsed; - } - if (Statusbar != null) - { - Statusbar.Visibility = Visibility.Collapsed; - } - if (searchdialog.SearchIsOpen) - searchdialog.SearchIsOpen = false; - - if (GoToLineWindowIsOpen) - { - GoToLineWindowIsOpen = false; - } - } - } - - //Highlight the selected tabpage in the tabbar, because it wont get scrolled to it if the Tabcontrol is in overflow - ScrollToSelectedTabPage(); - } - private void TextTabControl_AddTabButtonClick(muxc.TabView sender, object args) - { - NewTab_Action(); - } - private async void TextTabControl_TabCloseRequested(muxc.TabView sender, muxc.TabViewTabCloseRequestedEventArgs args) - { - if (tabactions.GetTextBoxFromTabPage(args.Tab) != null) - { - await tabactions.CloseTabAndSaveDataBase(args.Tab); - } - else if (SettingsWindowSelected || args.Tab.Content is Frame) - { - CloseSettingsTabPage(); - } - //Create a new tab when no tab exists - if (tabactions.GetTabItemCount() == 0) - { - NewTab_Action(); - } - } - private async void TextTabControl_TabDroppedOutside(muxc.TabView sender, muxc.TabViewTabDroppedOutsideEventArgs args) - { - if (args.Tab != null) - await secondaryeditinginstance.ExpandTabPageToNewView(args.Tab); - } - private void TextTabControl_Loaded(object sender, RoutedEventArgs e) - { - tabviewlistview = TextTabControl.FindElementByName("TabListView") as TabViewListView; - } - - - //Titlebar - private async void Titlebar_Loaded(object sender, RoutedEventArgs e) - { - SetTitlebar(); - //Load tabs - await LoadTabs(navigaionEvent); - } - private void SetTitlebar() - { - ApplicationViewTitleBar titleBar = ApplicationView.GetForCurrentView().TitleBar; - titleBar.ButtonBackgroundColor = Colors.Transparent; - titleBar.ButtonInactiveBackgroundColor = Colors.Transparent; - titleBar.InactiveForegroundColor = Convert.WhiteOrBlackFromColorBrightness(StatusbarBackgroundColor); - - var coreTitleBar = CoreApplication.GetCurrentView().TitleBar; - coreTitleBar.ExtendViewIntoTitleBar = true; - coreTitleBar.LayoutMetricsChanged += CoreTitleBar_LayoutMetricsChanged; - Window.Current.SetTitleBar(Titlebar); - Titlebar.UpdateLayout(); - } - private void CoreTitleBar_LayoutMetricsChanged(CoreApplicationViewTitleBar sender, object args) - { - if (FlowDirection == FlowDirection.LeftToRight) - { - Titlebar.MinWidth = sender.SystemOverlayRightInset; - ShellTitlebarInset.MinWidth = sender.SystemOverlayLeftInset; - } - else - { - Titlebar.MinWidth = sender.SystemOverlayLeftInset; - ShellTitlebarInset.MinWidth = sender.SystemOverlayRightInset; - } - Titlebar.Height = ShellTitlebarInset.Height = sender.Height; + Initialise(); } - //Autosave temp files / AutoBackup Database - //private void AutosaveTempfilesTimer() - //{ - // var BackupTimeInMinutes = appsettings.GetSettingsAsInt("AutoSaveFileTime", DefaultValues.AutoSaveTempFileMinutes); - // if (BackupTimeInMinutes > 0) - // { - // var AutosaveTempfilesTimer = new DispatcherTimer(); - // AutosaveTempfilesTimer.Tick += async delegate - // { - // await tabactions.SaveAllTabChanges(); - // }; - // AutosaveTempfilesTimer.Interval = new TimeSpan(0, 0, BackupTimeInMinutes, 0); - // AutosaveTempfilesTimer.Start(); - // } - //} - private void AutoBackupDataBaseTimer() + //A function, that can be called from anywhere to update the settings + public void ApplySettings() { - var BackupTimeInMinutes = appsettings.GetSettingsAsInt("AutoBackupDatabaseTime", DefaultValues.AutoBackupDataBaseMinutes); - if (BackupTimeInMinutes > 0) - { - var dp = new DispatcherTimer(); - dp.Tick += async delegate - { - await databaseimportexport.CreateDatabaseBackup(); - }; - dp.Interval = new TimeSpan(0, 0, BackupTimeInMinutes, 0); - dp.Start(); - } - } - - //Settings - public async Task SetSettingsToTheme() - { - ThemeHelper.RootTheme = - this.RequestedTheme = - (ElementTheme)Enum.Parse(typeof(ElementTheme), appsettings.GetSettingsAsInt("ThemeIndex", 0).ToString()); - - if (appsettings.GetSettingsAsBool("AutomaticThemeChange", false)) - { - await ChangeDesign(App.Current.RequestedTheme); - } + SettingsUpdater.UpdateSettings(this, tabControl, mainMenubar, statusbar, null); } - public void SetSettingsToTabPage(muxc.TabViewItem Tab, Thickness ContentThickness) + private void Initialise() { - if (tabactions == null || Tab == null) return; - if (tabactions.GetTextBoxFromTabPage(Tab) is TextControlBox textbox) + if (!FirstLoaded) { - if (textbox == null) - return; + FirstLoaded = true; - textbox.ZoomChangedEvent += TextControlBox_ZoomChangedEvent; - textbox.DocumentTitleChangedEvent += TextControlBox_DocumentTitleChangedEvent; - textbox.LineNumberchangedEvent += TextControlBox_LineNumberchangedEvent; - textbox.EncodingChangedEvent += Content_EncodingChangedEvent; - textbox.SaveStatusChangedEvent += Content_SaveStatusChangedEvent; - textbox.WordCountChangedEvent += Textbox_WordCountChangedEvent; - - if (textbox.FontFamily != TextBoxFontfamily) - { - textbox.FontFamily = TextBoxFontfamily; - } + //copy the designs only on first start or when forced by user + DesignHelper.CopyDefaultDesigns(); - if (textbox.TextColor != TextColor) - { - textbox.TextColor = TextColor; - } + //Add all the controls, that need to be hidden when in settings + ControlsToHideInSettings.Add(mainMenubar); + ControlsToHideInSettings.Add(statusbar); - if (textbox.Background != TextBoxBackgroundcolor) - { - textbox.Background = TextBoxBackgroundcolor; - } + //Create additinal controls: + CreateMenubarFromLanguage(); - if (textbox.TextSelectionColor != TextSelectionColor) - { - textbox.TextSelectionColor = TextSelectionColor; - } + titlebarhelper.SetTitlebar(); - if (textbox.LineNumberBackground != LineNumberBackgroundColor) + if (AppSettings.GetSettings(AppSettingsValues.App_FirstStart).Length == 0) { - textbox.LineNumberBackground = LineNumberBackgroundColor; + AppSettings.SaveSettings(AppSettingsValues.App_FirstStart, "L"); + InfoMessages.WelcomeMessage(); } - - if (textbox.LineNumberForeground != LineNumberForegroundColor) - { - textbox.LineNumberForeground = LineNumberForegroundColor; - } - - if (textbox.Margin != ContentThickness) - { - textbox.Margin = ContentThickness; - } - - if(textbox.IsHandWritingEnabled != IsHandWritingEnabled) - { - textbox.IsHandWritingEnabled = IsHandWritingEnabled; - } - - if(textbox.ShowSelectionFlyout != ShowSelectionFlyout) - { - textbox.ShowSelectionFlyout = ShowSelectionFlyout; - } - - textbox.LineHighlighterBackground = LineHighlighterBackground; - textbox.LineHighlighterForeground = LineHighlighterForeground; - textbox.ShowLineNumbers = ShowLineNumbers; - textbox.LineHighlighter = ShowLineHighlighter; - - textbox.FontSizeWithoutZoom = TextBoxFontSize; - textbox.SetFontZoomFactor(textbox._zoomFactor); - textbox.UpdateLayout(); - - //Change the tabicon - //Generate new icon if buffer is null - if (TabPageFontIconSource == null) - { - TabPageFontIconSource = new muxc.FontIconSource - { - FontFamily = new FontFamily("Segoe MDL2 Assets"), - Glyph = appsettings.GetSettingsAsString("TabIconId", DefaultValues.DefaultTabIconId) - }; - Debug.WriteLine(Tab.Name + "=" + TabPageFontIconSource.Glyph); - } - if (textbox.IsReadOnly) - Tab.IconSource = new muxc.SymbolIconSource() { Symbol = Symbol.ProtectedDocument }; - else - Tab.IconSource = TabPageFontIconSource; - - Tab.UpdateLayout(); - } - } - public void ApplySettingsToAllTabPages() - { - //Apply settings to all TabPages - Thickness textboxmargin = TextBoxMargin(); - var TabItems = tabactions.GetTabItems(); - for (int i = 0; i < TabItems.Count; i++) - { - if (TabItems[i] is muxc.TabViewItem Tab) - { - SetSettingsToTabPage(Tab, textboxmargin); - } - } - } - private void SetControlColors() - { - //TextBackgroundColor --> Page1 - TextBoxBackgroundcolor = appsettings.GetSettingsAsColorWithDefault("TextBackgroundColor", DefaultValues.DefaultTextBackgroundColor); - //TitleBarBackgroundColor --> Page4 - TitleBarBackgroundColor = appsettings.GetSettingsAsColorWithDefault("TitleBarBackgroundColor", DefaultValues.DefaultTitleBarBackgroundColor); - //TextColor --> Page1 - TextColor = appsettings.GetSettingsAsColorWithDefault("TextColor", DefaultValues.DefaultTextColor); - //TextSelectionColor --> Page1 - TextSelectionColor = appsettings.GetSettingsAsColorWithDefault("TextSelectionColor", DefaultValues.DefaultTextSelectionColor); - //Tabcolor not focused --> Page4 - TabColorNotFocused = appsettings.GetSettingsAsColorWithDefault("TabColorNotFocused", DefaultValues.DefaultTabColorNotFocused); - //Tab color focused --> Page4 - TabColorFocused = appsettings.GetSettingsAsColorWithDefault("TabColorFocused", DefaultValues.DefaultTabColorFocused); - //LineNumberForeground --> Page1 - LineNumberForegroundColor = appsettings.GetSettingsAsColorWithDefault("LineNumberForegroundColor", DefaultValues.DefaultLineNumberForegroundColor); - //LineNumberBackground --> Page1 - LineNumberBackgroundColor = appsettings.GetSettingsAsColorWithDefault("LineNumberBackgroundColor", DefaultValues.DefaultLineNumberBackgroundColor); - //StatusbarForeground --> Page8 - StatusbarForegroundColor = appsettings.GetSettingsAsColorWithDefault("StatusbarForegroundColor", DefaultValues.DefaultStatusbarForegroundColor); - //StatusbarBackground --> Page8 - StatusbarBackgroundColor = appsettings.GetSettingsAsColorWithDefault("StatusbarBackgroundColor", DefaultValues.DefaultStatusbarBackgroundColor); - //LineHighlighterColor --> Page 1 - LineHighlighterBackground = appsettings.GetSettingsAsColorWithDefault("LineHighlighterBackground", Colors.Transparent); - LineHighlighterForeground = appsettings.GetSettingsAsColorWithDefault("LineHighlighterForeground", DefaultValues.SystemAccentColor); - - //If user wants the text color and line color to be the same - if (appsettings.GetSettingsAsInt("LineNumberForegroundColorIndex", 1) == 1) - { - LineNumberForegroundColor = appsettings.GetSettingsAsColorWithDefault("TextColor", DefaultValues.SystemAccentColorLight2); - } - } - private void SetSettingsToStatusbar() - { - if (ShowStatusBar = appsettings.GetSettingsAsBool("ShowStatusbar", true)) - { - if (!SettingsWindowSelected) - { - Statusbar.Visibility = Visibility.Visible; - } - - if (appsettings.GetSettingsAsBool("StatusbarInBoldFont", false)) - { - LineNumberDisplay.FontWeight = ZoomDisplay.FontWeight = WordCountDisplay.FontWeight = - FileNameDisplay.FontWeight = EncodingDisplay.FontWeight = SaveStatusDisplay.FontWeight - = FontWeights.Bold; - } - else - { - LineNumberDisplay.FontWeight = ZoomDisplay.FontWeight = WordCountDisplay.FontWeight = - FileNameDisplay.FontWeight = EncodingDisplay.FontWeight = SaveStatusDisplay.FontWeight - = FontWeights.Normal; - } - - Statusbar.Background = new SolidColorBrush(StatusbarBackgroundColor); - SaveStatusDisplay.Foreground = WordCountDisplay.Foreground = LineNumberDisplay.Foreground = ZoomDisplay.Foreground = - FileNameDisplay.Foreground = EncodingDisplay.Foreground = - new SolidColorBrush(StatusbarForegroundColor); - - WordCountDisplay.Visibility = Convert.BoolToVisibility(appsettings.GetSettingsAsBool("ShowWordCountButtonOn_SBar", false)); - SaveStatusDisplay.Visibility = Convert.BoolToVisibility(appsettings.GetSettingsAsBool("ShowSaveStatusButtonOn_SBar", true)); - EncodingDisplay.Visibility = Convert.BoolToVisibility(appsettings.GetSettingsAsBool("ShowEncodingButtonOn_SBar", true)); - LineNumberDisplay.Visibility = Convert.BoolToVisibility(appsettings.GetSettingsAsBool("ShowLinenumberButtonOn_SBar", true)); - ZoomDisplay.Visibility = Convert.BoolToVisibility(appsettings.GetSettingsAsBool("ShowZoomButtonOn_SBar", true)); - FileNameDisplay.Visibility = Convert.BoolToVisibility(appsettings.GetSettingsAsBool("ShowRenameButtonOn_SBar", true)); - } - Statusbar.Visibility = Convert.BoolToVisibility(ShowStatusBar); - } - private void SetSettingsToTitlebarButtons() - { - //Check if DropdownMenu is hidden, and when the are show the Settingsbutton in the corner - //Apply dark/light themes to all buttons: - var titlebarbuttonTheme = Convert.ThemeFromColorBrightness(TitleBarBackgroundColor); - - DropDownMenu.Visibility = Convert.BoolToVisibility(appsettings.GetSettingsAsBool("ShowDropdown", true)); - DropDownMenu.RequestedTheme = titlebarbuttonTheme; - - NavigateToPreviousTab.Visibility = Convert.BoolToVisibility(appsettings.GetSettingsAsBool("ShowNavigateToPreviousTab", false)); - NavigateToPreviousTab.RequestedTheme = titlebarbuttonTheme; - - NavigateToNextTab.Visibility = Convert.BoolToVisibility(appsettings.GetSettingsAsBool("ShowNavigateToNextTab", false)); - NavigateToNextTab.RequestedTheme = titlebarbuttonTheme; - } - private void SetSettingsToEditor() - { - //LineHighlighter - ShowLineHighlighter = appsettings.GetSettingsAsBool("LineHighlighter", true); - //LineNumbers - ShowLineNumbers = appsettings.GetSettingsAsBool("ShowLineNumbers", true); - ShowSelectionFlyout = appsettings.GetSettingsAsBool("TextboxShowSelectionFlyout", false); - IsHandWritingEnabled = appsettings.GetSettingsAsBool("HandwritingEnabled", DefaultValues.HandWritingEnabled); - //Get data for Fontsize and Fontfamily and store in local variable to use it in SetSettingsToTabPage function - TextBoxFontfamily = new FontFamily(appsettings.GetSettingsAsString("FontFamily", DefaultValues.DefaultFontFamily)); - TextBoxFontSize = appsettings.GetSettingsAsInt("FontSize", DefaultValues.DefaultFontsize); - } - private void SetSettingsToSearchDialog() - { - SearchReplaceWindowDisplay.Margin = new Thickness(10, 40 + (MainMenuBar != null ? MainMenuBar.Height : 0), 10, 0); - GoToLineWindow.Background = searchdialog.Background = DefaultValues.ContentDialogBackgroundColor(); - - //Align the searchwindow either to the right or in the center - GoToLineWindow.HorizontalAlignment = SearchReplaceWindowDisplay.HorizontalAlignment = - appsettings.GetSettingsAsBool("SearchPanelCenterAlign", true) ? HorizontalAlignment.Center : HorizontalAlignment.Right; - - //Search dialog: - if (appsettings.GetSettingsAsBool("SearchOpen", false)) - searchdialog.Show(""); - else - searchdialog.Close(); - - //Expand the search for replacing: - searchdialog.Replace(!(appsettings.GetSettingsAsInt("SearchExpanded", 1) == 1)); - } - private void SetSettingsToTabControl() - { - Color UnselectedTabViewItemColor; - - if (appsettings.GetSettingsAsBool("UseMica", false)) - { - TextTabControl.Background = new SolidColorBrush(Colors.Transparent); - UnselectedTabViewItemColor = Convert.GetColorFromThemeReversed(ThemeHelper.RootTheme); - } - else - { - TextTabControl.Background = appsettings.CreateBrushWithOrWithoutAcrylic(TitleBarBackgroundColor); - UnselectedTabViewItemColor = Convert.WhiteOrBlackFromColorBrightness(TabColorNotFocused.A > 50 ? TabColorNotFocused : TitleBarBackgroundColor); - } - - //Set the Icon for the tabpage: - TabPageFontIconSource = new muxc.FontIconSource - { - FontFamily = new FontFamily("Segoe MDL2 Assets"), - Glyph = appsettings.GetSettingsAsString("TabIconId", DefaultValues.DefaultTabIconId) - }; - - TextTabControl.RequestedTheme = Convert.ThemeFromColorBrightness(TitleBarBackgroundColor); - (TextTabControl.Resources["TabViewItemHeaderBackground"] as SolidColorBrush).Color = TabColorNotFocused; - (TextTabControl.Resources["TabViewItemHeaderBackgroundSelected"] as SolidColorBrush).Color = TabColorFocused; - (TextTabControl.Resources["TabViewItemHeaderForeground"] as SolidColorBrush).Color = UnselectedTabViewItemColor; - (TextTabControl.Resources["TabViewItemHeaderForegroundSelected"] as SolidColorBrush).Color = Convert.WhiteOrBlackFromColorBrightness(TabColorFocused); - UnderTabControlLine.Background = new SolidColorBrush(TabColorFocused); - UnderTabControlLine.Visibility = Convert.BoolToVisibility(appsettings.GetSettingsAsBool("ShowUnderTabLine", true)); - TextTabControl.TabWidthMode = - (muxc.TabViewWidthMode)Enum.Parse(typeof(muxc.TabViewWidthMode), - appsettings.GetSettingsAsString("TabSizeModeIndex", DefaultValues.defaultTabSizeMode.ToString())); - - TextTabControl.Margin = new Thickness(0, 0, 0, Statusbar.Visibility == Visibility.Collapsed && !SettingsWindowSelected ? 0 : Statusbar.Height); - TextTabControl.UpdateLayout(); - } - private void SetSettingsToMenubar() - { - ShowMenubar = appsettings.GetSettingsAsBool("ShowMenubar", true); - if(ShowMenubar) - { - int index = appsettings.GetSettingsAsInt("MenuBarAlignment", 1); - if (index > 2 || index < 0) - index = 0; - - MainMenuBar.HorizontalAlignment = (HorizontalAlignment)Enum.Parse(typeof(HorizontalAlignment), index.ToString()); - } - } - public async Task SetSettings(bool ApplyToAllTabPages = true) - { - try - { - //Set the theme and do the automatic theme change - await SetSettingsToTheme(); - - //App-Background: - BackgroundHelper.SetBackgroundToPage(this); - - //Application Language - Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = appsettings.GetSettingsAsString("AppLanguage", "en-US"); - - //Load the colors for the controls from settings, right at the beginning - SetControlColors(); - - //Menubar - SetSettingsToMenubar(); - - //Statusbar - SetSettingsToStatusbar(); - - //Tabcontrol - SetSettingsToTabControl(); - - SetSettingsToTitlebarButtons(); - - SetSettingsToEditor(); - - //Spellcheckingbutton - DropDownMenu_SpellChecking.IsChecked = appsettings.GetSettingsAsBool("Spellchecking", DefaultValues.SpellCheckingEnabled); - - //Fullscreenbutton - Utilities.FullScreen(appsettings.GetSettingsAsBool("FullScreen", false), appsettings); - - //Searchdialog - SetSettingsToSearchDialog(); - - //Set settings to secondary views - await secondaryeditinginstance.ApplySettingToAllViews(); - - if (ApplyToAllTabPages) - { - ApplySettingsToAllTabPages(); - } - - TextTabControl_SelectionChanged(null, null); - SetTitlebar(); - } - catch (Exception e) - { - Debug.WriteLine("EXCEPTION in Mainpage -> SetSettings\n" + e.StackTrace); - ShowInfobar(ErrorDialogs.LoadSettingsError(e)); - } - } - public Thickness TextBoxMargin() - { - return new Thickness( - 0, - UnderTabControlLine.Height + (ShowMenubar ? (MainMenuBar.ActualHeight == 0 ? MainMenuBar.Height : MainMenuBar.ActualHeight) : 0), - 0, - 0 - ); - } - - /// - ///Used for the keyevent if the ESC-Key is pressed. Hides the flyout if it is open - /// - private void HideFlyoutIfOpened(Flyout flyout) - { - if (flyout.IsOpen) - { - flyout.Hide(); - } - } - private bool IsControlNOTNull(object Control) - { - return Control != null; - } - private void SetTitlebarText(string title) - { - ApplicationView.GetForCurrentView().Title = title; - } - public muxc.InfoBar ShowInfobar(string Content = "", string Title = "", muxc.InfoBarSeverity severity = muxc.InfoBarSeverity.Warning, int VisibilityTime = 5, object content = null) - { - var MainInformationInfobar = new muxc.InfoBar - { - Severity = severity, - Title = Title, - Message = Content, - IsOpen = true, - Content = content, - Margin = new Thickness(0, 0, 0, 5), - Name = "Infobar" + InfoBarDisplay.Children.Count - }; - var HideInfobarTimer = new DispatcherTimer(); - HideInfobarTimer.Interval = TimeSpan.FromSeconds(VisibilityTime); - HideInfobarTimer.Tick += delegate - { - MainInformationInfobar.IsOpen = false; - InfoBarDisplay.Children.Remove(MainInformationInfobar); - - HideInfobarTimer.Stop(); - InfoBarDisplay.UpdateLayout(); - }; - HideInfobarTimer.Start(); - InfoBarDisplay.Children.Add(MainInformationInfobar); - return MainInformationInfobar; - } - public muxc.InfoBar ShowInfobar(muxc.InfoBar infobar, int VisibilityTime = 5) - { - if (infobar.Margin.Bottom != 5) - infobar.Margin = new Thickness(0, 0, 0, 5); - - infobar.Name = "Infobar" + InfoBarDisplay.Children.Count; - var HideInfobarTimer = new DispatcherTimer(); - HideInfobarTimer.Interval = TimeSpan.FromSeconds(VisibilityTime); - HideInfobarTimer.Tick += delegate - { - infobar.IsOpen = false; - InfoBarDisplay.Children.Remove(infobar); - - HideInfobarTimer.Stop(); - InfoBarDisplay.UpdateLayout(); - }; - HideInfobarTimer.Start(); - InfoBarDisplay.Children.Add(infobar); - return infobar; - } - private bool IsOnNewVersion() - { - string version = Package.Current.Id.Version.Major + "." + - Package.Current.Id.Version.Minor + "." + - Package.Current.Id.Version.Build; - if (version != appsettings.GetSettings("AppVersion")) - { - appsettings.SaveSettings("AppVersion", version); - return true; - } - return false; - } - private void ShowNewVersionInfobar() - { - if (NewVersionInfobar == null) - NewVersionInfobar = FindName("NewVersionInfobar") as muxc.InfoBar; - - NewVersionInfobar.Background = DefaultValues.ContentDialogBackgroundColor(); - NewVersionInfobar.Foreground = DefaultValues.ContentDialogForegroundColor(); - NewVersionInfobar.Closed += delegate - { - if(NewVersionInfobar != null) - UnloadObject(NewVersionInfobar); - }; - string version = Package.Current.Id.Version.Major + "." + - Package.Current.Id.Version.Minor + "." + - Package.Current.Id.Version.Build; - NewVersionInfobar.Message = $"{appsettings.GetResourceString("InfoBarMessage_NewVersion_Text1/Text")} {version}"; - NewVersionInfobar.IsOpen = true; - } - private void ShowHideControlsOnSelectionChanged(bool isEnabled) - { - //DropDownMenu: - if (DropDownMenu.Visibility == Visibility.Visible) - { - for (int i = 0; i < ToolbarFlyout.Items.Count; i++) - { - if (ToolbarFlyout.Items[i] is MenuFlyoutItem item) - { - if (item.Tag is string str && str.Equals("HideIfNoTab", StringComparison.Ordinal)) - { - item.IsEnabled = isEnabled; - } - } - if (ToolbarFlyout.Items[i] is MenuFlyoutSubItem subitem) - { - if (subitem.Tag is string str && str.Equals("HideIfNoTab", StringComparison.Ordinal)) - { - subitem.IsEnabled = isEnabled; - } - } - } - } - //Menubar: - if (!ShowMenubar) - return; - for (int i = 0; i < MainMenuBar.Items.Count; i++) - { - if (MainMenuBar.Items[i] is MenuBarItem mbitem) - { - if (mbitem.Tag is string str && str.Equals("HideIfNoTab", StringComparison.Ordinal)) - { - mbitem.IsEnabled = isEnabled; - } - else - { - for (int j = 0; j < mbitem.Items.Count; j++) - { - if (mbitem.Items[j] is MenuFlyoutItem mfi) - { - if (mfi.Tag is string str2 && str2.Equals("HideIfNoTab", StringComparison.Ordinal)) - { - mfi.IsEnabled = isEnabled; - } - } - else if (mbitem.Items[j] is ToggleMenuFlyoutItem tmfi) - { - if (tmfi.Tag is string str2 && str2.Equals("HideIfNoTab", StringComparison.Ordinal)) - { - tmfi.IsEnabled = isEnabled; - } - } - } - } - } - } - } - - //Drag-Drop - private async Task OpenStorageFiles(IReadOnlyList StorageItems, TabSaveMode savemode = TabSaveMode.SaveAsDragDrop) - { - bool result = false; - Thickness textboxmargin = TextBoxMargin(); - for (int i = 0; i < StorageItems.Count; i++) - { - if (StorageItems[i] is StorageFile file) - { - if (tabactions.GetTabItemCount() == 1) - { - if (TextTabControl.TabItems[0] is muxc.TabViewItem tab) - { - //override first created tab, only if it is emty - if (tabpagehelper.GetIsModified(tab) == false && tabpagehelper.GetTabText(tab).Length == 0 && tabpagehelper.GetTabFilepath(tab).Length == 0) - { - await tabactions.RemoveTab(tab); - } - } - } - var (Succed, TabPage) = await tabactions.DoOpenFile(null, file, savemode, false, false, "", false, true, true); - if (Succed == true) - SetSettingsToTabPage(TabPage, textboxmargin); - else - result = false; - } - } - if (await tabactions.SaveAllTabChanges() == false) - result = false; - TextTabControl_SelectionChanged(null, null); - return result; - } - public async Task DropFile(object sender, DragEventArgs e) - { - try - { - if (e.DataView.Contains(StandardDataFormats.Text)) - { - if (CurrentlySelectedTabPage_Textbox != null) - { - CurrentlySelectedTabPage_Textbox.SelectedText = await e.DataView.GetTextAsync(); - } - } - if (e.DataView.Contains(StandardDataFormats.StorageItems)) - { - var items = await e.DataView.GetStorageItemsAsync(); - await OpenStorageFiles(items); - } - } - catch (Exception exception) - { - ShowInfobar(appsettings.GetResourceString("ErrorDialogs_DragDropError/Text") + "\n" + exception.Message, appsettings.GetResourceString("ErrorDialogs_Header_Error.Text"), muxc.InfoBarSeverity.Error); - } - } - public new void DragOver(DragEventArgs e) - { - e.AcceptedOperation = DataPackageOperation.Copy; - - if (e.DragUIOverride != null) - { - e.DragUIOverride.Caption = "Open"; - e.DragUIOverride.SetContentFromSoftwareBitmap(new Windows.Graphics.Imaging.SoftwareBitmap(Windows.Graphics.Imaging.BitmapPixelFormat.Rgba8, 400, 400)); - e.DragUIOverride.IsContentVisible = true; - } - } - - //Dialogs: - public async void ShowEncodingDialog() - { - if (CurrentlySelectedTabPage != null) - { - await new EncodingDialog(CurrentlySelectedTabPage).ShowDialog(); - } - } - public async void ShowRecyclebinDialog() - { - await new RecyclebinWindow(tabactions).ShowDialog(); - } - private async void ShowFileInfoDialog() - { - if (CurrentlySelectedTabPage != null) - { - await new FileInfoDialog(CurrentlySelectedTabPage).ShowAsync(); - } - } - private bool IsContentDialogOpen() - { - var openedpopups = VisualTreeHelper.GetOpenPopups(Window.Current); - for (int i = 0; i < openedpopups.Count; i++) - { - if (openedpopups[i].Child is ContentDialog) - { - return true; - } - } - return false; - } - - public async void CloseSettingsTabPage() - { - if (SettingsTabPage != null) - { - TextTabControl.TabItems.Remove(SettingsTabPage); - tabactions.SettingsTabPage = null; - SettingsWindowSelected = false; - await SetSettings(); - } - } - public void ShowSettingsTabPage(string tabforpage = "") - { - //Create only if null otherwise select it - if (SettingsTabPage == null) - { - var frame = new Frame - { - HorizontalAlignment = HorizontalAlignment.Stretch, - VerticalAlignment = VerticalAlignment.Stretch - }; - frame.Navigate(typeof(SettingsPage), new SettingsNavigationParameter { Mainpage = this, Tabcontrol = TextTabControl, PageToNavigateTo = tabforpage }); - tabactions.SettingsTabPage = SettingsTabPage = new muxc.TabViewItem - { - Content = frame, - Header = "Settings", - Tag = "Settings", - IconSource = new muxc.SymbolIconSource { Symbol = Symbol.Setting } - }; - } - if(!TextTabControl.TabItems.Contains(SettingsTabPage)) - TextTabControl.TabItems.Add(SettingsTabPage); - TextTabControl.SelectedItem = SettingsTabPage; - } - public void ScrollToSelectedTabPage() - { - tabviewlistview.ScrollIntoView(TextTabControl.SelectedItem); - } - - //Actions - private void Copy_Action() - { - if (CurrentlySelectedTabPage_Textbox != null) - { - CurrentlySelectedTabPage_Textbox.Copy(); - } - } - private void Cut_Action() - { - if (CurrentlySelectedTabPage_Textbox != null) - { - CurrentlySelectedTabPage_Textbox.Cut(); - } - } - private void Paste_Action() - { - if (CurrentlySelectedTabPage != null && CurrentlySelectedTabPage_Textbox != null) - { - if (tabpagehelper.GetTabReadOnly(CurrentlySelectedTabPage) == false) - { - CurrentlySelectedTabPage_Textbox.Paste(); - } - } - } - private void Redo_Action() - { - if (CurrentlySelectedTabPage != null) - { - if (tabpagehelper.GetTabReadOnly(CurrentlySelectedTabPage) == false) - { - CurrentlySelectedTabPage_Textbox.Redo(); - } - } - } - private void Undo_Action() - { - if (CurrentlySelectedTabPage != null) - { - if (tabpagehelper.GetTabReadOnly(CurrentlySelectedTabPage) == false) - { - CurrentlySelectedTabPage_Textbox.Undo(); - } - } - } - private async void Save_Action() - { - if (CurrentlySelectedTabPage != null) - { - await savefilehelper.Save(CurrentlySelectedTabPage); - } - } - private async void Open_Action() - { - - var tabs = await tabactions.OpenFile(); - if (tabs != null) - { - for (int i = 0; i < tabs.Count; i++) - { - if (tabs[i] != null) - { - SetSettingsToTabPage(tabs[i], TextBoxMargin()); - } - } - } - } - private async void SaveAs_Action() - { - if (CurrentlySelectedTabPage != null) - { - await savefilehelper.SaveFileAs(CurrentlySelectedTabPage); } + ApplySettings(); } - private void SelectAll_Action() + private void CreateMenubarFromLanguage() { - if (CurrentlySelectedTabPage_Textbox != null) + //items already added + if (CodeLanguageSelector.Items.Count > 1) + return; + + foreach (var item in TextControlBox.TextControlBox.CodeLanguages) { - CurrentlySelectedTabPage_Textbox.SelectAll(); + var menuItem = new MenuFlyoutItem + { + Text = item.Value.Name, + Tag = item.Key, + }; + menuItem.Click += CodeLanguage_Click; + CodeLanguageSelector.Items.Add(menuItem); + + var runCommandWindowItem = new RunCommandWindowItem + { + Command = item.Value.Name, + Tag = item.Key, + }; + runCommandWindowItem.RunCommandWindowItemClicked += CodeLanguage_Click; + RunCommandWindowItem_CodeLanguages.Items.Add(runCommandWindowItem); } - } - private void WordWrap_Action() - { - if (CurrentlySelectedTabPage_Textbox != null) + + var noneItem = new MenuFlyoutItem { - CurrentlySelectedTabPage_Textbox.WordWrap = - CurrentlySelectedTabPage_Textbox.WordWrap == TextWrapping.Wrap ? TextWrapping.NoWrap : TextWrapping.Wrap; - } + Text = "None", + Tag = "", + }; + noneItem.Click += CodeLanguage_Click; + CodeLanguageSelector.Items.Add(noneItem); + + var noneCmdWindowItem = new RunCommandWindowItem + { + Command = "None", + Tag = "", + }; + noneCmdWindowItem.RunCommandWindowItemClicked += CodeLanguage_Click; + RunCommandWindowItem_CodeLanguages.Items.Add(noneCmdWindowItem); } - private async void Encoding_Action() + public void UpdateStatubar() { - if (CurrentlySelectedTabPage != null) - { - await new EncodingDialog(CurrentlySelectedTabPage).ShowDialog(); - } + if (currentlySelectedTabPage == null || statusbar.Visibility == Visibility.Collapsed) + return; + + Statusbar_Column.ChangingText = currentlySelectedTabPage.textbox.CursorPosition.CharacterPosition.ToString(); + Statusbar_Line.ChangingText = (currentlySelectedTabPage.textbox.CursorPosition.LineNumber + 1).ToString(); + Statusbar_FilePath.ChangingText = currentlySelectedTabPage.DatabaseItem.FileName.ToString(); + Statusbar_Zoom.ChangingText = currentlySelectedTabPage.textbox.ZoomFactor + "%"; + Statusbar_Encoding.ChangingText = EncodingHelper.GetEncodingName(currentlySelectedTabPage.Encoding); } - private void ZoomIn_Action() + public void SelectedTabChanged() { - if (CurrentlySelectedTabPage != null) - { - tabpagehelper.ZoomIn(CurrentlySelectedTabPage); - } + TabView_SelectionChanged(tabControl, null); } - private void ZoomOut_Action() + public void ChangeSelectedTab(TabPageItem tab) { - if (CurrentlySelectedTabPage != null) - { - tabpagehelper.ZoomOut(CurrentlySelectedTabPage); - } + tabControl.SelectedItem = tab; } - private void SearchWindow_Action() + public async Task SaveDatabase(bool ShowProgress = true) { - if (!searchdialog.SearchIsOpen && CurrentlySelectedTabPage_Textbox != null) - { - searchdialog.Show(CurrentlySelectedTabPage_Textbox.SelectedText); - searchdialog.Replace(false); - } - else - { - searchdialog.Close(); - } + await TabPageHelper.SaveTabDatabase(tabdatabase, tabControl, ShowProgress ? progressWindow : null); } - private void Share_Action() + public void ShowSettings(string page = null) { - if (CurrentlySelectedTabPage_Textbox != null) - { - new ShareFile(CurrentlySelectedTabPage_Textbox); - } + SettingsTabPageHelper.OpenSettings(this, tabControl, page); } - private void SpellChecking_Action() + + protected async override void OnNavigatedTo(NavigationEventArgs e) { - var tabitems = tabactions.GetTabItems(); - for (int i = 0; i < tabitems.Count; i++) + //Save back the value and read from it after all tabs are loaded + AppActivationHelper.NavigationEvent = e; + + //handle activation from files and commandline after the tabs are already loaded + if (TabsLoaded) { - if (tabitems[i] is muxc.TabViewItem Tab) - { - if (Tab.Content is TextControlBox textbox) - { - textbox.SpellChecking = !textbox.SpellChecking; - appsettings.SaveSettings("Spellchecking", textbox.SpellChecking); - } - } + await AppActivationHelper.HandleAppActivation(tabControl); } + + base.OnNavigatedTo(e); } - private void NavigateToNextTab_Action() + private async void tabControl_TabDragStarting(TabView sender, TabViewTabDragStartingEventArgs args) { - tabactions.SelectNextTab(); + if (currentlySelectedTabPage == null) + return; + + await SaveFileHelper.DragFileToPath(currentlySelectedTabPage, args); } - private void NavigateToPreviousTab_Action() + private void SettingsUpdater_SettingsTabClosed() { - tabactions.SelectPreviousTab(); + //Event when the settings page got closed + ApplySettings(); } - private void DuplicateLine_Action() + private async void MainPage_CloseRequested(object sender, SystemNavigationCloseRequestedPreviewEventArgs e) { - if (CurrentlySelectedTabPage_Textbox != null) - { - CurrentlySelectedTabPage_Textbox.DuplicateLine(); - } + var deferral = e.GetDeferral(); + + await SaveDatabase(); + + deferral.Complete(); } - public void NewTab_Action() + private async void CustomDragRegion_Loaded(object sender, RoutedEventArgs e) { - muxc.TabViewItem tab = tabactions.NewTab(); - newTabSaveTime.Tick += async delegate - { - await tabactions.SaveAllTabChanges(); - newTabSaveTime.Stop(); - }; - newTabSaveTime.Interval = new TimeSpan(0, 0, 0, 0, 1000); - newTabSaveTime.Start(); - if (tab != null) + if (!TabsLoaded) { - SetSettingsToTabPage(tab, TextBoxMargin()); + TabsLoaded = true; + + progressBar.IsActive = true; + + //load the database + await TabPageHelper.LoadTabDatabase(tabControl, tabdatabase); + + //handle activation from files and commandline on start + await AppActivationHelper.HandleAppActivation(tabControl); + + //apply the settings + SettingsUpdater.UpdateSettings(this, tabControl, mainMenubar, statusbar, DesignHelper.CurrentDesign); + + //Show new-version info + VersionHelper.CheckNewVersion(infobarDisplay); + + progressBar.IsActive = false; } } - private void OpenSettings_Action() - { - ShowSettingsTabPage(); - } - private async void CloseSelectedTab_SaveDatabase() + private void CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args) { - if (tabactions.GetTextBoxFromTabPage(CurrentlySelectedTabPage) != null) - { - await tabactions.CloseTabAndSaveDataBase(CurrentlySelectedTabPage); - } - else if (SettingsWindowSelected) + var ctrl = Window.Current.CoreWindow.GetKeyState(Windows.System.VirtualKey.Control).HasFlag(Windows.UI.Core.CoreVirtualKeyStates.Down); + var shift = Window.Current.CoreWindow.GetKeyState(Windows.System.VirtualKey.Shift).HasFlag(Windows.UI.Core.CoreVirtualKeyStates.Down); + + if (ctrl && args.VirtualKey == Windows.System.VirtualKey.Tab) + TabPageHelper.SelectNextTab(tabControl); + else if (ctrl && shift && args.VirtualKey == Windows.System.VirtualKey.Tab) + TabPageHelper.SelectPreviousTab(tabControl); + + if (ctrl) { - CloseSettingsTabPage(); + switch (args.VirtualKey) + { + case VirtualKey.N: + NewFile_Click(null, null); + break; + case VirtualKey.O: + OpenFile_Click(null, null); + break; + case VirtualKey.S: + if (shift) + SaveFileAs_Click(null, null); + else + SaveFile_Click(null, null); + break; + case VirtualKey.F: + Search_Click(null, null); + break; + case VirtualKey.R: + Replace_Click(null, null); + break; + case VirtualKey.G: + GoToLine_Click(null, null); + break; + case VirtualKey.Add: + ZoomIn_Click(null, null); + break; + case VirtualKey.Subtract: + ZoomOut_Click(null, null); + break; + case VirtualKey.I: + FileInfo_Click(null, null); + break; + case VirtualKey.B: + runCommandWindow.Toggle(tabControl); + break; + case VirtualKey.W: + CloseTab_Click(null, null); + break; + case VirtualKey.T: + AddTabButton_Click(null, null); + break; + case VirtualKey.E: + ChangeEncoding_Click(null, null); + break; + case VirtualKey.L: + ShowTabInNewWindow_Click(null, null); + break; + case VirtualKey.K: + CompactOverlayMode_Click(null, null); + break; + case VirtualKey.D: + DuplicateLine_Click(null, null); + break; + } } - //Create a new tab when no tab exists - if(tabactions.GetTabItemCount() == 0) + + switch (args.VirtualKey) { - NewTab_Action(); + case VirtualKey.F1: + Settings_Click(null, null); + break; + case VirtualKey.F11: + Fullscreen_Click(null, null); + break; } } - private async void ExpandTabToNewWindow_Action() + + //TabControl + private void AddTabButton_Click(Microsoft.UI.Xaml.Controls.SplitButton sender, Microsoft.UI.Xaml.Controls.SplitButtonClickEventArgs args) { - if (CurrentlySelectedTabPage != null) - await secondaryeditinginstance.ExpandTabPageToNewView(CurrentlySelectedTabPage); + TabPageHelper.AddNewTab(tabControl, true); } - private void Fullscreen_Action() + private async void TabView_CloseTabButtonClick(TabView sender, TabViewTabCloseRequestedEventArgs args) { - Utilities.ToggleFullscreen(appsettings); + await TabPageHelper.CloseTab(tabControl, args.Item); } - private void ToggleMarkdown_Action() + private async void TabView_SelectionChanged(object sender, SelectionChangedEventArgs e) { - if (CurrentlySelectedTabPage != null && CurrentlySelectedTabPage_Textbox != null) + if (tabControl.SelectedItem is TabPageItem tab) { - CurrentlySelectedTabPage_Textbox.MarkdownPreview = !CurrentlySelectedTabPage_Textbox.MarkdownPreview; + currentlySelectedTabPage = tab; + if (tab == null) + return; + + SettingsTabPageHelper.SettingsSelected = false; + + UpdateStatubar(); + + //set the focus to the textbox: + tab.textbox.Focus(FocusState.Programmatic); + + await TabPageHelper.LoadUnloadedTab(tab, progressWindow); } - } - private void SurroundWithText_Action() - { - if (CurrentlySelectedTabPage_Textbox == null) + else if (SettingsTabPageHelper.IsSettingsPage(tabControl.SelectedItem)) + { + SettingsTabPageHelper.SettingsSelected = true; + SettingsTabPageHelper.HideControls(); return; - //reset to default state - SurroundWith_Textbox2.Visibility = Visibility.Collapsed; - SurroundWith_Textbox1.Text = SurroundWith_Textbox2.Text = ""; - var rect = CurrentlySelectedTabPage_Textbox.GetSelectionRect(); + } - SurroundWithFlyout.ShowAt( - CurrentlySelectedTabPage_Textbox, - new FlyoutShowOptions { - Position = new Point { X = rect.X + (rect.Width / 2) + 20, Y = rect.Y + (rect.Height / 2) - 40 - CurrentlySelectedTabPage_Textbox.GetScrollbarPositions().ScrollbarPositionVertical}, - Placement = FlyoutPlacementMode.Auto} - ); - SurroundWith_Textbox1.Focus(FocusState.Programmatic); - } - private void LockTab_Action() - { - if(CurrentlySelectedTabPage != null) + //show hidden controls + if (!SettingsTabPageHelper.SettingsSelected) { - tabpagehelper.SetTabReadOnly(CurrentlySelectedTabPage, !tabpagehelper.GetTabReadOnly(CurrentlySelectedTabPage)); + SettingsUpdater.SetControlsVisibility(tabControl, mainMenubar, statusbar); } } - //Click-Events - private void NewDocumentButton(object sender, RoutedEventArgs e) - { - NewTab_Action(); - } - private void SaveFileButton(object sender, RoutedEventArgs e) - { - Save_Action(); - } - private void Save_Click(object sender, PointerRoutedEventArgs e) + //Drag drop + private async void Page_Drop(object sender, DragEventArgs e) { - Save_Action(); - } - private void UndoButton(object sender, RoutedEventArgs e) - { - Undo_Action(); - } - private void RedoButton(object sender, RoutedEventArgs e) - { - Redo_Action(); - } - private void CutButton(object sender, RoutedEventArgs e) - { - Cut_Action(); - } - private void CopyButton(object sender, RoutedEventArgs e) - { - Copy_Action(); - } - private void PasteButton(object sender, RoutedEventArgs e) - { - Paste_Action(); - } - public void Settingsbutton(object sender, RoutedEventArgs e) - { - OpenSettings_Action(); - } - private void OpenFileButton(object sender, RoutedEventArgs e) - { - Open_Action(); - } - private void SaveAsAppBarButtonName_Click(object sender, RoutedEventArgs e) - { - SaveAs_Action(); - } - private void SelectAllAppBarButtonName_Click(object sender, RoutedEventArgs e) - { - SelectAll_Action(); - } - private void WordWrapButton_Click(object sender, RoutedEventArgs e) - { - WordWrap_Action(); - } - private void EncodingAppBarButtonName_Click(object sender, RoutedEventArgs e) - { - Encoding_Action(); - } - private void FullScreenButton_Click(object sender, RoutedEventArgs e) - { - Fullscreen_Action(); - } - private void ZoomInAppBarButtonName_Click(object sender, RoutedEventArgs e) - { - ZoomIn_Action(); - } - private void ZoomOutAppBarButtonName_Click(object sender, RoutedEventArgs e) - { - ZoomOut_Action(); + if (e.DataView.Contains(StandardDataFormats.StorageItems)) + { + var files = await e.DataView.GetStorageItemsAsync(); + await TabPageHelper.OpenFiles(tabControl, files); + } } - private void SearchAppBarButtonName_Click(object sender, RoutedEventArgs e) + private void Page_DragOver(object sender, DragEventArgs e) { - SearchWindow_Action(); + //only accept files + if (e.DataView.Contains(StandardDataFormats.StorageItems)) + { + e.AcceptedOperation = DataPackageOperation.Copy; + } } - private void ShareAppBarButtonName_Click(object sender, RoutedEventArgs e) + + //File + private void NewFile_Click(object sender, RoutedEventArgs e) { - Share_Action(); + TabPageHelper.AddNewTab(tabControl, true); } - private void SpellcheckingButton_Click(object sender, RoutedEventArgs e) + private async void OpenFile_Click(object sender, RoutedEventArgs e) { - SpellChecking_Action(); + await TabPageHelper.OpenFile(tabControl); } - private void GoToLineButton_Click(object sender, RoutedEventArgs e) + private async void SaveFile_Click(object sender, RoutedEventArgs e) { - ShowGoToLineWindow(); + await TabPageHelper.SaveFile(currentlySelectedTabPage); } - private void FileInfoButton_Click(object sender, RoutedEventArgs e) + private async void SaveFileAs_Click(object sender, RoutedEventArgs e) { - ShowFileInfoDialog(); + await TabPageHelper.SaveFileAs(currentlySelectedTabPage); } - private void RecycleBin_Click(object sender, RoutedEventArgs e) + private void Settings_Click(object sender, RoutedEventArgs e) { - ShowRecyclebinDialog(); - ApplySettingsToAllTabPages(); + SettingsTabPageHelper.OpenSettings(this, tabControl); } - private void NavigateToPreviousTab_Click(object sender, RoutedEventArgs e) + private async void RecycleBin_Click(object sender, RoutedEventArgs e) { - NavigateToPreviousTab_Action(); + await new RecycleBinDialog(tabControl).ShowDialog(); } - private void NavigateToNextTab_Click(object sender, RoutedEventArgs e) + //Edit + private void Undo_Click(object sender, RoutedEventArgs e) { - NavigateToNextTab_Action(); + EditActions.Undo(currentlySelectedTabPage); } - private void ViewChangelog_Click(object sender, RoutedEventArgs e) + private void Redo_Click(object sender, RoutedEventArgs e) { - ShowSettingsTabPage("Changelog"); + EditActions.Redo(currentlySelectedTabPage); } - private void CloseTab_Click(object sender, RoutedEventArgs e) + private void Cut_Click(object sender, RoutedEventArgs e) { - CloseSelectedTab_SaveDatabase(); + EditActions.Cut(currentlySelectedTabPage); } - private void MarkdownPreview_Click(object sender, RoutedEventArgs e) + private void Copy_Click(object sender, RoutedEventArgs e) { - ToggleMarkdown_Action(); + EditActions.Copy(currentlySelectedTabPage); } - private void LockTab_Click(object sender, RoutedEventArgs e) + private void Paste_Click(object sender, RoutedEventArgs e) { - LockTab_Action(); + EditActions.Paste(currentlySelectedTabPage); } - private async void Close_Click(object sender, RoutedEventArgs e) + private void SelectAll_Click(object sender, RoutedEventArgs e) { - if (sender is MenuFlyoutItem item && CurrentlySelectedTabPage != null) - { - switch (Convert.ToInt(item.Tag)) - { - case 0: - await tabactions.CloseAllTabs(); - break; - case 1: - await tabactions.CloseAllLeft(CurrentlySelectedTabPage); - break; - case 2: - await tabactions.CloseAllRight(CurrentlySelectedTabPage); - break; - case 3: - await tabactions.CloseAllButThis(CurrentlySelectedTabPage); - break; - case 4: - await tabactions.CloseAllWithoutSave(); - break; - } - } + EditActions.SelectAll(currentlySelectedTabPage); } - private void OpenInNewView_Click(object sender, RoutedEventArgs e) + private void DuplicateLine_Click(object sender, RoutedEventArgs e) { - ExpandTabToNewWindow_Action(); + EditActions.DuplicateLine(currentlySelectedTabPage); } - private async void FormatCode_Click(object sender, RoutedEventArgs e) + private void CodeLanguage_Click(object sender, RoutedEventArgs e) { - if (CurrentlySelectedTabPage_Textbox == null) + if (currentlySelectedTabPage == null) return; if (sender is MenuFlyoutItem item) { - string text = CurrentlySelectedTabPage_Textbox.GetText(); - switch (Convert.ToInt(item.Tag, 0)) + if (item != null && item.Tag != null) { - case 0: //Json - text = CodeFormatter.FormatJson(text); - break; - case 1: //Xml - var res = CodeFormatter.FormatXml(text, out string output); - if (res != null) - ShowInfobar(res.Message, "Could not format you code:", InfoBarSeverity.Error); - else - text = output; - break; - case 2: //C# - text = CodeFormatter.FormatCs(text); - break; + if (item.Tag.ToString().Length == 0) + currentlySelectedTabPage.CodeLanguage = null; + + currentlySelectedTabPage.CodeLanguage = TextControlBox.TextControlBox.GetCodeLanguageFromId(item.Tag.ToString()); } - await CurrentlySelectedTabPage_Textbox.ChangeText(text); } - } - private void SurroundWith_Click(object sender, RoutedEventArgs e) - { - SurroundWithText_Action(); - } - private void SurroundWith_Textbox_KeyDown(object sender, KeyRoutedEventArgs e) - { - if (sender is TextBox tb) + else if (sender is RunCommandWindowItem rcwitem) { - if (tb.Name == SurroundWith_Textbox1.Name) - { - if (e.Key == VirtualKey.Enter) - { - CurrentlySelectedTabPage_Textbox.SurroundSelectionBy(SurroundWith_Textbox1.Text); - SurroundWithFlyout.Hide(); - } - else if (e.Key == VirtualKey.Tab) - { - SurroundWith_Textbox2.Visibility = Visibility.Visible; - } - } - else if (tb.Name == SurroundWith_Textbox2.Name) + if (rcwitem != null && rcwitem.Tag != null) { - if (e.Key == VirtualKey.Enter) - { - CurrentlySelectedTabPage_Textbox.SurroundSelectionBy(SurroundWith_Textbox1.Text, SurroundWith_Textbox2.Text); - SurroundWithFlyout.Hide(); - } + if (rcwitem.Tag.ToString().Length == 0) + currentlySelectedTabPage.CodeLanguage = null; + + currentlySelectedTabPage.CodeLanguage = TextControlBox.TextControlBox.GetCodeLanguageFromId(rcwitem.Tag.ToString()); } } } - private void DuplicateLine_Click(object sender, RoutedEventArgs e) + private void Search_Click(object sender, RoutedEventArgs e) { - if (CurrentlySelectedTabPage_Textbox != null) - CurrentlySelectedTabPage_Textbox.DuplicateLine(); + searchControl.ShowSearch(currentlySelectedTabPage.textbox); } - - - //Search-Dialog - private void ExpandSearchBoxForReplaceButton_Click(object sender, RoutedEventArgs e) + private void Replace_Click(object sender, RoutedEventArgs e) { - searchdialog.Show(); - searchdialog.Replace(appsettings.GetSettingsAsInt("SearchExpanded", 0) == 1); + searchControl.ShowReplace(currentlySelectedTabPage.textbox); } - - //Go to line dialog - private bool GoToLineWindowIsOpen { get => GoToLineWindow.Visibility == Visibility.Visible; set { GoToLineWindow.Visibility = Convert.BoolToVisibility(value); } } - private void CloseGoToLineDialog() + private async void GoToLine_Click(object sender, RoutedEventArgs e) { - GoToLineWindowIsOpen = false; - appsettings.SaveSettings("GoToLineWindowOpened", false); + await GoToLineDialog.Show(currentlySelectedTabPage); } - private void GoToLinebutton2_Click(object sender, RoutedEventArgs e) + + //Document + private async void CloseTab_Click(object sender, RoutedEventArgs e) { - bool Succed = DoGoToLine(GoToLineTextBox); - GoToLineWindow.BorderBrush = Succed ? DefaultValues.CorrectInput_Color : DefaultValues.WrongInput_Color; - if (appsettings.GetSettingsAsBool("HideGoToLineDialogAfterEntering", true) && Succed) - { - GoToLineWindowIsOpen = false; - } + await TabPageHelper.CloseTab(tabControl, currentlySelectedTabPage); } - private void ShowGoToLineWindow() + private async void FileInfo_Click(object sender, RoutedEventArgs e) { - if (!SettingsWindowSelected) - { - GoToLineWindowIsOpen = !GoToLineWindowIsOpen; - appsettings.SaveSettings("GoToLineWindowOpened", GoToLineWindowIsOpen); - GoToLineTextBox.Focus(FocusState.Programmatic); - } + await FileInfoDialog.Show(currentlySelectedTabPage); } - private void GoToLineWindow_CloseClick(object sender, RoutedEventArgs e) + private async void ChangeEncoding_Click(object sender, RoutedEventArgs e) { - CloseGoToLineDialog(); + await EncodingDialog.Show(currentlySelectedTabPage); + UpdateStatubar(); } - private void TextBoxes_GotFocus(object sender, RoutedEventArgs e) + private void ShareDocument_Click(object sender, RoutedEventArgs e) { - if (sender is TextBox tb) - { - tb.SelectAll(); - } + ShareDialog.Share(currentlySelectedTabPage); } - - ////////Statusbar//////// - //EVENTS// - private void TextControlBox_ZoomChangedEvent(TextControlBox sender, double ZoomFactor) + private async void ShowTabInNewWindow_Click(object sender, RoutedEventArgs e) { - if (Statusbar != null) - { - preventZoomOnFactorChanged = true; - ZoomDisplay.Content = appsettings.GetResourceString("Statusbar_Display_Zoom/Text") + " " + (int)ZoomFactor + "%"; - ZoomFlyoutSlider.Value = (int)ZoomFactor; - ZoomFlyoutSlider.Header = ZoomFactor + "%"; - preventZoomOnFactorChanged = false; - } + await TabWindowHelper.ShowInNewWindow(tabControl, currentlySelectedTabPage); } - private void TextControlBox_DocumentTitleChangedEvent(TextControlBox sender, string Header) + + //View + private void ZoomIn_Click(object sender, RoutedEventArgs e) { - if (Statusbar != null && FileNameDisplay != null) - { - FileNameDisplay.Content = Header.Replace("*", ""); - } + EditActions.ZoomIn(currentlySelectedTabPage); } - private void TextControlBox_LineNumberchangedEvent(TextControlBox sender, int CurrentLine) + private void ZoomOut_Click(object sender, RoutedEventArgs e) { - if (Statusbar != null) - { - LineNumberDisplay.Content = appsettings.GetResourceString("Statusbar_Display_Line/Text") + " " + CurrentLine; - //LineNumberDisplay.Content = appsettings.GetResourceString("Statusbar_Display_Line/Text") + " " + CurrentLine + " " + appsettings.GetResourceString("Statusbar_Display_Column/Text") + " " + sender.GetCurrentColumn; - } + EditActions.ZoomOut(currentlySelectedTabPage); } - private void Content_EncodingChangedEvent(TextControlBox sender, Encoding e) + private void TabSpaces_Click(object sender, RoutedEventArgs e) { - if (Statusbar != null) + if (currentlySelectedTabPage == null) + return; + + if (sender is MenuFlyoutItem item) { - EncodingDisplay.Content = Encodings.EncodingToString(e); + TabPageHelper.TabsOrSpaces(tabControl, item.Tag); } - } - private void Content_SaveStatusChangedEvent(TextControlBox sender, bool IsModified) - { - if (Statusbar != null) + else if (sender is RunCommandWindowItem runitem) { - //if (appsettings.GetSettingsAsBool("ShowColorsForSaveStatusButton", true)) - // SaveStatusDisplay.Foreground = IsModified ? DefaultValues.WrongInput_Color : DefaultValues.CorrectInput_Color; - SaveStatusDisplay.Content = IsModified ? appsettings.GetResourceString("MainPage_Statusbar_Unsaved/Text") : appsettings.GetResourceString(" MainPage_Statusbar_Saved/Text"); + TabPageHelper.TabsOrSpaces(tabControl, runitem.Tag); } } - private void StatusbarButton_PointerEnterExit(object sender, PointerRoutedEventArgs e) + private void Fullscreen_Click(object sender, RoutedEventArgs e) { - if (sender is Button btn) - { - btn.Foreground = new SolidColorBrush(StatusbarForegroundColor); - Statusbar.Background = new SolidColorBrush(StatusbarBackgroundColor); - } - //if (appsettings.GetSettingsAsBool("ShowColorsForSaveStatusButton", true)) - // SaveStatusDisplay.Foreground = tabActions.GetTextBoxFromSelectedTabPage().IsModified ? DefaultValues.WrongInput_Color : DefaultValues.CorrectInput_Color; - //else SaveStatusDisplay.Foreground = LineNumberDisplay.Foreground; + WindowHelper.ToggleFullscreen(); } - private void ZoomDisplay_PointerWheelChanged(object sender, PointerRoutedEventArgs e) + private void CompactOverlayMode_Click(object sender, RoutedEventArgs e) { - if (CurrentlySelectedTabPage != null) - { - int delta = e.GetCurrentPoint((UIElement)sender).Properties.MouseWheelDelta; - - if (delta < 0) - { - tabpagehelper.ZoomOut(CurrentlySelectedTabPage); - } - - if (delta > 0) - { - tabpagehelper.ZoomIn(CurrentlySelectedTabPage); - } - } + WindowHelper.ToggleCompactOverlay(); } - private void Textbox_WordCountChangedEvent(TextControlBox sender, int Words) + private void ShowRunCommandWindow_Click(object sender, RoutedEventArgs e) { - WordCountDisplay.Content = appsettings.GetResourceString("MainPage_Statusbar_Wordcount/Text") + ": " + Words; + runCommandWindow.Toggle(tabControl); } - //Zoom-flyout// - private void ZoomFlyoutSlider_ValueChanged(object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e) + private void ShowAllTabsFlyout_Opened(object sender, object e) { - if (tabactions != null && preventZoomOnFactorChanged == false) + void update() { - if (e.OldValue != e.NewValue && ZoomFlyoutSlider.Value != 0) + if (ShowAllTabsFlyout.Content is ListView listView) { - TextControlBox textbox = tabactions.GetTextBoxFromSelectedTabPage(); - if (textbox != null) - { - textbox.SetFontZoomFactor(ZoomFlyoutSlider.Value); - } + AllTabsFlyout.UpdateFlyout(tabControl, listView); + listView.Tag = null; + listView.Focus(FocusState.Programmatic); + listView.SelectedIndex = tabControl.SelectedIndex > listView.Items.Count ? 0 : -1; } } - } - - //Rename-flyout// - private async void TryRenameFile() - { - if (StringBuilder.IsValidFilename(RenameTextBox.Text)) + + //fixes flyout not showing up on first button press + if (ShowAllTabsFlyout == null) { - RenameTextBox.BorderBrush = DefaultValues.CorrectInput_Color; - if (CurrentlySelectedTabPage != null) + if (sender is Flyout fl) { - if (RenameTextBox.Text != tabpagehelper.GetTabHeader(CurrentlySelectedTabPage)) - { - if (await tabactions.RenameFile(RenameTextBox.Text)) - { - RenameFlyout.Hide(); - } - } + ShowAllTabsFlyout = fl; + update(); } } else { - RenameTextBox.BorderBrush = DefaultValues.WrongInput_Color; - RenameFileButton.IsEnabled = false; - } - } - private void RenameTextBox_KeyDown(object sender, KeyRoutedEventArgs e) - { - e.Handled = true; - if (TextTabControl != null && e.Key == VirtualKey.Enter) - { - TryRenameFile(); - RenameFlyout.Hide(); - } - if (e.Key == VirtualKey.Escape) - { - HideFlyoutIfOpened(RenameFlyout); + if (ShowAllTabsFlyout.Content is ListView) + { + update(); + } } } - private void RenameFileButton_Click(object sender, RoutedEventArgs e) - { - TryRenameFile(); - } - private void RenameTextBox_TextChanged(object sender, TextChangedEventArgs e) + private void AllTabsFlyout_SelectionChanged(object sender, SelectionChangedEventArgs e) { - if (sender is TextBox) + if (ShowAllTabsFlyout == null) + return; + + if (sender is ListView listView && listView.SelectedItem is TabFlyoutItem tabFlyoutItem) { - TextBox tb = sender as TextBox; - if (StringBuilder.IsValidFilename(tb.Text)) - { - tb.BorderBrush = DefaultValues.CorrectInput_Color; - RenameFileButton.IsEnabled = true; - } - else + //Don't hide the flyout when the tag has a value -> for searching and up/down using arrow keys + if (listView.Tag == null) { - tb.BorderBrush = DefaultValues.WrongInput_Color; - RenameFileButton.IsEnabled = false; + tabControl.SelectedItem = tabFlyoutItem.Tab; + + //hide the flyout + ShowAllTabsFlyout.Hide(); } } } - private void RenameFlyout_Opened(object sender, object e) + private void AllTabsFlyout_CharacterReceived(UIElement sender, CharacterReceivedRoutedEventArgs args) { - TextControlBox textbox = tabactions.GetTextBoxFromSelectedTabPage(); - if (textbox != null) + if (sender is ListView listView) { - RenameTextBox.Text = textbox.Header; - string ext = Path.GetExtension(RenameTextBox.Text); - RenameTextBox.Select(0, RenameTextBox.Text.Length - ext.Length); + AllTabsFlyout.Flyout_CharacterReceived(args.Character, listView); } } - private void RenameTextBox_FocusEngaged(Control sender, FocusEngagedEventArgs args) - { - RenameTextBox.BorderBrush = new SolidColorBrush(Colors.Gray); - } - private void OpenRenameFlyout() + private void AllTabsFlyout_KeyDown(object sender, KeyRoutedEventArgs e) { - RenameFlyout.ShowAt(FileNameDisplay); - } + if (ShowAllTabsFlyout == null) + return; - //Go to line-flyout / Go to line dialog// - private bool DoGoToLine(TextBox sender) - { - TextControlBox textbox = tabactions.GetTextBoxFromSelectedTabPage(); - if (StringBuilder.IsAllNumber(sender.Text) && textbox != null) + if (sender is ListView listView) { - if (!sender.Text.Equals("0", StringComparison.Ordinal) && sender.Text.Length != 0) + if (e.Key == VirtualKey.Enter) + { + if (listView.Tag != null && listView.SelectedItem is TabFlyoutItem tabFlyoutItem) + tabControl.SelectedItem = tabFlyoutItem.Tab; + + //hide the flyout + ShowAllTabsFlyout.Hide(); + } + else if (e.Key == Windows.System.VirtualKey.Down) { - int EnteredLineNumber = Convert.ToInt(sender.Text); - if (EnteredLineNumber <= textbox.GetLinesCount && EnteredLineNumber > 0) + if (listView.SelectedIndex < listView.Items.Count - 1) { - GoToLineWindow.BorderBrush = new SolidColorBrush(Colors.Gray); - textbox.GoToLine(EnteredLineNumber); - return true; + listView.Tag = ""; } } - } - return false; - } - private void GoToLinebuttonClick(object sender, RoutedEventArgs e) - { - DoGoToLine(LineNumberTextBox); - } - private void LineNumberTextBox_KeyDown(object sender, KeyRoutedEventArgs e) - { - if (e.Key == VirtualKey.Enter) - { - DoGoToLine(sender as TextBox); - } - } - private void LineNumberTextBox_TextChanged(object sender, TextChangedEventArgs e) - { - if (sender is TextBox) - { - bool succed = false; - TextBox tb = sender as TextBox; - TextControlBox textbox = tabactions.GetTextBoxFromSelectedTabPage(); - if (StringBuilder.IsAllNumber(tb.Text) && textbox != null) + else if (e.Key == Windows.System.VirtualKey.Up) { - if (!tb.Text.Equals("0", StringComparison.Ordinal) && tb.Text.Length != 0) + if (listView.SelectedIndex > 0) { - int EnteredLineNumber = Convert.ToInt(tb.Text); - if (EnteredLineNumber <= textbox.GetLinesCount && EnteredLineNumber > 0) - { - succed = true; - } + listView.Tag = ""; } } - GoToLineWindow.BorderBrush = succed ? DefaultValues.CorrectInput_Color : DefaultValues.WrongInput_Color; - } } - - //Encoding-flyout - private void AddEncodingButtonsToStatusbar() - { - //if the Encodingflyout has more then the two default buttons return and don't add them again - if (EncodingFlyout.Items.Count > 2) - return; - for (int i = 0; i < Encodings.AllEncodingNames.Count; i++) - { - var openwithitem = new MenuFlyoutItem - { - Text = Encodings.AllEncodingNames[i] - }; - openwithitem.Click += Openwithitem_Click; - OpenWithEncodingButton.Items.Add(openwithitem); - var item = new MenuFlyoutItem - { - Text = Encodings.AllEncodingNames[i] - }; - item.Click += EncodingButton_Click; - EncodingFlyout.Items.Add(item); - } - } - private void EncodingButton_Click(object sender, RoutedEventArgs e) - { - if (sender is MenuFlyoutItem selecteditem) - { - if (CurrentlySelectedTabPage_Textbox != null) - { - CurrentlySelectedTabPage_Textbox.Encoding = Encodings.StringToEncoding(selecteditem.Text); - tabpagehelper.SetTabModified(CurrentlySelectedTabPage, true); - } - } - } - private async void Openwithitem_Click(object sender, RoutedEventArgs e) + private void Statusbar_GoToLineTextbox_KeyDown(object sender, KeyRoutedEventArgs e) { - if (sender is MenuFlyoutItem item) + if (e.Key == Windows.System.VirtualKey.Enter) { - LoadingProgressRing.Visibility = Visibility.Visible; + int res = ConvertHelper.ToInt(Statusbar_GoToLineTextbox.Text, -1) - 1; + if (res == -1) + return; - await Task.Delay(100); //idk. why but without it the Progressbar is hidden - await tabactions.OpenFileWithEncoding(CurrentlySelectedTabPage, Encodings.StringToEncoding(item.Text)); - LoadingProgressRing.Visibility = Visibility.Collapsed; + EditActions.GoToLine(currentlySelectedTabPage, res); + Statusbar_Line.HideFlyout(); } } } - - public class SettingsNavigationParameter - { - public muxc.TabView Tabcontrol { get; set; } - public MainPage Mainpage { get; set; } - public string PageToNavigateTo { get; set; } = ""; - } - public class OpenedSecondaryViewItem - { - public CoreApplicationView CoreApplicationView { get; set; } - public ApplicationView ApplicationView { get; set; } - } - public class CommandLineLaunchNavigationParameter - { - public string Arguments { get; set; } - public string CurrentDirectoryPath { get; set; } - } } diff --git a/Fastedit/Views/PrivacyPoliciesPage.xaml b/Fastedit/Views/PrivacyPoliciesPage.xaml deleted file mode 100644 index 238beef..0000000 --- a/Fastedit/Views/PrivacyPoliciesPage.xaml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - Privacy Policy - - - By using the app you are consenting to our policies regarding the collection, use and disclosure of personal information set out in this privacy policy. - - - - Collection of Personal Information - - - We do not collect, store, use or share any information, personal or otherwise. - - - - Email - - - If you email the developer for support or other feedback, the emails with email addresses will be retained for quality assurance purposes. The email addresses will be used only to reply to the concerns or suggestions raised and will never be used for any marketing purpose. - - - - Disclosure of Personal Information - - - We will not disclose your information to any third party except if you expressly consent or where required by law. - - - - Contacting Us - - - If you have any questions regarding this privacy policy, you can email - fasteditsoftware@gmail.com - - - - - diff --git a/Fastedit/Views/PrivacyPoliciesPage.xaml.cs b/Fastedit/Views/PrivacyPoliciesPage.xaml.cs deleted file mode 100644 index f2258c0..0000000 --- a/Fastedit/Views/PrivacyPoliciesPage.xaml.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Windows.UI.Xaml.Controls; - -// Die Elementvorlage "Leere Seite" wird unter https://go.microsoft.com/fwlink/?LinkId=234238 dokumentiert. - -namespace Fastedit.Views -{ - /// - /// Eine leere Seite, die eigenständig verwendet oder zu der innerhalb eines Rahmens navigiert werden kann. - /// - public sealed partial class PrivacyPoliciesPage : Page - { - public PrivacyPoliciesPage() - { - this.InitializeComponent(); - } - } -} diff --git a/Fastedit/Views/SettingsPage.xaml b/Fastedit/Views/SettingsPage.xaml index 4c5bd19..0fe74b4 100644 --- a/Fastedit/Views/SettingsPage.xaml +++ b/Fastedit/Views/SettingsPage.xaml @@ -1,85 +1,59 @@ - - - - - + xmlns:muxc="using:Microsoft.UI.Xaml.Controls" + mc:Ignorable="d"> + + - + - + - - - - - - - + + - + - + - + - - + - + - - + + - - - - - - + - - - - - - + - - - - - - - - - - - - - - + + + + + + + + + + + + + diff --git a/Fastedit/Views/SettingsPages/Settings_DesignPage.xaml.cs b/Fastedit/Views/SettingsPages/Settings_DesignPage.xaml.cs new file mode 100644 index 0000000..9c19077 --- /dev/null +++ b/Fastedit/Views/SettingsPages/Settings_DesignPage.xaml.cs @@ -0,0 +1,35 @@ +using Fastedit.Helper; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; +using Windows.UI.Xaml.Navigation; + +// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238 + +namespace Fastedit.Views.SettingsPages +{ + /// + /// An empty page that can be used on its own or navigated to within a Frame. + /// + public sealed partial class Settings_DesignPage : Page + { + public Settings_DesignPage() + { + this.InitializeComponent(); + } + + protected override void OnNavigatedTo(NavigationEventArgs e) + { + DesignGridViewHelper.LoadItems(designGridView); + base.OnNavigatedTo(e); + } + private void BasicGridView_ItemClick(object sender, ItemClickEventArgs e) + { + DesignGridViewHelper.GridViewClick(e); + } + + private void UpdateDesigns_Click(object sender, RoutedEventArgs e) + { + DesignGridViewHelper.UpdateItems(designGridView); + } + } +} diff --git a/Fastedit/Views/SettingsPages/Settings_DocumentPage.xaml b/Fastedit/Views/SettingsPages/Settings_DocumentPage.xaml new file mode 100644 index 0000000..4eaaa3f --- /dev/null +++ b/Fastedit/Views/SettingsPages/Settings_DocumentPage.xaml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Fastedit/Views/SettingsPages/Settings_DocumentPage.xaml.cs b/Fastedit/Views/SettingsPages/Settings_DocumentPage.xaml.cs new file mode 100644 index 0000000..0915657 --- /dev/null +++ b/Fastedit/Views/SettingsPages/Settings_DocumentPage.xaml.cs @@ -0,0 +1,76 @@ +using Fastedit.Settings; +using Microsoft.Graphics.Canvas.Text; +using System.Linq; +using System.Runtime.InteropServices.WindowsRuntime; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; +using Windows.UI.Xaml.Controls.Primitives; + +// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238 + +namespace Fastedit.Views.SettingsPages +{ + /// + /// An empty page that can be used on its own or navigated to within a Frame. + /// + public sealed partial class Settings_DocumentPage : Page + { + public string[] Fonts + { + get + { + return CanvasTextFormat.GetSystemFontFamilies().OrderBy(f => f).ToArray(); + } + } + + public Settings_DocumentPage() + { + this.InitializeComponent(); + + SpacesOrTabsSwitch.IsOn = AppSettings.GetSettingsAsBool(AppSettingsValues.Settings_UseSpacesInsteadTabs, DefaultValues.UseSpacesInsteadTabs); + + var value = AppSettings.GetSettingsAsInt(AppSettingsValues.Settings_SpacesPerTab, DefaultValues.NumberOfSpacesPerTab); + SpacesPerTabSlider.Value = value == -1 ? DefaultValues.NumberOfSpacesPerTab : value; + //load + FontFamilyCombobox.SelectedItem = AppSettings.GetSettings(AppSettingsValues.Settings_FontFamily, DefaultValues.FontFamily); + FontSizeNumberBox.Value = AppSettings.GetSettingsAsInt(AppSettingsValues.Settings_FontSize, DefaultValues.FontSize); + + ShowLinenumbersSwitch.IsOn = AppSettings.GetSettingsAsBool(AppSettingsValues.Settings_ShowLineNumbers, DefaultValues.ShowLinenumbers); + EnableSyntaxhighlightingSwitch.IsOn = AppSettings.GetSettingsAsBool(AppSettingsValues.Settings_Syntaxhighlighting, DefaultValues.SyntaxHighlighting); + ShowLinehighlighterSwitch.IsOn = AppSettings.GetSettingsAsBool(AppSettingsValues.Settings_ShowLineHighlighter, DefaultValues.ShowLineHighlighter); + } + + private void SpacesOrTabsSwitch_Toggled(object sender, RoutedEventArgs e) + { + AppSettings.SaveSettings(AppSettingsValues.Settings_UseSpacesInsteadTabs, SpacesOrTabsSwitch.IsOn); + } + private void SpacesPerTabSlider_ValueChanged(object sender, RangeBaseValueChangedEventArgs e) + { + AppSettings.SaveSettings(AppSettingsValues.Settings_SpacesPerTab, SpacesPerTabSlider.Value); + } + + private void FontFamilyCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + AppSettings.SaveSettings(AppSettingsValues.Settings_FontFamily, FontFamilyCombobox.SelectedItem); + } + + private void FontSizeNumberBox_ValueChanged(Microsoft.UI.Xaml.Controls.NumberBox sender, Microsoft.UI.Xaml.Controls.NumberBoxValueChangedEventArgs args) + { + AppSettings.SaveSettings(AppSettingsValues.Settings_FontSize, FontSizeNumberBox.Value); + } + private void ShowLinenumbersSwitch_Toggled(object sender, RoutedEventArgs e) + { + AppSettings.SaveSettings(AppSettingsValues.Settings_ShowLineNumbers, ShowLinenumbersSwitch.IsOn); + } + + private void ShowLinehighlighterSwitch_Toggled(object sender, RoutedEventArgs e) + { + AppSettings.SaveSettings(AppSettingsValues.Settings_ShowLineHighlighter, ShowLinehighlighterSwitch.IsOn); + } + + private void EnableSyntaxhighlightingSwitch_Toggled(object sender, RoutedEventArgs e) + { + AppSettings.SaveSettings(AppSettingsValues.Settings_Syntaxhighlighting, EnableSyntaxhighlightingSwitch.IsOn); + } + } +} diff --git a/Fastedit/Views/SettingsPages/Settings_TabControl.xaml b/Fastedit/Views/SettingsPages/Settings_TabControl.xaml new file mode 100644 index 0000000..64da97b --- /dev/null +++ b/Fastedit/Views/SettingsPages/Settings_TabControl.xaml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/Fastedit/Views/SettingsPages/Settings_TabControl.xaml.cs b/Fastedit/Views/SettingsPages/Settings_TabControl.xaml.cs new file mode 100644 index 0000000..de013da --- /dev/null +++ b/Fastedit/Views/SettingsPages/Settings_TabControl.xaml.cs @@ -0,0 +1,50 @@ +using Fastedit.Dialogs; +using Fastedit.Settings; +using System; +using System.IO; +using System.Linq; +using Windows.UI.Xaml.Controls; + +namespace Fastedit.Views.SettingsPages +{ + public sealed partial class Settings_TabControl : Page + { + public Settings_TabControl() + { + this.InitializeComponent(); + TabSizecombobox.SelectedIndex = AppSettings.GetSettingsAsInt(AppSettingsValues.Settings_TabViewWidthMode); + + newTabTitleTextbox.Text = AppSettings.GetSettings(AppSettingsValues.Settings_NewTabTitle, DefaultValues.NewTabTitle) + AppSettings.GetSettings(AppSettingsValues.Settings_NewTabExtension, DefaultValues.NewTabExtension); + } + + private void TabSizecombobox_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + AppSettings.SaveSettings(AppSettingsValues.Settings_TabViewWidthMode, TabSizecombobox.SelectedIndex); + } + + private void NewTabTitle_TextChanged(object sender, TextChangedEventArgs e) + { + if (sender is TextBox textbox) + { + //validate data: + string data = textbox.Text; + if (data.Length == 0) + return; + + //check for invalid characters + char[] invalidChars = Path.GetInvalidFileNameChars(); + for (int i = 0; i < data.Length; i++) + { + if (invalidChars.Contains(data[0])) + { + InfoMessages.FileNameInvalidCharacters(); + return; + } + } + + AppSettings.SaveSettings(AppSettingsValues.Settings_NewTabTitle, Path.GetFileNameWithoutExtension(data.Trim())); + AppSettings.SaveSettings(AppSettingsValues.Settings_NewTabExtension, Path.GetExtension(data.Trim())); + } + } + } +} diff --git a/Fastedit/Views/TabWindowPage.xaml b/Fastedit/Views/TabWindowPage.xaml new file mode 100644 index 0000000..b8c3454 --- /dev/null +++ b/Fastedit/Views/TabWindowPage.xaml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Fastedit/Views/TabWindowPage.xaml.cs b/Fastedit/Views/TabWindowPage.xaml.cs new file mode 100644 index 0000000..2ff978f --- /dev/null +++ b/Fastedit/Views/TabWindowPage.xaml.cs @@ -0,0 +1,122 @@ +using Fastedit.Helper; +using Fastedit.Storage; +using Fastedit.Tab; +using System; +using Windows.UI.WindowManagement; +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; +using Windows.UI.Xaml.Input; + +// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238 + +namespace Fastedit.Views +{ + /// + /// An empty page that can be used on its own or navigated to within a Frame. + /// + public sealed partial class TabWindowPage : Page + { + public AppWindow window { get; set; } + public TabPageItem tab { get; set; } + public Grid MainGrid => mainGrid; + + public TabWindowPage(TabPageItem tab, AppWindow window) + { + this.InitializeComponent(); + + this.tab = tab; + this.window = window; + + Grid.SetRow(tab.textbox, 1); + //Add the textbox to the contentControl + this.mainGrid.Children.Add(tab.textbox); + + tab.textbox.ContextFlyout = RightClickMenu; + } + + public void Close() + { + //Show the default rightclick menu + tab.textbox.ContextFlyout = null; + + Grid.SetRow(tab.textbox, 0); + this.mainGrid.Children.Remove(tab.textbox); + } + + private void Fullscreen_Click(object sender, RoutedEventArgs e) + { + WindowHelper.ToggleFullscreenForAppWindow(window); + } + private void CompactOverlay_Click(object sender, RoutedEventArgs e) + { + WindowHelper.ToggleCompactOverlayForAppWindow(window); + } + private async void SaveAs_Click(object sender, RoutedEventArgs e) + { + await SaveFileHelper.SaveFileAs(tab); + } + private async void Save_Click(object sender, RoutedEventArgs e) + { + await SaveFileHelper.Save(tab); + } + private async void Open_Click(object sender, RoutedEventArgs e) + { + await OpenFileHelper.OpenFileForTab(tab); + } + + private void Page_KeyDown(object sender, KeyRoutedEventArgs e) + { + var ctrl = Window.Current.CoreWindow.GetKeyState(Windows.System.VirtualKey.Control).HasFlag(Windows.UI.Core.CoreVirtualKeyStates.Down); + var shift = Window.Current.CoreWindow.GetKeyState(Windows.System.VirtualKey.Shift).HasFlag(Windows.UI.Core.CoreVirtualKeyStates.Down); + if (ctrl) + { + switch (e.Key) + { + case Windows.System.VirtualKey.L: + Close_Click(null, null); + break; + case Windows.System.VirtualKey.S: + if (shift) + SaveAs_Click(null, null); + else + Save_Click(null, null); + break; + case Windows.System.VirtualKey.O: + Open_Click(null, null); + break; + case Windows.System.VirtualKey.F11: + Fullscreen_Click(null, null); + break; + case Windows.System.VirtualKey.K: + CompactOverlay_Click(null, null); + break; + case Windows.System.VirtualKey.D: + EditActions.DuplicateLine(tab); + break; + } + } + } + public Grid Titlebar => titlebar; + + private void Cut_Click(object sender, RoutedEventArgs e) + { + tab.textbox.Cut(); + } + + private void Paste_Click(object sender, RoutedEventArgs e) + { + tab.textbox.Paste(); + } + + private void Copy_Click(object sender, RoutedEventArgs e) + { + tab.textbox.Copy(); + } + + private async void Close_Click(object sender, RoutedEventArgs e) + { + if (window != null) + await window.CloseAsync(); + } + } +} diff --git a/Fastedit/Views/TextboxViewPage.xaml b/Fastedit/Views/TextboxViewPage.xaml deleted file mode 100644 index 2fed5d6..0000000 --- a/Fastedit/Views/TextboxViewPage.xaml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - -