Skip to content

Commit

Permalink
Code QA
Browse files Browse the repository at this point in the history
  • Loading branch information
neon-nyan committed Sep 22, 2024
1 parent 1526c6f commit 9a0ef0f
Show file tree
Hide file tree
Showing 23 changed files with 340 additions and 336 deletions.
3 changes: 0 additions & 3 deletions CollapseLauncher/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
using PhotoSauce.MagicScaler;
using PhotoSauce.NativeCodecs.Libwebp;
using System;
using System.Collections.Generic;
using System.Linq;
using Windows.UI;
using static CollapseLauncher.InnerLauncherConfig;
Expand Down Expand Up @@ -148,14 +147,12 @@ public static void ToggleBlurBackdrop(bool useBackdrop = true)
// then select the value, get the type of ResourceDictionary, then enumerate it
foreach (ResourceDictionary list in resource!
.ThemeDictionaries!
.OfType<KeyValuePair<object, object>>()
.Select(x => x.Value)
.OfType<ResourceDictionary>())
{
// Parse the dictionary as type of KeyValuePair<object, object>,
// and get the value which has type of AcrylicBrush only, then enumerate it
foreach (AcrylicBrush theme in list
.OfType<KeyValuePair<object, object>>()
.Select(x => x.Value)
.OfType<AcrylicBrush>())
{
Expand Down
147 changes: 83 additions & 64 deletions CollapseLauncher/Classes/Helper/Animation/AnimationHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
// ReSharper disable CheckNamespace

namespace CollapseLauncher.Helper.Animation
{
Expand Down Expand Up @@ -65,26 +66,26 @@ internal static async Task StartAnimation(this UIElement element, TimeSpan durat
{
foreach (KeyFrameAnimation anim in animBase!)
{
if (element?.DispatcherQueue?.HasThreadAccess ?? false)
if (element.DispatcherQueue?.HasThreadAccess ?? false)
{
anim.Duration = duration;
anim.StopBehavior = AnimationStopBehavior.LeaveCurrentValue;
animGroup.Add(anim);
}
else
element?.DispatcherQueue?.TryEnqueue(() =>
element.DispatcherQueue?.TryEnqueue(() =>
{
anim.Duration = duration;
anim.StopBehavior = AnimationStopBehavior.LeaveCurrentValue;
animGroup.Add(anim);
});
}
if (element?.DispatcherQueue?.HasThreadAccess ?? false)
if (element.DispatcherQueue?.HasThreadAccess ?? false)
{
element.StartAnimation(animGroup);
}
else
element?.DispatcherQueue?.TryEnqueue(() =>
element.DispatcherQueue?.TryEnqueue(() =>
{
element.StartAnimation(animGroup);
});
Expand Down Expand Up @@ -123,69 +124,85 @@ internal static void EnableSingleImplicitAnimation(this UIElement element,
rootFrameVisual.ImplicitAnimations = animationCollection;
}

internal static void EnableImplicitAnimation(this UIElement element,
bool recursiveAssignment = false,
CompositionEasingFunction easingFunction = null)
internal static void EnableImplicitAnimation(this UIElement element, bool recursiveAssignment = false, CompositionEasingFunction easingFunction = null)
{
try
while (true)
{
Visual rootFrameVisual = ElementCompositionPreview.GetElementVisual(element);
Compositor compositor = CompositionTarget.GetCompositorForCurrentThread();

ImplicitAnimationCollection animationCollection =
rootFrameVisual.ImplicitAnimations != null ?
rootFrameVisual.ImplicitAnimations : compositor!.CreateImplicitAnimationCollection();

foreach (VisualPropertyType type in Enum.GetValues<VisualPropertyType>())
try
{
KeyFrameAnimation animation = CreateAnimationByType(compositor, type, 250, 0, easingFunction);
Visual rootFrameVisual = ElementCompositionPreview.GetElementVisual(element);
Compositor compositor = CompositionTarget.GetCompositorForCurrentThread();

if (animation != null)
{
animationCollection[type.ToString()] = animation;
}
}
ImplicitAnimationCollection animationCollection = rootFrameVisual.ImplicitAnimations != null ? rootFrameVisual.ImplicitAnimations : compositor!.CreateImplicitAnimationCollection();

rootFrameVisual.ImplicitAnimations = animationCollection;
element.EnableElementVisibilityAnimation();
}
catch (Exception ex)
{
Logger.LogWriteLine($"[AnimationHelper::EnableImplicitAnimation()] Error has occurred while assigning Implicit Animation to the element!\r\n{ex}", LogType.Error, true);
}
foreach (VisualPropertyType type in Enum.GetValues<VisualPropertyType>())
{
KeyFrameAnimation animation = CreateAnimationByType(compositor, type, 250, 0, easingFunction);

if (!recursiveAssignment) return;
if (animation != null)
{
animationCollection[type.ToString()] = animation;
}
}

if (element is Button button && button.Content is UIElement buttonContent)
buttonContent.EnableImplicitAnimation(recursiveAssignment, easingFunction);
rootFrameVisual.ImplicitAnimations = animationCollection;
element.EnableElementVisibilityAnimation();
}
catch (Exception ex)
{
Logger.LogWriteLine($"[AnimationHelper::EnableImplicitAnimation()] Error has occurred while assigning Implicit Animation to the element!\r\n{ex}", LogType.Error, true);
}

if (element is Page page && page.Content is UIElement pageContent)
pageContent.EnableImplicitAnimation(recursiveAssignment, easingFunction);
if (!recursiveAssignment) return;

if (element is NavigationView navigationView && navigationView.Content is UIElement navigationViewContent)
navigationViewContent.EnableImplicitAnimation(recursiveAssignment, easingFunction);
switch (element)
{
case Button { Content: UIElement buttonContent }:
buttonContent.EnableImplicitAnimation(true, easingFunction);
break;
case Page { Content: not null } page:
page.Content.EnableImplicitAnimation(true, easingFunction);
break;
case NavigationView { Content: UIElement navigationViewContent }:
navigationViewContent.EnableImplicitAnimation(true, easingFunction);
break;
case Panel panel:
{
foreach (UIElement childrenElement in panel.Children!) childrenElement.EnableImplicitAnimation(true, easingFunction);
break;
}
case ScrollViewer { Content: UIElement elementInner }:
elementInner.EnableImplicitAnimation(true, easingFunction);
break;
}

if (element is Panel panel)
foreach (UIElement childrenElement in panel.Children!)
childrenElement.EnableImplicitAnimation(recursiveAssignment, easingFunction);
switch (element)
{
case ContentControl { Content: UIElement contentControlInner } contentControl and (SettingsCard or Expander):
{
contentControlInner.EnableImplicitAnimation(true, easingFunction);

if (element is ScrollViewer scrollViewer && scrollViewer.Content is UIElement elementInner)
elementInner.EnableImplicitAnimation(recursiveAssignment, easingFunction);
if (contentControl is Expander { Header: UIElement expanderHeader })
{
element = expanderHeader;
recursiveAssignment = true;
continue;
}

if (element is ContentControl contentControl && (element is SettingsCard || element is Expander) && contentControl.Content is UIElement contentControlInner)
{
contentControlInner.EnableImplicitAnimation(true, easingFunction);
break;
}
case InfoBar { Content: UIElement infoBarInner }:
element = infoBarInner;
recursiveAssignment = true;
continue;
}

if (contentControl is Expander expander && expander.Header is UIElement expanderHeader)
expanderHeader.EnableImplicitAnimation(true, easingFunction);
break;
}

if (element is InfoBar infoBar && infoBar.Content is UIElement infoBarInner)
infoBarInner.EnableImplicitAnimation(true, easingFunction);
}

private static KeyFrameAnimation CreateAnimationByType(Compositor compositor, VisualPropertyType type,
double duration = 800, double delay = 0, CompositionEasingFunction easing = null)
double duration = 800, double delay = 0, CompositionEasingFunction easing = null)
{
KeyFrameAnimation animation;

Expand All @@ -202,6 +219,8 @@ private static KeyFrameAnimation CreateAnimationByType(Compositor compositor, Vi
case VisualPropertyType.RotationAngleInDegrees:
animation = compositor.CreateScalarKeyFrameAnimation();
break;
case VisualPropertyType.None:
case VisualPropertyType.All:
default:
return null;
}
Expand All @@ -221,25 +240,25 @@ public static void EnableElementVisibilityAnimation(this UIElement element, Comp

ElementCompositionPreview.SetIsTranslationEnabled(element, true);

ScalarKeyFrameAnimation HideOpacityAnimation = compositor.CreateScalarKeyFrameAnimation();
ScalarKeyFrameAnimation ShowOpacityAnimation = compositor.CreateScalarKeyFrameAnimation();
ScalarKeyFrameAnimation hideOpacityAnimation = compositor.CreateScalarKeyFrameAnimation();
ScalarKeyFrameAnimation showOpacityAnimation = compositor.CreateScalarKeyFrameAnimation();

HideOpacityAnimation.InsertKeyFrame(1.0f, 0.0f);
HideOpacityAnimation.Duration = animDur;
HideOpacityAnimation.Target = "Opacity";
hideOpacityAnimation.InsertKeyFrame(1.0f, 0.0f);
hideOpacityAnimation.Duration = animDur;
hideOpacityAnimation.Target = "Opacity";

ShowOpacityAnimation.InsertKeyFrame(1.0f, 1.0f);
ShowOpacityAnimation.Duration = animDur;
ShowOpacityAnimation.Target = "Opacity";
showOpacityAnimation.InsertKeyFrame(1.0f, 1.0f);
showOpacityAnimation.Duration = animDur;
showOpacityAnimation.Target = "Opacity";

CompositionAnimationGroup HideAnimationGroup = compositor.CreateAnimationGroup();
CompositionAnimationGroup ShowAnimationGroup = compositor.CreateAnimationGroup();
CompositionAnimationGroup hideAnimationGroup = compositor.CreateAnimationGroup();
CompositionAnimationGroup showAnimationGroup = compositor.CreateAnimationGroup();

HideAnimationGroup.Add(HideOpacityAnimation);
ShowAnimationGroup.Add(ShowOpacityAnimation);
hideAnimationGroup.Add(hideOpacityAnimation);
showAnimationGroup.Add(showOpacityAnimation);

ElementCompositionPreview.SetImplicitHideAnimation(element, HideAnimationGroup);
ElementCompositionPreview.SetImplicitShowAnimation(element, ShowAnimationGroup);
ElementCompositionPreview.SetImplicitHideAnimation(element, hideAnimationGroup);
ElementCompositionPreview.SetImplicitShowAnimation(element, showAnimationGroup);
}

internal static Compositor GetElementCompositor(this UIElement element)
Expand Down
38 changes: 21 additions & 17 deletions CollapseLauncher/Classes/Helper/Image/ImageLoaderHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@
using CollapseLauncher.Extension;
using CollapseLauncher.Helper.Background;
using CommunityToolkit.WinUI.Animations;
using CommunityToolkit.WinUI.Controls;
using CommunityToolkit.WinUI.Media;
using Hi3Helper;
using Hi3Helper.CommunityToolkit.WinUI.Controls;
using Hi3Helper.Data;
using Microsoft.UI.Text;
using Microsoft.UI.Xaml;
Expand Down Expand Up @@ -159,7 +157,7 @@ internal static async Task<FileStream> LoadImage(string path, bool isUseImageCro
}

private static async Task<FileStream> SpawnImageCropperDialog(string filePath, string cachedFilePath,
uint ToWidth, uint ToHeight)
uint toWidth, uint toHeight)
{
Grid parentGrid = new()
{
Expand Down Expand Up @@ -226,7 +224,7 @@ private static async Task<FileStream> SpawnImageCropperDialog(string filePath, s
}

FileInfo cachedFileInfo = new FileInfo(cachedFilePath);
return await GenerateCachedStream(cachedFileInfo, ToWidth, ToHeight, true);
return await GenerateCachedStream(cachedFileInfo, toWidth, toHeight, true);
}

private static async void LoadImageCropperDetached(string filePath, ImageCropper imageCropper,
Expand Down Expand Up @@ -403,19 +401,22 @@ public static bool IsFileCompletelyDownloaded(FileInfo fileInfo)

// Try to get the prop file which includes the filename + the suggested size provided
// by the network stream if it has been downloaded before
string propFilePath = Directory.EnumerateFiles(outputParentPath, $"{outputFileName}#*", SearchOption.TopDirectoryOnly).FirstOrDefault();
// Check if the file is found (not null), then try parse the information
if (string.IsNullOrEmpty(propFilePath))
if (outputParentPath != null)
{
return false;
}
string propFilePath = Directory.EnumerateFiles(outputParentPath, $"{outputFileName}#*", SearchOption.TopDirectoryOnly).FirstOrDefault();
// Check if the file is found (not null), then try parse the information
if (string.IsNullOrEmpty(propFilePath))
{
return false;
}

// Try split the filename into a segment by # char
string[] propSegment = Path.GetFileName(propFilePath).Split('#');
// Assign the check if the condition met and set the file existence status
return propSegment.Length >= 2
&& long.TryParse(propSegment[1], null, out long suggestedSize)
&& fileInfo.Exists && fileInfo.Length == suggestedSize;
// Try split the filename into a segment by # char
string[] propSegment = Path.GetFileName(propFilePath).Split('#');
// Assign the check if the condition met and set the file existence status
return propSegment.Length >= 2
&& long.TryParse(propSegment[1], null, out long suggestedSize)
&& fileInfo.Exists && fileInfo.Length == suggestedSize;
}

// If the prop doesn't exist, then return false to assume that the file doesn't exist
}
Expand Down Expand Up @@ -446,8 +447,11 @@ public static async ValueTask TryDownloadToCompleteness(string url, FileInfo fil
// Create the prop file for download completeness checking
string outputParentPath = Path.GetDirectoryName(fileInfo.FullName);
string outputFilename = Path.GetFileName(fileInfo.FullName);
string propFilePath = Path.Combine(outputParentPath, $"{outputFilename}#{netStream.Length}");
await File.Create(propFilePath).DisposeAsync();
if (outputParentPath != null)
{
string propFilePath = Path.Combine(outputParentPath, $"{outputFilename}#{netStream.Length}");
await File.Create(propFilePath).DisposeAsync();
}

// Copy (and download) the remote streams to local
int read;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Text.Json.Serialization;
using System.Threading;
using WinRT;
// ReSharper disable PartialTypeWithSinglePart

namespace CollapseLauncher.Helper.LauncherApiLoader.Sophon
{
Expand Down Expand Up @@ -84,7 +85,7 @@ public List<LauncherGameNewsPost>? NewsPostTypeInfo
return _newsPostTypeInfo;
}

_newsPostTypeInfo = NewsPost.Where(x => x.PostType == LauncherGameNewsPostType.POST_TYPE_INFO)?
_newsPostTypeInfo = NewsPost.Where(x => x.PostType == LauncherGameNewsPostType.POST_TYPE_INFO)
.OrderBy(x => x.PostOrder)
.ToList();
return _newsPostTypeInfo;
Expand All @@ -106,7 +107,7 @@ public List<LauncherGameNewsPost>? NewsPostTypeActivity
return _newsPostTypeActivity;
}

_newsPostTypeActivity = NewsPost.Where(x => x.PostType == LauncherGameNewsPostType.POST_TYPE_ACTIVITY)?
_newsPostTypeActivity = NewsPost.Where(x => x.PostType == LauncherGameNewsPostType.POST_TYPE_ACTIVITY)
.OrderBy(x => x.PostOrder)
.ToList();
return _newsPostTypeActivity;
Expand All @@ -129,7 +130,7 @@ public List<LauncherGameNewsPost>? NewsPostTypeAnnouncement
}

_newsPostTypeAnnouncement = NewsPost
.Where(x => x.PostType == LauncherGameNewsPostType.POST_TYPE_ANNOUNCE)?
.Where(x => x.PostType == LauncherGameNewsPostType.POST_TYPE_ANNOUNCE)
.OrderBy(x => x.PostOrder)
.ToList();
return _newsPostTypeAnnouncement;
Expand Down
Loading

0 comments on commit 9a0ef0f

Please sign in to comment.