Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions src/OneWare.Essentials/Controls/SegmentedControl.axaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="using:OneWare.Essentials.Controls">
<Design.PreviewWith>
<controls:SegmentedControl Margin="20" SelectedIndex="0">
<controls:SegmentedControlItem Content="Available" />
<controls:SegmentedControlItem Content="Installed" />
<controls:SegmentedControlItem Content="Updates" />
</controls:SegmentedControl>
</Design.PreviewWith>

<Styles.Resources>
<ControlTheme x:Key="{x:Type controls:SegmentedControl}" TargetType="controls:SegmentedControl">
<Setter Property="Background" Value="{DynamicResource ThemeControlMidBrush}" />
<Setter Property="BorderBrush" Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="4" />
<Setter Property="Padding" Value="2" />
<Setter Property="Template">
<ControlTemplate>
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{TemplateBinding CornerRadius}"
Padding="{TemplateBinding Padding}">
<ItemsPresenter Name="PART_ItemsPresenter"
ItemsPanel="{TemplateBinding ItemsPanel}" />
</Border>
</ControlTemplate>
</Setter>
</ControlTheme>

<ControlTheme x:Key="{x:Type controls:SegmentedControlItem}" TargetType="controls:SegmentedControlItem">
<Setter Property="Foreground" Value="{DynamicResource ThemeForegroundBrush}" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="CornerRadius" Value="3" />
<Setter Property="Padding" Value="8 2" />
<Setter Property="Margin" Value="1 0" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border"
Background="{TemplateBinding Background}"
CornerRadius="{TemplateBinding CornerRadius}"
Padding="{TemplateBinding Padding}">
<ContentPresenter Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</Border>
</ControlTemplate>
</Setter>

<Style Selector="^:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeControlHighlightMidBrush}" />
</Style>
<Style Selector="^:selected">
<Setter Property="Background" Value="{DynamicResource ThemeAccentBrush}" />
<Setter Property="Foreground" Value="{DynamicResource ThemeForegroundBrush}" />
</Style>
<Style Selector="^:selected:pointerover">
<Setter Property="Background" Value="{DynamicResource ThemeAccentBrush}" />
</Style>
</ControlTheme>
</Styles.Resources>
</Styles>
70 changes: 70 additions & 0 deletions src/OneWare.Essentials/Controls/SegmentedControl.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Mixins;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Input;
using Avalonia.Layout;

namespace OneWare.Essentials.Controls;

/// <summary>
/// A generic single-selection segmented control that lays its items out horizontally.
/// Items can be plain objects or <see cref="SegmentedControlItem" /> instances.
/// </summary>
public class SegmentedControl : SelectingItemsControl
{
private static readonly FuncTemplate<Panel?> DefaultPanel =
new(() => new StackPanel { Orientation = Orientation.Horizontal });

static SegmentedControl()
{
SelectionModeProperty.OverrideDefaultValue<SegmentedControl>(
SelectionMode.Single | SelectionMode.AlwaysSelected);
ItemsPanelProperty.OverrideDefaultValue<SegmentedControl>(DefaultPanel);
}

protected override Type StyleKeyOverride => typeof(SegmentedControl);

protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);

if (e.Source is Visual source && e.GetCurrentPoint(source).Properties.IsLeftButtonPressed)
e.Handled = UpdateSelectionFromEventSource(e.Source);
}

protected override Control CreateContainerForItemOverride(object? item, int index, object? recycleKey)
{
return new SegmentedControlItem();
}

protected override bool NeedsContainerOverride(object? item, int index, out object? recycleKey)
{
return NeedsContainer<SegmentedControlItem>(item, out recycleKey);
}
}

