Skip to content

Commit

Permalink
Add peek support
Browse files Browse the repository at this point in the history
  • Loading branch information
Aaron-Junker committed Apr 16, 2024
1 parent 3b02932 commit edc52c8
Show file tree
Hide file tree
Showing 8 changed files with 60 additions and 37 deletions.
13 changes: 0 additions & 13 deletions src/common/FilePreviewCommon/MonacoHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -103,18 +103,5 @@ public static string GetLanguage(string fileExtension)
return "plaintext";
}
}

public static string ReadIndexHtml()
{
string html;

using (StreamReader htmlFileReader = new StreamReader(new FileStream(MonacoDirectory + "\\index.html", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
{
html = htmlFileReader.ReadToEnd();
htmlFileReader.Close();
}

return html;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ManagedCommon;
using Microsoft.UI;
Expand Down Expand Up @@ -53,6 +54,8 @@ public Uri? Source
typeof(BrowserControl),
new PropertyMetadata(null, new PropertyChangedCallback((d, e) => ((BrowserControl)d).OnIsDevFilePreviewChanged())));

public Queue<string> JavascriptCommandQueue { get; set; } = [];

// Will actually be true for Markdown files as well.
public bool IsDevFilePreview
{
Expand All @@ -71,6 +74,16 @@ public BrowserControl()
{
this.InitializeComponent();
Environment.SetEnvironmentVariable("WEBVIEW2_USER_DATA_FOLDER", TempFolderPath.Path, EnvironmentVariableTarget.Process);

PreviewBrowser.NavigationCompleted += async (sender, _) =>
{
foreach (string command in JavascriptCommandQueue)
{
await sender.ExecuteScriptAsync(command);
}

JavascriptCommandQueue.Clear();
};
}

public void Dispose()
Expand Down
16 changes: 15 additions & 1 deletion src/modules/peek/Peek.FilePreviewer/FilePreview.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading;
Expand Down Expand Up @@ -107,6 +108,8 @@ private async void Previewer_PropertyChanged(object? sender, System.ComponentMod

public IUnsupportedFilePreviewer? UnsupportedFilePreviewer => Previewer as IUnsupportedFilePreviewer;

public Queue<string> JavascriptCommandQueue { get; set; } = [];

public IFileSystemItem Item
{
get => (IFileSystemItem)GetValue(ItemProperty);
Expand Down Expand Up @@ -180,6 +183,9 @@ private async Task OnItemPropertyChanged()
imagePreviewer.ScalingFactor = ScalingFactor;
}

BrowserPreview.JavascriptCommandQueue.Clear();
JavascriptCommandQueue.Clear();

await UpdatePreviewAsync(_cancellationTokenSource.Token);
}

Expand Down Expand Up @@ -209,6 +215,12 @@ private async Task UpdatePreviewAsync(CancellationToken cancellationToken)
cancellationToken.ThrowIfCancellationRequested();
await Previewer.LoadPreviewAsync(cancellationToken);

if (Previewer is IBrowserPreviewer browserPreviewer)
{
BrowserPreview.JavascriptCommandQueue = browserPreviewer.JavascriptCommandQueue;
JavascriptCommandQueue = browserPreviewer.JavascriptCommandQueue;
}

cancellationToken.ThrowIfCancellationRequested();
await UpdateTooltipAsync(cancellationToken);
}
Expand Down Expand Up @@ -250,6 +262,8 @@ partial void OnPreviewerChanging(IPreviewer? value)
{
value.PropertyChanged += Previewer_PropertyChanged;
}

JavascriptCommandQueue.Clear();
}

private void BrowserPreview_DOMContentLoaded(Microsoft.Web.WebView2.Core.CoreWebView2 sender, Microsoft.Web.WebView2.Core.CoreWebView2DOMContentLoadedEventArgs args)
Expand Down Expand Up @@ -349,7 +363,7 @@ private async Task UpdateTooltipAsync(CancellationToken cancellationToken)
sb.Append(fileNameFormatted);

cancellationToken.ThrowIfCancellationRequested();
string fileType = await Task.Run(Item.GetContentTypeAsync);
string fileType = await Item.GetContentTypeAsync().ConfigureAwait(true);
string fileTypeFormatted = string.IsNullOrEmpty(fileType) ? string.Empty : "\n" + ReadableStringHelper.FormatResourceString("PreviewTooltip_FileType", fileType);
sb.Append(fileTypeFormatted);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;

namespace Peek.FilePreviewer.Previewers.Interfaces
{
Expand All @@ -11,5 +12,7 @@ public interface IBrowserPreviewer : IPreviewer, IPreviewTarget
public Uri? Preview { get; }

public bool IsDevFilePreview { get; }

public Queue<string> JavascriptCommandQueue { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,13 @@ public static HashSet<string> GetExtensions()
/// <summary>
/// Prepares temp html for the previewing
/// </summary>
public static string PreviewTempFile(string fileText, string extension, string tempFolder, bool tryFormat, bool wrapText)
public static (Uri Uri, string VsCodeLangSet, string FileContent) PreviewTempFile(string fileText, string extension, bool tryFormat)
{
// TODO: check if file is too big, add MaxFileSize to settings
return InitializeIndexFileAndSelectedFile(fileText, extension, tempFolder, tryFormat, wrapText);
return InitializeIndexFileAndSelectedFile(fileText, extension, tryFormat);
}

private static string InitializeIndexFileAndSelectedFile(string fileContent, string extension, string tempFolder, bool tryFormat, bool wrapText)
private static (Uri Uri, string VsCodeLangSet, string FileContent) InitializeIndexFileAndSelectedFile(string fileContent, string extension, bool tryFormat)
{
string vsCodeLangSet = Microsoft.PowerToys.FilePreviewCommon.MonacoHelper.GetLanguage(extension);

Expand All @@ -71,21 +71,7 @@ private static string InitializeIndexFileAndSelectedFile(string fileContent, str
}
}

string base64FileCode = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(fileContent));
string theme = ThemeManager.GetWindowsBaseColor().ToLowerInvariant();

// prepping index html to load in
string html = Microsoft.PowerToys.FilePreviewCommon.MonacoHelper.ReadIndexHtml();

html = html.Replace("[[PT_LANG]]", vsCodeLangSet, StringComparison.InvariantCulture);
html = html.Replace("[[PT_WRAP]]", wrapText ? "1" : "0", StringComparison.InvariantCulture);
html = html.Replace("[[PT_THEME]]", theme, StringComparison.InvariantCulture);
html = html.Replace("[[PT_CODE]]", base64FileCode, StringComparison.InvariantCulture);
html = html.Replace("[[PT_URL]]", Microsoft.PowerToys.FilePreviewCommon.MonacoHelper.VirtualHostName, StringComparison.InvariantCulture);

string filename = tempFolder + "\\" + Guid.NewGuid().ToString() + ".html";
File.WriteAllText(filename, html);
return filename;
return (new Uri("http://" + Microsoft.PowerToys.FilePreviewCommon.MonacoHelper.VirtualHostName + "/index.html"), vsCodeLangSet, fileContent);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Common.UI;
using CommunityToolkit.Mvvm.ComponentModel;
using Microsoft.UI.Dispatching;
using Peek.Common.Constants;
Expand Down Expand Up @@ -80,6 +81,21 @@ protected virtual async void Dispose(bool disposing)

private Task<bool>? DisplayInfoTask { get; set; }

private Queue<string> _javascriptCommandQueue = [];

Queue<string> IBrowserPreviewer.JavascriptCommandQueue
{
get
{
return _javascriptCommandQueue;
}

set
{
_javascriptCommandQueue = value;
}
}

public Task<PreviewSize> GetPreviewSizeAsync(CancellationToken cancellationToken)
{
return Task.FromResult(new PreviewSize { MonitorSize = null });
Expand Down Expand Up @@ -111,8 +127,12 @@ await Dispatcher.RunOnUiThread(async () =>

if (IsDevFilePreview && !isHtml && !isMarkdown)
{
var raw = await ReadHelper.Read(File.Path.ToString());
Preview = new Uri(MonacoHelper.PreviewTempFile(raw, File.Extension, TempFolderPath.Path, _previewSettings.SourceCodeTryFormat, _previewSettings.SourceCodeWrapText));
string raw = await Task.Run(() => ReadHelper.Read(File.Path.ToString()));
(Preview, string vsCodeLangSet, string fileContent) = MonacoHelper.PreviewTempFile(raw, File.Extension, _previewSettings.SourceCodeTryFormat);
_javascriptCommandQueue.Enqueue("editor.setValue(\"" + fileContent.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "\\r") + "\");");
_javascriptCommandQueue.Enqueue("monaco.editor.setModelLanguage(editor.getModel(), \"" + vsCodeLangSet + "\");");
_javascriptCommandQueue.Enqueue("editor.updateOptions({\"wordWrap\": \"" + (_previewSettings.SourceCodeWrapText ? "on" : "off") + "\"});");
_javascriptCommandQueue.Enqueue("editor.updateOptions({\"theme\": \"" + (ThemeManager.GetWindowsBaseColor().Equals("dark", StringComparison.OrdinalIgnoreCase) ? "vs-dark" : "vs") + "\"});");
}
else if (isMarkdown)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public class MonacoPreviewHandlerControl : FormHandlerControl

private static readonly string _appDataPath = Environment.GetEnvironmentVariable("USERPROFILE") + "\\AppData\\LocalLow\\Microsoft\\PowerToys\\MonacoPreview-Temp";

private static bool _doesGpoDisableMonaco = global::PowerToys.GPOWrapper.GPOWrapper.GetConfiguredMonacoPreviewEnabledValue() == global::PowerToys.GPOWrapper.GpoRuleConfigured.Disabled;
private static readonly bool _doesGpoDisableMonaco = global::PowerToys.GPOWrapper.GPOWrapper.GetConfiguredMonacoPreviewEnabledValue() == global::PowerToys.GPOWrapper.GpoRuleConfigured.Disabled;

private Task _gatherFileInformationTask;

Expand Down Expand Up @@ -213,7 +213,7 @@ private async void WebView2Init(object sender, CoreWebView2NavigationCompletedEv
if (!_hasNavigated)
{
await _gatherFileInformationTask.ConfigureAwait(true);
await _webView.CoreWebView2.ExecuteScriptAsync("editor.setValue(\"" + _fileContent.Replace("\"", "\\\"").Replace("\n", "\\n") + "\");").ConfigureAwait(true);
await _webView.CoreWebView2.ExecuteScriptAsync("editor.setValue(\"" + _fileContent.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "\\r") + "\");").ConfigureAwait(true);
await _webView.CoreWebView2.ExecuteScriptAsync("monaco.editor.setModelLanguage(editor.getModel(), \"" + _vsCodeLangSet + "\");").ConfigureAwait(true);
await _webView.CoreWebView2.ExecuteScriptAsync("editor.updateOptions({\"wordWrap\": \"" + (Settings.Wrap ? "on" : "off") + "\"});").ConfigureAwait(true);
await _webView.CoreWebView2.ExecuteScriptAsync("editor.updateOptions({\"theme\": \"" + (Settings.GetTheme() == "dark" ? "vs-dark" : "vs") + "\"});").ConfigureAwait(true);
Expand Down
2 changes: 1 addition & 1 deletion src/modules/previewpane/MonacoPreviewHandler/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace Microsoft.PowerToys.PreviewHandler.Monaco
{
internal static class Program
{
private static CancellationTokenSource _tokenSource = new();
private static readonly CancellationTokenSource _tokenSource = new();

private static MonacoPreviewHandlerControl _previewHandlerControl;

Expand Down

1 comment on commit edc52c8

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@check-spelling-bot Report

🔴 Please review

See the 📜action log or 📝 job summary for details.

Unrecognized words (2)

backgrounding
phishing

Previously acknowledged words that are now absent COMMANDTITLE FILELOCKSMITHLIB interactable JArray ksh localport OOBEPT Pathto qwertyuiopasdfghjklzxcvbnm qwrtyuiopsghjklzxvnm redirectedfrom runsettings testhost toggleswitch 🫥
To accept these unrecognized words as correct and remove the previously acknowledged and now absent words, you could run the following commands

... in a clone of the [email protected]:microsoft/PowerToys.git repository
on the dev/aaron-junker/monaco-fast-laod branch (ℹ️ how do I use this?):

curl -s -S -L 'https://raw.githubusercontent.com/check-spelling/check-spelling/v0.0.22/apply.pl' |
perl - 'https://github.com/microsoft/PowerToys/actions/runs/8703604841/attempts/1'
Available 📚 dictionaries could cover words (expected and unrecognized) not in the 📘 dictionary

This includes both expected items (1873) from .github/actions/spell-check/expect.txt and unrecognized words (2)

Dictionary Entries Covers Uniquely
cspell:r/src/r.txt 543 1 1
cspell:cpp/src/people.txt 23 1
cspell:cpp/src/ecosystem.txt 51 1

Consider adding them (in .github/workflows/spelling2.yml) for uses: check-spelling/[email protected] in its with:

      with:
        extra_dictionaries:
          cspell:r/src/r.txt
          cspell:cpp/src/people.txt
          cspell:cpp/src/ecosystem.txt

To stop checking additional dictionaries, add (in .github/workflows/spelling2.yml) for uses: check-spelling/[email protected] in its with:

check_extra_dictionaries: ''
If the flagged items are 🤯 false positives

If items relate to a ...

  • binary file (or some other file you wouldn't want to check at all).

    Please add a file path to the excludes.txt file matching the containing file.

    File paths are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your files.

    ^ refers to the file's path from the root of the repository, so ^README\.md$ would exclude README.md (on whichever branch you're using).

  • well-formed pattern.

    If you can write a pattern that would match it,
    try adding it to the patterns.txt file.

    Patterns are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your lines.

    Note that patterns can't match multiline strings.

Please sign in to comment.