Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use webview2 control, fix background color of webview #182

Merged
merged 9 commits into from
Dec 17, 2023
1 change: 1 addition & 0 deletions FoliCon/FoliCon.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ dineshsolanki.github.io/folicon/</Description>
<PackageReference Include="IGDB" Version="3.0.0" />
<PackageReference Include="Jot" Version="2.1.17" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="8.0.0" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2210.55" />
<PackageReference Include="NLog" Version="5.2.6" />
<PackageReference Include="Ookii.Dialogs.Wpf" Version="5.0.1" />
<PackageReference Include="Polly" Version="8.2.0" />
Expand Down
12 changes: 5 additions & 7 deletions FoliCon/Modules/Extension/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,13 @@ public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable
{
return new ObservableCollection<T>(col);
}
public static Task<Bitmap> GetBitmap(this HttpResponseMessage responseMessage)
public static async Task<Bitmap> GetBitmap(this HttpResponseMessage responseMessage)
{
Logger.Trace("GetBitmap from HttpResponseMessage");
return responseMessage.Content.ReadAsStreamAsync().ContinueWith(t =>
{
Bitmap bitmap = new(t.Result);
Logger.Trace("GetBitmap from HttpResponseMessage - done");
return bitmap;
});
var stream = await responseMessage.Content.ReadAsStreamAsync();
var bitmap = new Bitmap(stream);
Logger.Trace("GetBitmap from HttpResponseMessage - done");
return bitmap;
}

public static void SentryConfig(this LoggingConfiguration config, bool enableSentry)
Expand Down
61 changes: 34 additions & 27 deletions FoliCon/ViewModels/SearchResultViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -389,51 +389,58 @@ private async Task GetGameTrailer(string itemId)

private async Task GetMovieTrailer(string itemId)
{
await _tmdbObject.GetClient().GetMovieVideosAsync(itemId.ConvertToInt()).ContinueWith(item =>
try
{
if (item.Result == null) return;
var i = ChooseTrailer(item.Result.Results);
if (i != null)
{
SetTrailer(i.Key);
}
else
var result = await _tmdbObject.GetClient().GetMovieVideosAsync(itemId.ConvertToInt());

if (result != null)
{
Logger.Warn("No trailer found for {Title}", ResultListViewData.SelectedItem.Title);
var trailer = ChooseTrailer(result.Results);
if (trailer != null)
{
SetTrailer(trailer.Key);
}
else
{
Logger.Warn("No trailer found for {Title}", ResultListViewData.SelectedItem.Title);
}
}
});
}
catch (Exception ex)
{
Logger.Error(ex, "Error fetching movie trailer for {Title}", ResultListViewData.SelectedItem.Title);
}
}

private async Task GetTvTrailer(string itemId)
{
await _tmdbObject.GetClient().GetTvShowVideosAsync(itemId.ConvertToInt()).ContinueWith(item =>
var result = await _tmdbObject.GetClient().GetTvShowVideosAsync(itemId.ConvertToInt());

if (result == null) return;

var i = ChooseTrailer(result.Results);

if (i != null)
{
if (item.Result == null) return;
var i = ChooseTrailer(item.Result.Results);
if (i != null)
{
SetTrailer(i.Key);
}
else
{
Logger.Warn("No trailer found for {Title}", ResultListViewData.SelectedItem.Title);
}
});
SetTrailer(i.Key);
}
else
{
Logger.Warn("No trailer found for {Title}", ResultListViewData.SelectedItem.Title);
}
}

private dynamic? ChooseTrailer(IReadOnlyCollection<dynamic> results)
{
if (!results.Any()) return null;
return results.Any(i => i.Type == "Trailer" && i.Site == "YouTube")
? results.First(i => i.Type == "Trailer")
: results.First();
var trailerYouTube = results.FirstOrDefault(item => item?.Type == "Trailer" && item?.Site == "YouTube");
return trailerYouTube != null ? trailerYouTube : results.FirstOrDefault();
}

private void SetTrailer(string trailerKey)
{
ResultListViewData.SelectedItem.TrailerKey = trailerKey;
ResultListViewData.SelectedItem.Trailer =
new Uri("https://www.youtube.com/embed/" + trailerKey);
new Uri($"https://www.youtube.com/embed/{trailerKey}");
Logger.Debug("Trailer for {Title} is {Trailer}", ResultListViewData.SelectedItem.Title,
ResultListViewData.SelectedItem.Trailer);
}
Expand Down
3 changes: 2 additions & 1 deletion FoliCon/Views/HtmlBox.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
mc:Ignorable="d" Background="{DynamicResource RegionBrush}">
<WebBrowser x:Name="Browser"/>
<wv2:WebView2 x:Name="Browser"/>
</UserControl>
127 changes: 70 additions & 57 deletions FoliCon/Views/HtmlBox.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace FoliCon.Views;
/// <summary>
/// Interaction logic for HtmlBox.xaml
/// </summary>
public partial class HtmlBox : UserControl
public partial class HtmlBox
{
private const string VideoUnavailable = "Video not available!";
private readonly string _backgroundColor;
Expand All @@ -17,12 +17,12 @@ public static readonly DependencyProperty HtmlTextProperty
typeof(HtmlBox),
new PropertyMetadata(default(string), OnHtmlTextPropertyChanged));

public bool IsVideoAvailable => !string.IsNullOrEmpty(HtmlText) && !HtmlText.Contains(VideoUnavailable);
public bool IsVideoAvailable { get; private set; }

public HtmlBox()
{
InitializeComponent();
_backgroundColor = ThemeManager.Current.ApplicationTheme == ApplicationTheme.Dark ? "#000000" : "#FFFFFF";
_backgroundColor = ThemeManager.Current.ApplicationTheme == ApplicationTheme.Dark ? "#1C1C1C" : "#FFFFFF";
}

public string HtmlText
Expand All @@ -31,74 +31,87 @@ public string HtmlText
set => SetValue(HtmlTextProperty, value);
}

private void ProcessBrowse()
private async Task ProcessBrowse()
{
if (Browser is not {IsLoaded: true}) return;

var content = !IsVideoAvailable
? $"""<html><body style="background-color: {_backgroundColor}"></body></html>"""
: GenerateHtmlContent();

if (!IsVideoAvailable)
{
Browser.NavigateToString($"""<html><body style="background-color: {_backgroundColor}"></body></html>""");
return;
}
var content = GenerateHtmlContent();
Browser.NavigateToString(content);
await InitializeAsync(content);
}

private string GenerateHtmlContent()
{
return $$"""

<html lang="{{LangProvider.Culture.TwoLetterISOLanguageName}}">
<head>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<meta content='IE=Edge' http-equiv='X-UA-Compatible'>
<style>
html, body {
overflow: hidden;
margin: 0;
padding: 0;
width: 100%;
height: 100%;
box-sizing: border-box;
}
</style>
<script src='https://code.jquery.com/jquery-latest.min.js' type='text/javascript'></script>
<script>
$(function() {
$('#video').css({
width: $(window).innerWidth() + 'px',
height: $(window).innerHeight() + 'px',
border: 'none'
});
$(window).resize(function() {
$('#video').css({
width: $(window).innerWidth() + 'px',
height: $(window).innerHeight() + 'px'
});
});
});
</script>
</head>
<body style="background-color: {{_backgroundColor}}">
<iframe id='video' allow='autoplay; fullscreen; clipboard-write; encrypted-media; picture-in-picture' allowfullscreen
src='{{HtmlText}}?hl={{LangProvider.Culture.TwoLetterISOLanguageName}}'
style="visibility:hidden;" onload="this.style.visibility='visible';">
</iframe>
</body>
</html>
""";
return string.Format(HtmlTemplate, LangProvider.Culture.TwoLetterISOLanguageName, _backgroundColor, HtmlText);
}

private static void OnHtmlTextPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
private static async void OnHtmlTextPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
var control = source as HtmlBox;
if (control!.CheckAccess())
var htmlText = e.NewValue as string;
if (source is not HtmlBox control)
{
return;
}
control.IsVideoAvailable = !string.IsNullOrEmpty(htmlText) && !htmlText.Contains(VideoUnavailable);
if (control.CheckAccess())
{
control.ProcessBrowse();
await control.ProcessBrowse();
}
else
{
control.Dispatcher.Invoke(control.ProcessBrowse);
await control.Dispatcher.InvokeAsync(control.ProcessBrowse);
}
}

private async Task InitializeAsync(string content)
{
await Browser.EnsureCoreWebView2Async(null);
Browser.DefaultBackgroundColor = ColorTranslator.FromHtml(_backgroundColor);
Browser.CoreWebView2.Settings.AreBrowserAcceleratorKeysEnabled = false;
Browser.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false;
Browser.CoreWebView2.NavigateToString(content);
}

private const string HtmlTemplate = """

<html lang="{0}">
<head>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<style>
html, body {{
overflow: hidden;
margin: 0;
padding: 0;
width: 100%;
height: 100%;
box-sizing: border-box;
}}
</style>
</head>
<body style="background-color: {1}">
<iframe id='video' allow='autoplay; fullscreen; clipboard-write; encrypted-media; picture-in-picture' allowfullscreen
src='{2}?hl={0}'
style="visibility:hidden;" onload="this.style.visibility='visible';">
</iframe>
<script src='https://code.jquery.com/jquery-latest.min.js' type='text/javascript'></script>
<script>
$(function() {{
$('#video').css({{
width: $(window).innerWidth() + 'px',
height: $(window).innerHeight() + 'px',
border: 'none'
}});
$(window).resize(function() {{
$('#video').css({{
width: $(window).innerWidth() + 'px',
height: $(window).innerHeight() + 'px'
}});
}});
}});
</script>
</body>
</html>
""";
}
1 change: 1 addition & 0 deletions Folicon.sln.DotSettings
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/UserDictionary/Words/=faelpessoal/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=FoliCon/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=langs/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Liaher/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=TMDB/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>