/// <summary>
/// Container for an item hosted inside a <see cref="SegmentedControl" />.
/// </summary>
public class SegmentedControlItem : ContentControl, ISelectable
{
public static readonly StyledProperty<bool> IsSelectedProperty =
SelectingItemsControl.IsSelectedProperty.AddOwner<SegmentedControlItem>();

static SegmentedControlItem()
{
SelectableMixin.Attach<SegmentedControlItem>(IsSelectedProperty);
PressedMixin.Attach<SegmentedControlItem>();
FocusableProperty.OverrideDefaultValue<SegmentedControlItem>(true);
}

public bool IsSelected
{
get => GetValue(IsSelectedProperty);
set => SetValue(IsSelectedProperty, value);
}

protected override Type StyleKeyOverride => typeof(SegmentedControlItem);
}
1 change: 1 addition & 0 deletions src/OneWare.Essentials/Controls/SharedControls.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@

<StyleInclude Source="avares://OneWare.Essentials/Controls/ComparisonControl.axaml" />
<StyleInclude Source="avares://OneWare.Essentials/Controls/SearchComboBox.axaml" />
<StyleInclude Source="avares://OneWare.Essentials/Controls/SegmentedControl.axaml" />
<StyleInclude Source="avares://OneWare.Essentials/Controls/UiExtensionCollection.axaml" />
</Styles>
2 changes: 1 addition & 1 deletion src/OneWare.Essentials/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public static bool EqualUrls(this string url1, string url2)
StringComparison.OrdinalIgnoreCase)
&& string.Equals(uri1.Query, uri2.Query, StringComparison.Ordinal);
}

public static bool ContainsSubPath(this string pathToFile, string subPath)
{
pathToFile = Path.GetDirectoryName(pathToFile) + "\\";
Expand Down
2 changes: 2 additions & 0 deletions src/OneWare.Essentials/PackageManager/Package.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ public class Package
public string? UrlLaunchIds { get; init; }

public string? IconUrl { get; init; }

public string? Icon { get; set; }

public string? SourceUrl { get; init; }

Expand Down
8 changes: 7 additions & 1 deletion src/OneWare.Essentials/PackageManager/PackageManifest.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
namespace OneWare.Essentials.PackageManager;
using System.Text.Json;

namespace OneWare.Essentials.PackageManager;

public class PackageManifest
{
public string? ManifestUrl { get; init; }

public JsonElement? Content { get; init; }

public string? Icon { get; init; }
}
7 changes: 7 additions & 0 deletions src/OneWare.Essentials/Services/IPackageService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@ public interface IPackageService : INotifyPropertyChanged
/// </summary>
void RegisterPackageRepository(string url);

/// <summary>
/// Registers a package repository URL with fallback URLs.
/// Uses the first URL of the array that works.
/// </summary>
/// <param name="urls"></param>
void RegisterPackageRepositoryWithFallback(string[] urls);

/// <summary>
/// Registers a package installer for a package type.
/// </summary>
Expand Down
2 changes: 1 addition & 1 deletion src/OneWare.PackageManager/Services/IPackageCatalog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ public interface IPackageCatalog
{
IReadOnlyDictionary<string, Package> Manifests { get; }

Task<bool> RefreshAsync(IEnumerable<string> sources, CancellationToken cancellationToken = default);
Task<bool> RefreshAsync(IEnumerable<string[]> repositories, CancellationToken cancellationToken = default);

void RegisterStandalone(Package package);
}
38 changes: 23 additions & 15 deletions src/OneWare.PackageManager/Services/PackageCatalog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,27 +26,35 @@ public void RegisterStandalone(Package package)
_manifests[package.Id] = package;
}

public async Task<bool> RefreshAsync(IEnumerable<string> sources, CancellationToken cancellationToken = default)
public async Task<bool> RefreshAsync(IEnumerable<string[]> repositories, CancellationToken cancellationToken = default)
{
var result = true;
var newPackages = new Dictionary<string, Package>();

foreach (var source in sources)
foreach (var repository in repositories)
{
IReadOnlyList<Package> loaded;
try
IReadOnlyList<Package> loaded = new List<Package>();
foreach (var source in repository)
{
loaded = await _repositoryClient.LoadRepositoryAsync(source, cancellationToken);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception e)
{
_logger.Error($"Failed to refresh package source '{source}'.", e);
result = false;
continue;
try
{
loaded = await _repositoryClient.LoadRepositoryAsync(source, cancellationToken);
if(loaded.Count == 0)
{
continue;
}
break;
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception e)
{
_logger.Error($"Failed to refresh package source '{source}'.", e);
result = false;
continue;
}
}

if (loaded.Count == 0)
Expand Down
66 changes: 53 additions & 13 deletions src/OneWare.PackageManager/Services/PackageRepositoryClient.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
using OneWare.Essentials.PackageManager;
using OneWare.Essentials.Services;
Expand Down Expand Up @@ -29,13 +28,12 @@ public async Task<IReadOnlyList<Package>> LoadRepositoryAsync(string url,
{
try
{
var repositoryString = await _httpService.DownloadTextAsync(url, TimeSpan.FromSeconds(10));
var repositoryString = await _httpService.DownloadTextAsync(url, TimeSpan.FromSeconds(10), cancellationToken);
if (repositoryString == null) return Array.Empty<Package>();

var trimmed = WhitespaceRegex().Replace(repositoryString, "");
var packages = new List<Package>();

if (trimmed.StartsWith("{\"packages\":", StringComparison.OrdinalIgnoreCase))
if (IsRepositoryJson(repositoryString))
{
try
{
Expand All @@ -45,12 +43,7 @@ public async Task<IReadOnlyList<Package>> LoadRepositoryAsync(string url,
foreach (var manifest in repository.Packages)
try
{
if (manifest.ManifestUrl == null) continue;

var downloadManifest =
await _httpService.DownloadTextAsync(manifest.ManifestUrl);

var package = JsonSerializer.Deserialize<Package>(downloadManifest!, SerializerOptions);
var package = await LoadPackageManifestAsync(manifest, cancellationToken);

if (package != null) packages.Add(package);
}
Expand Down Expand Up @@ -97,10 +90,57 @@ public async Task<IReadOnlyList<Package>> LoadRepositoryAsync(string url,
catch (Exception e)
{
_logger.Error($"Failed to load package source '{url}'.", e);
return Array.Empty<Package>();
return [];
}
}

[GeneratedRegex(@"\s+")]
private static partial Regex WhitespaceRegex();
private async Task<Package?> LoadPackageManifestAsync(PackageManifest manifest,
CancellationToken cancellationToken)
{
var manifestContent = GetManifestContent(manifest.Content);

if (manifestContent == null)
{
if (string.IsNullOrWhiteSpace(manifest.ManifestUrl))
return null;

manifestContent = await _httpService.DownloadTextAsync(manifest.ManifestUrl, cancellationToken: cancellationToken);
}

if (string.IsNullOrWhiteSpace(manifestContent))
return null;

var package = JsonSerializer.Deserialize<Package>(manifestContent, SerializerOptions);

if (package != null && string.IsNullOrWhiteSpace(package.Icon) && !string.IsNullOrWhiteSpace(manifest.Icon))
package.Icon = manifest.Icon;

return package;
}

private static bool IsRepositoryJson(string json)
{
using var document = JsonDocument.Parse(json, new JsonDocumentOptions
{
AllowTrailingCommas = true
});

return document.RootElement.ValueKind == JsonValueKind.Object
&& document.RootElement.TryGetProperty("packages", out var packages)
&& packages.ValueKind == JsonValueKind.Array;
}

private static string? GetManifestContent(JsonElement? content)
{
if (content is not { } contentElement) return null;

return contentElement.ValueKind switch
{
JsonValueKind.String => string.IsNullOrWhiteSpace(contentElement.GetString())
? null
: contentElement.GetString(),
JsonValueKind.Object => contentElement.GetRawText(),
_ => null
};
}
}
Loading
Loading