commit dd725ba93049a07284bcd1906562b2b92eb6a13a Author: Stone_Red <56473591+Stone-Red-Code@users.noreply.github.com> Date: Thu Mar 21 22:34:53 2024 +0100 Initial commit diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..426d76d --- /dev/null +++ b/.gitignore @@ -0,0 +1,398 @@ +## 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/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET 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 +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..db33ee8 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Stone_Red + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Markdowser.sln b/Markdowser.sln new file mode 100644 index 0000000..ac25629 --- /dev/null +++ b/Markdowser.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.9.34616.47 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Markdowser", "Markdowser\Markdowser.csproj", "{98C02B25-7D7D-4F83-892D-5503FFF3D108}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {98C02B25-7D7D-4F83-892D-5503FFF3D108}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {98C02B25-7D7D-4F83-892D-5503FFF3D108}.Debug|Any CPU.Build.0 = Debug|Any CPU + {98C02B25-7D7D-4F83-892D-5503FFF3D108}.Release|Any CPU.ActiveCfg = Release|Any CPU + {98C02B25-7D7D-4F83-892D-5503FFF3D108}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {93739FBA-8641-4D80-A0C5-64201ABD1B13} + EndGlobalSection +EndGlobal diff --git a/Markdowser/App.axaml b/Markdowser/App.axaml new file mode 100644 index 0000000..5758836 --- /dev/null +++ b/Markdowser/App.axaml @@ -0,0 +1,15 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Markdowser/App.axaml.cs b/Markdowser/App.axaml.cs new file mode 100644 index 0000000..5782b35 --- /dev/null +++ b/Markdowser/App.axaml.cs @@ -0,0 +1,41 @@ +using Avalonia; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Markup.Xaml; +using Avalonia.Styling; + +using Markdowser.Utilities; +using Markdowser.ViewModels; +using Markdowser.Views; + +namespace Markdowser; + +public partial class App : Application +{ + public override void Initialize() + { + AvaloniaXamlLoader.Load(this); + } + + public override void OnFrameworkInitializationCompleted() + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + desktop.MainWindow = new MainWindow + { + DataContext = new MainWindowViewModel(), + }; + + desktop.MainWindow.Closing += (sender, e) => + { + Settings.SaveSettings(); + }; + } + + base.OnFrameworkInitializationCompleted(); + + if (Current is not null) + { + Current.RequestedThemeVariant = Settings.Current.DarkMode ? ThemeVariant.Dark : ThemeVariant.Light; + } + } +} \ No newline at end of file diff --git a/Markdowser/Assets/Markdowser-Dark-Transparent.png b/Markdowser/Assets/Markdowser-Dark-Transparent.png new file mode 100644 index 0000000..0539ef6 Binary files /dev/null and b/Markdowser/Assets/Markdowser-Dark-Transparent.png differ diff --git a/Markdowser/Assets/Markdowser-Dark.png b/Markdowser/Assets/Markdowser-Dark.png new file mode 100644 index 0000000..8af62fb Binary files /dev/null and b/Markdowser/Assets/Markdowser-Dark.png differ diff --git a/Markdowser/Assets/Markdowser-Light-Transparent.png b/Markdowser/Assets/Markdowser-Light-Transparent.png new file mode 100644 index 0000000..861a133 Binary files /dev/null and b/Markdowser/Assets/Markdowser-Light-Transparent.png differ diff --git a/Markdowser/Assets/Markdowser-Light.png b/Markdowser/Assets/Markdowser-Light.png new file mode 100644 index 0000000..472d4e0 Binary files /dev/null and b/Markdowser/Assets/Markdowser-Light.png differ diff --git a/Markdowser/Assets/avalonia-logo.ico b/Markdowser/Assets/avalonia-logo.ico new file mode 100644 index 0000000..da8d49f Binary files /dev/null and b/Markdowser/Assets/avalonia-logo.ico differ diff --git a/Markdowser/Commands/ChangeThemeCommand.cs b/Markdowser/Commands/ChangeThemeCommand.cs new file mode 100644 index 0000000..96213da --- /dev/null +++ b/Markdowser/Commands/ChangeThemeCommand.cs @@ -0,0 +1,31 @@ +using Avalonia; +using Avalonia.Styling; + +using Markdowser.Utilities; + +using System; +using System.Windows.Input; + +namespace Markdowser.Commands; + +internal class ChangeThemeCommand : ICommand +{ + public event EventHandler? CanExecuteChanged; + + public bool CanExecute(object? parameter) + { + return true; + } + + public void Execute(object? parameter) + { + Application? app = Application.Current; + if (app is not null) + { + ThemeVariant theme = app.ActualThemeVariant; + app.RequestedThemeVariant = theme == ThemeVariant.Dark ? ThemeVariant.Light : ThemeVariant.Dark; + Settings.Current.DarkMode = app.RequestedThemeVariant == ThemeVariant.Dark; + GlobalState.ReloadContent(this); + } + } +} \ No newline at end of file diff --git a/Markdowser/Commands/HomeCommand.cs b/Markdowser/Commands/HomeCommand.cs new file mode 100644 index 0000000..e0cdeff --- /dev/null +++ b/Markdowser/Commands/HomeCommand.cs @@ -0,0 +1,21 @@ +using Markdowser.Utilities; + +using System; +using System.Windows.Input; + +namespace Markdowser.Commands; + +internal class HomeCommand : ICommand +{ + public event EventHandler? CanExecuteChanged; + + public bool CanExecute(object? parameter) + { + return true; + } + + public void Execute(object? parameter) + { + GlobalState.Url = Settings.Current.HomeUrl ?? string.Empty; + } +} \ No newline at end of file diff --git a/Markdowser/Commands/HyperlinkCommand.cs b/Markdowser/Commands/HyperlinkCommand.cs new file mode 100644 index 0000000..b7df8ff --- /dev/null +++ b/Markdowser/Commands/HyperlinkCommand.cs @@ -0,0 +1,38 @@ +using Markdowser.Utilities; + +using System; +using System.Diagnostics; +using System.Windows.Input; + +namespace Markdowser.Commands; + +public class HyperlinkCommand : ICommand +{ + public event EventHandler? CanExecuteChanged; + + public bool CanExecute(object? parameter) + { + return true; + } + + public void Execute(object? parameter) + { + if (parameter is string url) + { + Debug.WriteLine($"Hyperlink clicked: {url}"); + + if (Uri.IsWellFormedUriString(url, UriKind.Absolute)) + { + GlobalState.Url = url; + } + else if (Uri.IsWellFormedUriString(url, UriKind.Relative) || url.StartsWith('/')) + { + GlobalState.Url = new Uri(new Uri(GlobalState.Url), url).ToString(); + } + else + { + Debug.WriteLine($"Invalid URL: {url}"); + } + } + } +} \ No newline at end of file diff --git a/Markdowser/GlobalSuppressions.cs b/Markdowser/GlobalSuppressions.cs new file mode 100644 index 0000000..48e5f4b --- /dev/null +++ b/Markdowser/GlobalSuppressions.cs @@ -0,0 +1,9 @@ +// This file is used by Code Analysis to maintain SuppressMessage +// attributes that are applied to this project. +// Project-level suppressions either have no target or are given +// a specific target and scoped to a namespace, type, member, etc. + +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage("Minor Code Smell", "S1075:URIs should not be hardcoded", Justification = "")] +[assembly: SuppressMessage("Minor Code Smell", "CS0067:The event 'ChangeThemeCommand.CanExecuteChanged' is never used", Justification = "", Scope = "member", Target = "~N:Markdowser.Commands")] \ No newline at end of file diff --git a/Markdowser/Markdowser.csproj b/Markdowser/Markdowser.csproj new file mode 100644 index 0000000..8209d0b --- /dev/null +++ b/Markdowser/Markdowser.csproj @@ -0,0 +1,42 @@ + + + WinExe + net8.0 + enable + true + app.manifest + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Markdowser/Program.cs b/Markdowser/Program.cs new file mode 100644 index 0000000..12b002f --- /dev/null +++ b/Markdowser/Program.cs @@ -0,0 +1,37 @@ +using Avalonia; +using Avalonia.ReactiveUI; + +using Projektanker.Icons.Avalonia; +using Projektanker.Icons.Avalonia.FontAwesome; +using Projektanker.Icons.Avalonia.MaterialDesign; + +using System; + +namespace Markdowser; + +internal static class Program +{ + // Initialization code. Don't use any Avalonia, third-party APIs or any + // SynchronizationContext-reliant code before AppMain is called: things aren't initialized + // yet and stuff might break. + [STAThread] + public static void Main(string[] args) + { + _ = BuildAvaloniaApp() + .StartWithClassicDesktopLifetime(args); + } + + // Avalonia configuration, don't remove; also used by visual designer. + public static AppBuilder BuildAvaloniaApp() + { + _ = IconProvider.Current + .Register() + .Register(); + + return AppBuilder.Configure() + .UsePlatformDetect() + .WithInterFont() + .LogToTrace() + .UseReactiveUI(); + } +} \ No newline at end of file diff --git a/Markdowser/Utilities/Configuration.cs b/Markdowser/Utilities/Configuration.cs new file mode 100644 index 0000000..f859e02 --- /dev/null +++ b/Markdowser/Utilities/Configuration.cs @@ -0,0 +1,12 @@ +using System; +using System.IO; + +namespace Markdowser.Utilities; + +internal static class Configuration +{ + public static string DownloadPath => Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); + public static string ApplicationDataPath => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), nameof(Markdowser)); + + public static string SettingsFilePath => Path.Combine(ApplicationDataPath, "settings.json"); +} \ No newline at end of file diff --git a/Markdowser/Utilities/GlobalState.cs b/Markdowser/Utilities/GlobalState.cs new file mode 100644 index 0000000..f78d35f --- /dev/null +++ b/Markdowser/Utilities/GlobalState.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace Markdowser.Utilities; + +[SuppressMessage("Major Code Smell", "S4220:Events should have proper arguments", Justification = "")] +internal static class GlobalState +{ + public static event EventHandler? UrlChanged; + + public static event EventHandler? ContentReload; + + private static string url = string.Empty; + + public static Stack BackHistory { get; } = new(); + + public static Stack ForwardHistory { get; } = new(); + + public static string Url + { + get => url; + set + { + if (url != value) + { + BackHistory.Push(url); + ForwardHistory.Clear(); + } + + url = value; + UrlChanged?.Invoke(null, url); + } + } + + internal static void SetUrl(object sender, string url) + { + GlobalState.url = url; + UrlChanged?.Invoke(sender, url); + } + + internal static void ReloadContent(object sender) + { + ContentReload?.Invoke(sender, EventArgs.Empty); + } +} \ No newline at end of file diff --git a/Markdowser/Utilities/HttpPathResolver.cs b/Markdowser/Utilities/HttpPathResolver.cs new file mode 100644 index 0000000..dd3d489 --- /dev/null +++ b/Markdowser/Utilities/HttpPathResolver.cs @@ -0,0 +1,58 @@ +using Avalonia.Platform; + +using Markdown.Avalonia.Utils; + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Net.Http; +using System.Threading.Tasks; + +namespace Markdowser.Utilities; + +public class HttpPathResolver : IPathResolver +{ + private readonly HttpClient httpClient = new(); + public string? AssetPathRoot { get; set; } + public IEnumerable? CallerAssemblyNames { get; set; } + + public async Task? ResolveImageResource(string relativeOrAbsolutePath) + { + if (string.IsNullOrWhiteSpace(relativeOrAbsolutePath)) + { + return GetLogo(); + } + + if (relativeOrAbsolutePath.StartsWith("avares://")) + { + return AssetLoader.Open(new Uri(relativeOrAbsolutePath))!; + } + + if (!Uri.IsWellFormedUriString(relativeOrAbsolutePath, UriKind.Absolute)) + { + relativeOrAbsolutePath = new Uri(new Uri(GlobalState.Url), relativeOrAbsolutePath).ToString(); + } + + Debug.WriteLine($"Resolving image: {relativeOrAbsolutePath}"); + + HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(relativeOrAbsolutePath)!; + + if (!httpResponseMessage.IsSuccessStatusCode) + { + return GetLogo(); + } + + return await httpResponseMessage.Content.ReadAsStreamAsync(); + } + + private static Stream GetLogo() + { + if (Settings.Current.DarkMode) + { + return AssetLoader.Open(new Uri("avares://Markdowser/Assets/Markdowser-Dark-Transparent.png"))!; + } + + return AssetLoader.Open(new Uri("avares://Markdowser/Assets/Markdowser-Light-Transparent.png"))!; + } +} \ No newline at end of file diff --git a/Markdowser/Utilities/Settings.cs b/Markdowser/Utilities/Settings.cs new file mode 100644 index 0000000..b98af4b --- /dev/null +++ b/Markdowser/Utilities/Settings.cs @@ -0,0 +1,35 @@ +using System.IO; +using System.Text.Json; + +namespace Markdowser.Utilities; + +internal class Settings +{ + public static Settings Current { get; set; } = LoadSettings(); + + public bool DarkMode { get; set; } + + public string? HomeUrl { get; set; } + + public static void SaveSettings() + { + if (!Directory.Exists(Configuration.ApplicationDataPath)) + { + _ = Directory.CreateDirectory(Configuration.ApplicationDataPath); + } + + File.WriteAllText(Configuration.SettingsFilePath, JsonSerializer.Serialize(Current)); + } + + private static Settings LoadSettings() + { + if (File.Exists(Configuration.SettingsFilePath)) + { + return JsonSerializer.Deserialize(File.ReadAllText(Configuration.SettingsFilePath)) ?? new Settings(); + } + else + { + return new Settings(); + } + } +} \ No newline at end of file diff --git a/Markdowser/ViewLocator.cs b/Markdowser/ViewLocator.cs new file mode 100644 index 0000000..e4efd96 --- /dev/null +++ b/Markdowser/ViewLocator.cs @@ -0,0 +1,34 @@ +using Avalonia.Controls; +using Avalonia.Controls.Templates; + +using Markdowser.ViewModels; + +using System; + +namespace Markdowser; +public class ViewLocator : IDataTemplate +{ + + public Control? Build(object? data) + { + if (data is null) + return null; + + var name = data.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal); + var type = Type.GetType(name); + + if (type != null) + { + var control = (Control)Activator.CreateInstance(type)!; + control.DataContext = data; + return control; + } + + return new TextBlock { Text = "Not Found: " + name }; + } + + public bool Match(object? data) + { + return data is ViewModelBase; + } +} diff --git a/Markdowser/ViewModels/MainWindowViewModel.cs b/Markdowser/ViewModels/MainWindowViewModel.cs new file mode 100644 index 0000000..6909ae4 --- /dev/null +++ b/Markdowser/ViewModels/MainWindowViewModel.cs @@ -0,0 +1,253 @@ +using Markdowser.Utilities; + +using ReactiveUI; + +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Reflection; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows.Input; + +namespace Markdowser.ViewModels; + +public partial class MainWindowViewModel : ViewModelBase +{ + private readonly HttpClient httpClient = new(new HttpClientHandler() { AllowAutoRedirect = true }); + private readonly ReverseMarkdown.Converter markdownConverter = new(); + + private StringBuilder? content; + + private bool isBusy; + + private int progress; + public string Title => $"{nameof(Markdowser)} - {Assembly.GetExecutingAssembly().GetName().Version?.ToString()}"; + + public StringBuilder Content + { + get => content ?? DefaultContent; + set => this.RaiseAndSetIfChanged(ref content, value); + } + + public string Url + { + get => GlobalState.Url; + set => GlobalState.SetUrl(this, value); + } + + public bool IsBusy + { + get => isBusy; + set => this.RaiseAndSetIfChanged(ref isBusy, value); + } + + public int Progress + { + get => progress; + set + { + _ = this.RaiseAndSetIfChanged(ref progress, value); + this.RaisePropertyChanged(nameof(ProgressIndeterminate)); + } + } + + public bool BackEnabled => GlobalState.BackHistory.Count > 0; + + public bool ForwardEnabled => GlobalState.ForwardHistory.Count > 0; + + public bool ProgressIndeterminate => Progress == 0; + + public ICommand Browse => ReactiveCommand.Create(FetchUrl); + + public ICommand Back => ReactiveCommand.Create(() => + { + if (GlobalState.BackHistory.Count > 0) + { + GlobalState.ForwardHistory.Push(GlobalState.Url); + Url = GlobalState.BackHistory.Pop(); + FetchUrl(); + + this.RaisePropertyChanged(nameof(BackEnabled)); + this.RaisePropertyChanged(nameof(ForwardEnabled)); + } + }); + + public ICommand Forward => ReactiveCommand.Create(() => + { + if (GlobalState.ForwardHistory.Count > 0) + { + GlobalState.BackHistory.Push(GlobalState.Url); + Url = GlobalState.ForwardHistory.Pop(); + FetchUrl(); + + this.RaisePropertyChanged(nameof(ForwardEnabled)); + this.RaisePropertyChanged(nameof(BackEnabled)); + } + }); + + private StringBuilder DefaultContent => new StringBuilder() + .AppendLine($"![Logo](avares://Markdowser/Assets/Markdowser-{(Settings.Current.DarkMode ? "Dark" : "Light")}-Transparent.png)") + .AppendLine() + .AppendLine($"{nameof(Markdowser)} {Assembly.GetExecutingAssembly().GetName().Version?.ToString()}\n") + .AppendLine("A markdown web browser.\n") + .AppendLine("[GitHub](https://github.me.stone-red.net/Markdowser)"); + + public MainWindowViewModel() + { + httpClient.DefaultRequestHeaders.UserAgent.ParseAdd($"{nameof(Markdowser)}/{Assembly.GetExecutingAssembly().GetName().Version?.ToString()}"); + httpClient.Timeout = TimeSpan.FromSeconds(10); + + markdownConverter.Config.UnknownTags = ReverseMarkdown.Config.UnknownTagsOption.Bypass; + markdownConverter.Config.SuppressDivNewlines = false; + markdownConverter.Config.SmartHrefHandling = false; + + GlobalState.UrlChanged += (sender, url) => + { + this.RaisePropertyChanged(nameof(ForwardEnabled)); + this.RaisePropertyChanged(nameof(BackEnabled)); + this.RaisePropertyChanged(nameof(Url)); + + if (sender == this) + { + return; + } + + FetchUrl(); + }; + + GlobalState.ContentReload += (sender, _) => + { + this.RaisePropertyChanged(nameof(Content)); + }; + } + + private static bool IsValidHttpUri(string uriString, [NotNullWhen(true)] out Uri? uri) + { + return Uri.TryCreate(uriString, UriKind.Absolute, out uri) && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps); + } + + [GeneratedRegex("!\\[(.*?)\\]\\((.*?)\\)")] + private static partial Regex MarkdownImage(); + + private void FetchUrl() + { + if (string.IsNullOrWhiteSpace(Url)) + { + content = null; + this.RaisePropertyChanged(nameof(Content)); + Debug.WriteLine("URL is empty."); + return; + } + + if (!IsValidHttpUri(Url, out _)) + { + // Search with duckduckgo + Url = $"https://duckduckgo.com/html/?kd=-1&k1=-1&q={Uri.EscapeDataString(Url)}"; + } + + content ??= new StringBuilder(); + _ = content.Clear(); + + IsBusy = true; + Progress = 0; + + _ = Task.Run(async () => + { + Debug.WriteLine("Fetching URL..."); + + StringBuilder html = new(); + + try + { + HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(Url); + + Url = httpResponseMessage.RequestMessage?.RequestUri?.ToString() ?? Url; + + if (!httpResponseMessage.IsSuccessStatusCode) + { + IsBusy = false; + _ = content.AppendLine($"# {(int)httpResponseMessage.StatusCode} {httpResponseMessage.StatusCode}"); + _ = content.AppendLine($"Failed to fetch URL: {httpResponseMessage.ReasonPhrase}"); + this.RaisePropertyChanged(nameof(Content)); + return; + } + + long length = httpResponseMessage.Content.Headers.ContentLength ?? 0; + + using Stream contentStream = await httpResponseMessage.Content.ReadAsStreamAsync(); + using StreamReader streamReader = new(contentStream); + + while (!streamReader.EndOfStream) + { + _ = html.AppendLine(await streamReader.ReadLineAsync()); + Progress = (int)((double)contentStream.Position / length * 100); + } + } + catch (HttpRequestException e) + { + IsBusy = false; + + if (e.StatusCode is not null) + { + _ = content.AppendLine($"# {(int)e.StatusCode} {e.StatusCode}"); + } + + _ = content.AppendLine($"# {e.HttpRequestError}"); + _ = content.AppendLine($"Failed to fetch URL: {e.Message}"); + this.RaisePropertyChanged(nameof(Content)); + } + catch (Exception e) + { + IsBusy = false; + _ = content.AppendLine($"# {e.GetType().Name}"); + _ = content.AppendLine($"Failed to fetch URL: {e.Message}"); + this.RaisePropertyChanged(nameof(Content)); + } + + Debug.WriteLine("Converting HTML to markdown..."); + + string markdown = markdownConverter.Convert(html.ToString()); + + Debug.WriteLine("Processing markdown..."); + + int currentLine = 0; + + string[] lines = markdown.Split('\n'); + foreach (string line in lines) + { + Progress = (int)((double)currentLine / lines.Length * 100); + currentLine++; + + string trimmedLine = line.Trim(); + + if (trimmedLine.All(c => c == '#')) + { + _ = Content.Append(trimmedLine); + continue; + } + else if (MarkdownImage().IsMatch(trimmedLine)) + { + _ = content.AppendLine() + .Append(trimmedLine) + .AppendLine() + .AppendLine(); + continue; + } + + _ = content.AppendLine(trimmedLine); + + //this.RaisePropertyChanged(nameof(Content)); + } + + Debug.WriteLine("Done processing."); + this.RaisePropertyChanged(nameof(Content)); + + IsBusy = false; + }); + } +} \ No newline at end of file diff --git a/Markdowser/ViewModels/ViewModelBase.cs b/Markdowser/ViewModels/ViewModelBase.cs new file mode 100644 index 0000000..28a9281 --- /dev/null +++ b/Markdowser/ViewModels/ViewModelBase.cs @@ -0,0 +1,6 @@ +using ReactiveUI; + +namespace Markdowser.ViewModels; +public class ViewModelBase : ReactiveObject +{ +} diff --git a/Markdowser/Views/MainWindow.axaml b/Markdowser/Views/MainWindow.axaml new file mode 100644 index 0000000..c5100d2 --- /dev/null +++ b/Markdowser/Views/MainWindow.axaml @@ -0,0 +1,131 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +