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
1 change: 1 addition & 0 deletions CHANGELOG.en-US.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ English (US) release notes, mirroring CHANGELOG.md (Brazilian Portuguese). Befor
### What's new
- Desktop icons go back where they were after a session: changing the main display could make Windows reshuffle them. Console Mode saves their positions before touching the screens and puts them back a few seconds after the desk is restored. Toggle it in Settings → **Put desktop icons back in place** (on by default); it does nothing while **Auto arrange icons** is on. (#167)
- **Wake the PC with the controller**: in Settings (and in the Console System tab → Controller), Console Mode shows whether the Xbox Wireless Adapter, Bluetooth or a wired controller can wake the PC from sleep, and **Turn on** enables it for them (Windows asks for administrator permission). Together with **Enter when a controller connects**, pressing the controller's center button wakes the PC straight into console mode. It doesn't work when the PC is shut down or hibernating. (#168)
- Console interface: the Home tiles show the official Steam, Playnite and Xbox logos, read from the installed apps, and Custom app shows its `.exe` icon. When an app isn't installed, its tile keeps the generic icon. (#169)

## [1.7.0-alpha.2]
### What's new
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ Notas em português do Brasil; a versão em inglês (Estados Unidos) fica em `CH
### Novidades
- Os ícones da área de trabalho voltam ao lugar depois da sessão: trocar a tela principal podia fazer o Windows embaralhá-los. O Console Mode salva a posição antes de mexer nas telas e os recoloca alguns segundos depois de restaurar a mesa. Liga e desliga em Ajustes → **Devolver os ícones da área de trabalho ao lugar** (ligado por padrão); não faz nada com **Organizar ícones automaticamente** ligado. (#167)
- **Acordar o PC pelo controle**: em Ajustes (e na aba Sistema → Controle do modo Console), o Console Mode mostra se o adaptador sem fio Xbox, o Bluetooth ou o controle no cabo podem acordar o PC da suspensão e, em **Ativar**, liga isso para eles (o Windows pede permissão de administrador). Junto com **Entrar ao conectar um controle**, apertar o botão central do controle acorda o PC direto no modo console. Não funciona com o PC desligado ou em hibernação. (#168)
- Interface Console: os blocos do Início mostram os logos oficiais da Steam, do Playnite e do Xbox, lidos dos apps instalados, e o Aplicativo personalizado mostra o ícone do seu `.exe`. Sem o app instalado, o bloco mantém o ícone genérico. (#169)

## [1.7.0-alpha.2]
### Novidades
Expand Down
1 change: 1 addition & 0 deletions docs/TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,7 @@ Pré-requisito: RivaTuner Statistics Server instalado, com "Show On-Screen Displ

### Início
- [ ] Os iniciadores aparecem numa fileira no topo (Steam Big Picture, Playnite se instalado, modo Xbox), cada um com sua cor e ícone; o que abre hoje tem o selo ✓ verde no canto e uma barra verde embaixo, e os outros ficam mais apagados.
- [ ] Logos oficiais nos blocos: Steam Big Picture com o logo da Steam, Playnite com o do Playnite e modo Xbox com o do app Xbox, nítidos na TV 4K (sem serrilhado nem borrão). Aplicativo personalizado mostra o ícone do `.exe` escolhido e troca ao escolher outro; Playnite troca ao escolher outra pasta. Sem a Steam ou o app Xbox instalado, o bloco mostra o ícone genérico de antes, sem bloco vazio. Resultado: ______
- [ ] Com o controle, subir do Jogar agora chega na fileira; o bloco focado cresce e ganha o contorno branco, sem cortar nos vizinhos nem no topo.
- [ ] Andar pela fileira já troca o iniciador, sem apertar A: o selo, a barra e o título grande embaixo seguem o foco, e a escolha aparece igual em Sistema → Ao entrar no modo console → Abrir e no modo PC.
- [ ] A num iniciador (ou um clique) abre direto aquele iniciador, como o Jogar agora. Sem tela de jogo escolhida, A só escolhe e não abre nada.
Expand Down
38 changes: 38 additions & 0 deletions src/ConsoleMode/Native/PackageLogos.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using System.Xml.Linq;
using ConsoleMode.Services;

namespace ConsoleMode.Native;

/// <summary>The app-list logo file of an installed Store app, at the biggest size it ships.</summary>
internal static class PackageLogos
{
/// <summary>Never throws: null when the app isn't installed or its logo can't be found.</summary>
public static string? Find(string appUserModelId)
{
try
{
var parts = appUserModelId.Split('!', 2);
if (parts.Length != 2) return null;
var package = new Windows.Management.Deployment.PackageManager()
.FindPackagesForUser(string.Empty, parts[0]).FirstOrDefault();
var folder = package?.InstalledLocation?.Path;
if (string.IsNullOrWhiteSpace(folder)) return null;

var manifest = XDocument.Load(Path.Combine(folder, "AppxManifest.xml"));
var app = manifest.Descendants().FirstOrDefault(e => e.Name.LocalName == "Application" && (string?)e.Attribute("Id") == parts[1]);
var visuals = app?.Descendants().FirstOrDefault(e => e.Name.LocalName == "VisualElements");
var logo = (string?)visuals?.Attribute("Square44x44Logo") ?? (string?)visuals?.Attribute("Square150x150Logo");
if (string.IsNullOrWhiteSpace(logo)) return null;

var logoFolder = Path.Combine(folder, Path.GetDirectoryName(logo) ?? "");
return Directory.Exists(logoFolder)
? PackageLogo.Pick(logo, Directory.EnumerateFiles(logoFolder, Path.GetFileNameWithoutExtension(logo) + "*"))
: null;
}
catch (Exception ex)
{
AppLog.Write($"Início: logo de {appUserModelId}: {ex.Message}");
return null;
}
}
}
25 changes: 22 additions & 3 deletions src/ConsoleMode/Native/WindowIcons.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,29 @@ public static class WindowIcons
}
}

private static IconBitmap? FromPackage(SwitchWindow window, int size)
/// <summary>
/// An app's own logo, for the console Home's launcher tiles: a Store app's by its AppUserModelID,
/// otherwise its exe's icon. Never throws: null means the tile keeps its glyph.
/// </summary>
public static IconBitmap? ForApp(string? exePath, string? appUserModelId, int size)
{
try
{
return (appUserModelId is null ? null : FromAppId(appUserModelId, size))
?? (File.Exists(exePath) ? FromExe(exePath, size) : null);
}
catch (Exception ex)
{
AppLog.Write($"Início: ícone de \"{appUserModelId ?? exePath}\": {ex.Message}");
return null;
}
}

private static IconBitmap? FromPackage(SwitchWindow window, int size) =>
AppUserModelIdOf(window) is { } id ? FromAppId(id, size) : null;

private static IconBitmap? FromAppId(string id, int size)
{
var id = AppUserModelIdOf(window);
if (id is null) return null;
var factoryId = typeof(IShellItemImageFactory).GUID;
if (SHCreateItemFromParsingName($@"shell:AppsFolder\{id}", 0, ref factoryId, out var factory) != 0 || factory is null) return null;
try
Expand Down
3 changes: 3 additions & 0 deletions src/ConsoleMode/Services/LaunchArt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ public static class LaunchArt

public static readonly Art Neutral = new("", 0xFF2A3038, 0xFF161A20);

/// <summary>The Xbox app, whose logo stands for the Xbox mode (the glyph shows if it is not installed).</summary>
public const string XboxAppId = "Microsoft.GamingApp_8wekyb3d8bbwe!Microsoft.Xbox.App";

public static Art For(string? mode) => mode switch
{
"bigPicture" => new("", 0xFF2A475E, 0xFF15202C),
Expand Down
52 changes: 52 additions & 0 deletions src/ConsoleMode/Services/PackageLogo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
namespace ConsoleMode.Services;

/// <summary>
/// Picks the sharpest file of a Store app's logo. The manifest names it as "Assets\Logo.png", but the
/// package holds variants such as "Logo.targetsize-256.png" or "Logo.scale-200.png"; the shell
/// only hands out the small one, which looks blurred on a TV tile.
/// </summary>
public static class PackageLogo
{
/// <summary>The best file among <paramref name="files"/> (names in the logo's folder), or null.</summary>
public static string? Pick(string manifestLogo, IEnumerable<string> files)
{
var stem = Path.GetFileNameWithoutExtension(manifestLogo);
var extension = Path.GetExtension(manifestLogo);
if (string.IsNullOrWhiteSpace(stem)) return null;

string? best = null;
var bestScore = int.MinValue;
foreach (var file in files)
{
var name = Path.GetFileName(file);
if (!name.StartsWith(stem, StringComparison.OrdinalIgnoreCase)
|| !name.EndsWith(extension, StringComparison.OrdinalIgnoreCase)) continue;
var rest = name[stem.Length..^extension.Length];
// "Logo2.png" is another file, not a variant of "Logo.png".
if (rest.Length > 0 && rest[0] != '.') continue;
var qualifiers = rest.TrimStart('.');
if (Score(qualifiers) is not { } score || score <= bestScore) continue;
best = file;
bestScore = score;
}
return best;
}

/// <summary>Bigger wins; the unplated form beats the plated one at the same size. Contrast themes are skipped.</summary>
private static int? Score(string qualifiers)
{
if (qualifiers.Length == 0) return 0;
var size = 0;
var unplated = false;
foreach (var part in qualifiers.Split('_'))
{
if (part.StartsWith("contrast-", StringComparison.OrdinalIgnoreCase)) return null;
if (part.Equals("altform-unplated", StringComparison.OrdinalIgnoreCase)) unplated = true;
else if (part.StartsWith("altform-", StringComparison.OrdinalIgnoreCase)) return null;
else if (part.StartsWith("targetsize-", StringComparison.OrdinalIgnoreCase) && int.TryParse(part[11..], out var target)) size = target;
// scale-200 of a 44 px logo is 88 px.
else if (part.StartsWith("scale-", StringComparison.OrdinalIgnoreCase) && int.TryParse(part[6..], out var scale)) size = 44 * scale / 100;
}
return size * 2 + (unplated ? 1 : 0);
}
}
1 change: 1 addition & 0 deletions src/ConsoleMode/ViewModels/MainViewModel.CustomApp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ partial void OnCustomAppPathChanged(string value)
{
OnPropertyChanged(nameof(CustomAppName));
OnPropertyChanged(nameof(CustomAppPathText));
RefreshLaunchLogo(CustomApp.Mode);
SettingChanged();
}

Expand Down
70 changes: 70 additions & 0 deletions src/ConsoleMode/ViewModels/MainViewModel.LaunchTiles.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
using System.Collections.ObjectModel;
using System.Runtime.InteropServices.WindowsRuntime;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ConsoleMode.Models;
using ConsoleMode.Native;
using ConsoleMode.Services;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Imaging;

namespace ConsoleMode.ViewModels;

Expand All @@ -14,7 +17,13 @@
public string Text => Option.Text;
public string Glyph { get; init; } = "";
public Brush Background { get; init; } = null!;
/// <summary>The launcher's own logo (Steam's, Playnite's, the Xbox app's, the custom app's); until then, or without it, the glyph.</summary>
[ObservableProperty, NotifyPropertyChangedFor(nameof(HasLogo), nameof(ShowGlyph))] private ImageSource? _logo;

Check warning on line 21 in src/ConsoleMode/ViewModels/MainViewModel.LaunchTiles.cs

View workflow job for this annotation

GitHub Actions / Build and test

The field ConsoleMode.ViewModels.LaunchTile._logo using
public bool HasLogo => Logo is not null;
/// <summary>The app whose logo this tile is waiting for (exe path or Store app id).</summary>
public string? LogoKey { get; set; }
public bool ShowGlyph => Logo is null;
[ObservableProperty, NotifyPropertyChangedFor(nameof(Opacity))] private bool _isSelected;

Check warning on line 26 in src/ConsoleMode/ViewModels/MainViewModel.LaunchTiles.cs

View workflow job for this annotation

GitHub Actions / Build and test

The field ConsoleMode.ViewModels.LaunchTile._isSelected using
/// <summary>The other launchers fade back, so the one that opens stands out.</summary>
public double Opacity => IsSelected ? 1 : 0.6;
}
Expand Down Expand Up @@ -42,6 +51,67 @@
IsSelected = ReferenceEquals(option, SelectedLaunch)
});
}
foreach (var tile in LaunchTiles) _ = LoadLaunchLogoAsync(tile);
}

/// <summary>Asked in pixels: the tile draws it at 64, so this stays sharp on a 4K TV.</summary>
private const int LaunchLogoSize = 256;

// The logos are read once per app: the tiles are rebuilt on every language switch.
// A Store app's logo is a file of its package; a program's, the icon pixels of its exe.
private readonly Dictionary<string, (string? File, IconBitmap? Pixels)> _launchLogos = new(StringComparer.OrdinalIgnoreCase);

/// <summary>A launcher's path changed: its tile shows the new app's logo (or the glyph).</summary>
private void RefreshLaunchLogo(string mode)
{
foreach (var tile in LaunchTiles.Where(t => t.Option.Value == mode))
{
tile.Logo = null;
_ = LoadLaunchLogoAsync(tile);
}
}

private async Task LoadLaunchLogoAsync(LaunchTile tile)
{
var (exe, appId) = tile.Option.Value switch
{
"bigPicture" => (SteamSession.FindSteamExe(), (string?)null),
"playnite" => (Engine.Launch.GetPlaynitePath(), null),
"xboxMode" => (null, LaunchArt.XboxAppId),
CustomApp.Mode => (CustomApp.CleanPath(CustomAppPath), null),
_ => (null, null)
};
var key = appId ?? exe;
// The app this tile now waits for: a slower load for a previous path must not land after this one.
tile.LogoKey = key;
if (string.IsNullOrWhiteSpace(key)) return;
if (!_launchLogos.TryGetValue(key, out var logo))
{
logo = await Task.Run(() =>
{
var file = appId is null ? null : PackageLogos.Find(appId);
return (file, file is null ? WindowIcons.ForApp(exe, appId, LaunchLogoSize) : null);
});
_launchLogos[key] = logo;
}
if (!string.Equals(tile.LogoKey, key, StringComparison.OrdinalIgnoreCase)) return;
try
{
if (logo.File is not null)
{
tile.Logo = new BitmapImage(new Uri(logo.File)) { DecodePixelWidth = LaunchLogoSize };
}
else if (logo.Pixels is { } bitmap)
{
var image = new WriteableBitmap(bitmap.Width, bitmap.Height);
using (var stream = image.PixelBuffer.AsStream()) stream.Write(bitmap.Pixels);
tile.Logo = image;
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved
}
}
catch (Exception ex)
{
AppLog.Write($"Início: ícone de \"{key}\": {ex.Message}");
}
}

private void SyncLaunchTiles()
Expand Down
1 change: 1 addition & 0 deletions src/ConsoleMode/ViewModels/MainViewModel.Playnite.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ partial void OnPlaynitePathChanged(string value)
Engine.Launch.CustomPlaynitePath = value;
OnPropertyChanged(nameof(HasPlaynitePath));
OnPropertyChanged(nameof(PlaynitePathText));
RefreshLaunchLogo("playnite");
if (_applying) return;
// The launcher list only offers Playnite when it can be found.
IsPlayniteAvailable = Engine.Launch.IsPlayniteAvailable();
Expand Down
5 changes: 4 additions & 1 deletion src/ConsoleMode/Views/ConsoleHomeView.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,10 @@
Command="{Binding ViewModel.PlayLaunchTileCommand, ElementName=Page}" CommandParameter="{x:Bind}"
AutomationProperties.Name="{x:Bind Text}">
<Grid>
<FontIcon Glyph="{x:Bind Glyph}" FontSize="48" Margin="0,0,0,20"/>
<FontIcon Glyph="{x:Bind Glyph}" FontSize="48" Margin="0,0,0,20" Visibility="{x:Bind ShowGlyph, Mode=OneWay}"/>
<!-- The launcher's own logo, from the installed app -->
<Image Source="{x:Bind Logo, Mode=OneWay}" Width="64" Height="64" Margin="0,0,0,24" Stretch="Uniform"
Visibility="{x:Bind HasLogo, Mode=OneWay}"/>
<TextBlock Text="{x:Bind Text}" FontSize="15" FontWeight="SemiBold" VerticalAlignment="Bottom" HorizontalAlignment="Center"
TextTrimming="CharacterEllipsis" MaxLines="1" Foreground="#E6FFFFFF"/>
<!-- What opens: a check in the corner -->
Expand Down
1 change: 1 addition & 0 deletions tests/ConsoleMode.Tests/ConsoleMode.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
<Compile Include="../../src/ConsoleMode/Services/DiagnosticsReport.cs" Link="DiagnosticsReport.cs" />
<Compile Include="../../src/ConsoleMode/Services/DesktopIconLayout.cs" Link="DesktopIconLayout.cs" />
<Compile Include="../../src/ConsoleMode/Services/ControllerWake.cs" Link="ControllerWake.cs" />
<Compile Include="../../src/ConsoleMode/Services/PackageLogo.cs" Link="PackageLogo.cs" />
<Compile Include="../../src/ConsoleMode/Models/Models.cs" Link="Models.cs" />
<Compile Include="../../src/ConsoleMode/Services/Tv/AdbProtocol.cs" Link="Tv/AdbProtocol.cs" />
<Compile Include="../../src/ConsoleMode/Services/Tv/AdbShellOutput.cs" Link="Tv/AdbShellOutput.cs" />
Expand Down
44 changes: 44 additions & 0 deletions tests/ConsoleMode.Tests/PackageLogoTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using ConsoleMode.Services;

namespace ConsoleMode.Tests;

public class PackageLogoTests
{
// The Xbox app's assets folder, trimmed.
private static readonly string[] XboxFiles =
[
"Xbox_AppList.scale-200.png",
"Xbox_AppList.scale-200_contrast-black.png",
"Xbox_AppList.targetsize-16.png",
"Xbox_AppList.targetsize-48.png",
"Xbox_AppList.targetsize-256.png",
"Xbox_AppList.targetsize-256_altform-lightunplated.png",
"Xbox_AppList.targetsize-256_contrast-white.png",
"Xbox_MedTile.scale-200.png",
];

[Fact]
public void The_biggest_plain_logo_wins() =>
Assert.Equal("Xbox_AppList.targetsize-256.png", PackageLogo.Pick(@"assets\Xbox_AppList.png", XboxFiles));

[Fact]
public void The_unplated_form_beats_the_plated_one_at_the_same_size() =>
Assert.Equal("Logo.targetsize-256_altform-unplated.png",
PackageLogo.Pick("Logo.png", ["Logo.targetsize-256.png", "Logo.targetsize-256_altform-unplated.png", "Logo.targetsize-48_altform-unplated.png"]));

[Fact]
public void Contrast_themes_are_never_picked() =>
Assert.Null(PackageLogo.Pick("Logo.png", ["Logo.targetsize-256_contrast-black.png", "Logo.scale-400_contrast-white.png"]));

[Fact]
public void Scaled_logos_count_by_their_scale() =>
Assert.Equal("Logo.scale-400.png", PackageLogo.Pick("Logo.png", ["Logo.scale-100.png", "Logo.scale-400.png", "Logo.scale-200.png"]));

[Fact]
public void A_logo_without_variants_is_used_as_is() =>
Assert.Equal("StoreLogo.png", PackageLogo.Pick(@"Assets\StoreLogo.png", ["StoreLogo.png", "Other.png"]));

[Fact]
public void Other_logos_and_extensions_are_ignored() =>
Assert.Null(PackageLogo.Pick("Logo.png", ["Logo.targetsize-256.jpg", "Logo2.png", "Splash.png"]));
}
Loading