From 32453c122926f696d532db16a1d2acc3e3e7da89 Mon Sep 17 00:00:00 2001 From: Filipe Moreira Date: Wed, 21 Oct 2026 10:35:07 -0300 Subject: [PATCH 1/2] feat: put desktop icons back in place after a console session Changing the primary display and disconnecting screens can make Explorer reshuffle the desktop icons. Their positions are now read through the shell's folder view before the session and put back after the desk is restored, a few times in the background while Explorer settles. Skipped when the desktop arranges icons automatically. On by default, with a toggle in both settings screens. Closes #30 Co-Authored-By: Claude Opus 5.5 --- docs/GUIDE.de-DE.md | 2 + docs/GUIDE.es-ES.md | 2 + docs/GUIDE.fr-FR.md | 2 + docs/GUIDE.md | 2 + docs/GUIDE.pt-BR.md | 2 + docs/GUIDE.ru-RU.md | 2 + docs/TESTING.md | 11 + src/ConsoleMode/Models/Models.cs | 5 + src/ConsoleMode/Native/DesktopIcons.cs | 263 ++++++++++++++++++ src/ConsoleMode/Resources/Strings.de-DE.json | 2 + src/ConsoleMode/Resources/Strings.en-US.json | 2 + src/ConsoleMode/Resources/Strings.es-ES.json | 2 + src/ConsoleMode/Resources/Strings.fr-FR.json | 2 + src/ConsoleMode/Resources/Strings.pt-BR.json | 2 + src/ConsoleMode/Resources/Strings.ru-RU.json | 2 + src/ConsoleMode/Services/ConsoleEngine.cs | 27 ++ src/ConsoleMode/Services/DesktopIconLayout.cs | 32 +++ .../Services/LocalizationService.cs | 2 + .../ViewModels/MainViewModel.ConsoleUi.cs | 1 + .../ViewModels/MainViewModel.Updates.cs | 2 + src/ConsoleMode/ViewModels/MainViewModel.cs | 2 + src/ConsoleMode/Views/ConsoleHomeView.xaml | 6 + src/ConsoleMode/Views/SettingsView.xaml | 7 + .../ConsoleMode.Tests.csproj | 1 + .../DesktopIconLayoutTests.cs | 47 ++++ 25 files changed, 430 insertions(+) create mode 100644 src/ConsoleMode/Native/DesktopIcons.cs create mode 100644 src/ConsoleMode/Services/DesktopIconLayout.cs create mode 100644 tests/ConsoleMode.Tests/DesktopIconLayoutTests.cs diff --git a/docs/GUIDE.de-DE.md b/docs/GUIDE.de-DE.md index 3a55462..ef431c2 100644 --- a/docs/GUIDE.de-DE.md +++ b/docs/GUIDE.de-DE.md @@ -27,6 +27,8 @@ Die Registerkarte **System** bietet dieselben Einstellungen wie der Desktopmodus Bei der Rückkehr aus Big Picture schließt **Steam beim Zurückkehren zum PC in den Infobereich minimieren** das Client-Fenster, während Steam weiterläuft. Ist die Option aus, bleibt der Desktop-Client geöffnet. Steam-Fenster werden nicht angetastet, wenn ein Spiel läuft oder sich sein Zustand nicht prüfen lässt. +Ein Wechsel des Hauptbildschirms kann Windows dazu bringen, die Desktopsymbole neu anzuordnen. **Desktopsymbole wieder an ihren Platz setzen** (standardmäßig an) speichert vor der Sitzung, wo sie liegen, und setzt sie nach der Wiederherstellung wieder dorthin. Ist auf dem Desktop **Symbole automatisch anordnen** aktiv, passiert nichts, weil Windows sie dann selbst anordnet. + ## Lokale Steuerungs-API `consolemode://`-Links werden abgeschickt, ohne auf eine Antwort zu warten. Werkzeuge, die eine Antwort brauchen, etwa ein Fernsteuerungs-Agent, der als Windows-Dienst läuft, oder ein Stream-Deck-Plugin, das anzeigt, ob der Konsolenmodus aktiv ist, können die Named Pipe `\\.\pipe\ConsoleMode.Control` nutzen, solange die App läuft: Eine JSON-Zeile senden, eine zurückbekommen. diff --git a/docs/GUIDE.es-ES.md b/docs/GUIDE.es-ES.md index 43cced6..9a6fbac 100644 --- a/docs/GUIDE.es-ES.md +++ b/docs/GUIDE.es-ES.md @@ -27,6 +27,8 @@ Abre la acción del atajo que quieras configurar, elige **Definir** o **Cambiar* Al volver de Big Picture, **Enviar Steam a la bandeja al volver al PC** cierra la ventana del cliente y deja Steam en marcha. Con la opción desactivada, el cliente de escritorio se queda abierto. Las ventanas de Steam no se tocan si hay un juego en marcha o si no se puede comprobar su estado. +Cambiar la pantalla principal puede hacer que Windows reordene los iconos del escritorio. **Devolver los iconos del escritorio a su sitio** (activado por defecto) guarda su posición antes de la sesión y los vuelve a colocar después de restaurar el escritorio. No hace nada si **Organizar iconos automáticamente** está activado en el escritorio, porque entonces Windows los coloca por sí mismo. + ## API de control local Los enlaces `consolemode://` se lanzan sin esperar respuesta. Las herramientas que necesitan una respuesta (un agente de control remoto que funciona como servicio de Windows, un plugin de Stream Deck que muestra si el modo consola está activo) pueden usar la canalización con nombre (named pipe) `\\.\pipe\ConsoleMode.Control` mientras la aplicación está abierta: envía una línea JSON y recibe otra. diff --git a/docs/GUIDE.fr-FR.md b/docs/GUIDE.fr-FR.md index 5060ac1..9612288 100644 --- a/docs/GUIDE.fr-FR.md +++ b/docs/GUIDE.fr-FR.md @@ -27,6 +27,8 @@ Ouvrez l'action de raccourci à configurer, choisissez **Définir** ou **Modifie Au retour de Big Picture, **Réduire Steam dans la zone de notification au retour au PC** ferme la fenêtre du client tout en laissant Steam en marche. Si l'option est désactivée, le client de bureau reste ouvert. Les fenêtres de Steam ne sont pas touchées quand un jeu est en cours ou quand son état ne peut pas être vérifié. +Changer d'écran principal peut amener Windows à mélanger les icônes du bureau. **Remettre les icônes du bureau à leur place** (activé par défaut) enregistre leur position avant la session et les remet en place une fois le bureau restauré. Sans effet si **Réorganiser automatiquement les icônes** est activé sur le bureau, car Windows les place alors lui-même. + ## API de contrôle local Les liens `consolemode://` s'envoient sans attendre de réponse. Les outils qui ont besoin d'une réponse (un agent de contrôle à distance qui tourne comme service Windows, un plugin Stream Deck qui indique si le mode console est actif) peuvent utiliser le canal nommé `\\.\pipe\ConsoleMode.Control` tant que l'application tourne : envoyez une ligne JSON, recevez-en une en retour. diff --git a/docs/GUIDE.md b/docs/GUIDE.md index f493c78..4b8774a 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -33,6 +33,8 @@ Open the shortcut action you want to configure, choose **Set** or **Change**, ho When returning from Big Picture, **Send Steam to the tray when going back to the PC** closes the client window while keeping Steam running. With the option off, the desktop client is left open. Steam windows are left alone when a game is running or its state cannot be checked. +Changing the main display can make Windows reshuffle the desktop icons. **Put desktop icons back in place** (on by default) saves where they are before the session and puts them back after the desk is restored. It does nothing when the desktop's **Auto arrange icons** is on, since Windows lays them out itself then. + ## Local control API `consolemode://` links fire and forget. Tools that need an answer — a remote-control agent running as a Windows service, a Stream Deck plugin showing whether console mode is on — can use the named pipe `\\.\pipe\ConsoleMode.Control` while the app is running: send one JSON line, get one back. diff --git a/docs/GUIDE.pt-BR.md b/docs/GUIDE.pt-BR.md index 8a9ce9e..b25d457 100644 --- a/docs/GUIDE.pt-BR.md +++ b/docs/GUIDE.pt-BR.md @@ -33,6 +33,8 @@ Abra a ação de atalho que deseja configurar, escolha **Definir** ou **Alterar* Ao voltar do Big Picture, **Mandar a Steam para a bandeja ao voltar ao PC** fecha a janela do cliente e mantém a Steam em execução. Com a opção desligada, o cliente desktop fica aberto. As janelas da Steam são preservadas quando há jogo rodando ou não é possível verificar esse estado. +Trocar a tela principal pode fazer o Windows embaralhar os ícones da área de trabalho. **Devolver os ícones da área de trabalho ao lugar** (ligado por padrão) salva a posição deles antes da sessão e os coloca de volta depois que a mesa é restaurada. Não faz nada quando **Organizar ícones automaticamente** está ligado na área de trabalho, porque aí o próprio Windows os arruma. + ## API de controle local Os links `consolemode://` não dão resposta. Ferramentas que precisam de uma — um agente de controle remoto rodando como serviço do Windows, um plugin de Stream Deck que mostra se o modo console está ligado — podem usar o named pipe `\\.\pipe\ConsoleMode.Control` com o app aberto: envie uma linha JSON e receba outra. diff --git a/docs/GUIDE.ru-RU.md b/docs/GUIDE.ru-RU.md index 9457df8..38a6f16 100644 --- a/docs/GUIDE.ru-RU.md +++ b/docs/GUIDE.ru-RU.md @@ -27,6 +27,8 @@ При возврате из Big Picture параметр **«Сворачивать Steam в область уведомлений при возврате к ПК»** закрывает окно клиента, но Steam продолжает работать. Если параметр выключен, клиент на рабочем столе остаётся открытым. Окна Steam не трогаются, если запущена игра или её состояние не удаётся проверить. +При смене основного экрана Windows может перемешать значки рабочего стола. Параметр **«Возвращать значки рабочего стола на место»** (включён по умолчанию) запоминает их расположение перед сеансом и возвращает значки после восстановления рабочего места. Если на рабочем столе включено **«Упорядочить значки автоматически»**, параметр ничего не делает: Windows расставляет их сам. + ## Локальный API управления Ссылки `consolemode://` срабатывают без ответа. Инструменты, которым нужен ответ (агент удалённого управления, работающий как служба Windows, плагин Stream Deck, показывающий, включён ли режим консоли), могут использовать именованный канал `\\.\pipe\ConsoleMode.Control`, пока приложение запущено: отправьте одну строку JSON и получите одну в ответ. diff --git a/docs/TESTING.md b/docs/TESTING.md index 6129468..94bd52d 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -373,6 +373,17 @@ Pré-condições: pelo menos 3 telas (a TV desligada na mesa normal, mais duas t - [ ] TV que já estava ligada (como tela estendida) antes da sessão: depois de voltar, ela continua ligada no mesmo lugar. Resultado: ______ - [ ] Se uma das telas originais não voltar (cabo solto): o log diz que a tela de jogo ficou ligada e o PC não fica sem imagem. Resultado: ______ +## Ícones da área de trabalho (issue #30) + +Pré-condições: área de trabalho com **Organizar ícones automaticamente** desligado (clique direito → Exibir) e ícones espalhados em lugares fáceis de reconhecer (alguns no meio da tela, um no canto direito); de preferência a TV não sendo a tela principal na mesa normal. + +- [ ] Ajustes → **Devolver os ícones da área de trabalho ao lugar** ligado (padrão): **Jogar agora** e **Voltar ao PC**: os ícones voltam exatamente onde estavam, mesmo que o Windows os tenha embaralhado durante a sessão. O log mostra `Ícones da área de trabalho: N posições salvas` e depois `… M reposicionados`. Resultado: ______ +- [ ] O retorno ao PC não fica mais lento: os ícones voltam alguns segundos depois da mesa, sem travar a janela. Resultado: ______ +- [ ] Um atalho criado na área de trabalho durante a sessão fica onde o Windows o pôs; um apagado durante a sessão não causa erro. Resultado: ______ +- [ ] Com a opção desligada (Ajustes e aba Sistema do modo Console): o log não mostra nada sobre ícones e nada é movido. Resultado: ______ +- [ ] Com **Organizar ícones automaticamente** ligado: o log mostra `organização automática ligada; posições não salvas` e o Windows arruma os ícones sozinho. Resultado: ______ +- [ ] Explorer reiniciado durante a sessão (Gerenciador de Tarefas → Reiniciar): voltar ao PC não trava nem dá erro. Resultado: ______ + ## Telas com código próprio (issue #91) Pré-condições: 1.6 instalada por cima da 1.5, com a configuração da 1.5 (tela de jogo e telas a esconder escolhidas). Anote antes, na 1.5, como o mapa de telas aparece, para comparar. diff --git a/src/ConsoleMode/Models/Models.cs b/src/ConsoleMode/Models/Models.cs index 9a40c75..0a93825 100644 --- a/src/ConsoleMode/Models/Models.cs +++ b/src/ConsoleMode/Models/Models.cs @@ -78,6 +78,9 @@ public sealed class AppConfig /// public bool CloseSteamOnRestore { get; set; } = true; + /// Put the desktop icons back where they were after the session (issue #30). + public bool RestoreDesktopIcons { get; set; } = true; + /// Enter console mode when a controller connects while the app is in the tray. public bool AutoStartOnController { get; set; } @@ -363,6 +366,8 @@ public sealed class ConsoleRuntimeState public bool HdrTurnedOffByUser { get; set; } public DateTime? SessionStartedAt { get; set; } public string? BackupAudioId { get; set; } + /// The desktop icons read before the session; null when they aren't restored. + public List? DesktopIcons { get; set; } } public sealed class RtssBackup diff --git a/src/ConsoleMode/Native/DesktopIcons.cs b/src/ConsoleMode/Native/DesktopIcons.cs new file mode 100644 index 0000000..fbecfe6 --- /dev/null +++ b/src/ConsoleMode/Native/DesktopIcons.cs @@ -0,0 +1,263 @@ +using System.Runtime.InteropServices; +using ConsoleMode.Services; + +namespace ConsoleMode.Native; + +/// +/// Reads and moves the desktop icons through the shell's own view of the desktop +/// (IShellWindows → the desktop's IShellBrowser → IFolderView), the documented route instead of +/// poking at Explorer's list view from another process (issue #30). +/// Each call runs on its own STA thread: the shell objects live in Explorer and want one. +/// +internal static class DesktopIcons +{ + /// Every icon and its position, or null when they can't be read or Windows arranges them itself. + public static List? Read() => OnSta(() => + { + using var desktop = DesktopView.Open(); + if (desktop is null) return null; + if (desktop.View.GetAutoArrange() == 0) + { + AppLog.Write("Ícones da área de trabalho: organização automática ligada; posições não salvas"); + return null; + } + var icons = new List(); + foreach (var (name, pidl) in desktop.Items()) + { + if (desktop.View.GetItemPosition(pidl, out var point) == 0) + icons.Add(new DesktopIcon(name, point.X, point.Y)); + } + return icons; + }, null); + + /// Puts the given icons where they were. Returns how many moved, or -1 on failure. + public static int Move(IReadOnlyList icons) => OnSta(() => + { + if (icons.Count == 0) return 0; + using var desktop = DesktopView.Open(); + if (desktop is null || desktop.View.GetAutoArrange() == 0) return -1; + var wanted = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var icon in icons) wanted[icon.Name] = icon; + + var moved = 0; + foreach (var (name, pidl) in desktop.Items()) + { + if (!wanted.TryGetValue(name, out var icon)) continue; + var hr = desktop.View.SelectAndPositionItems(1, [pidl], [new Point { X = icon.X, Y = icon.Y }], SvsiPositionItem); + if (hr == 0) moved++; + } + return moved; + }, -1); + + private static T OnSta(Func work, T fallback) + { + var result = fallback; + var thread = new Thread(() => + { + try { result = work(); } + catch (Exception ex) { AppLog.Write($"Ícones da área de trabalho: {ex.Message}"); } + }) { IsBackground = true, Name = "DesktopIcons" }; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + if (thread.Join(TimeSpan.FromSeconds(10))) return result; + AppLog.Write("Ícones da área de trabalho: o Explorer não respondeu"); + return fallback; + } + + /// The desktop's folder view and folder; frees every shell object and item id it hands out. + private sealed class DesktopView : IDisposable + { + public IFolderView View { get; } + private readonly IShellFolder _folder; + private readonly List _comObjects; + private readonly List _pidls = []; + + private DesktopView(IFolderView view, IShellFolder folder, List comObjects) + { + View = view; + _folder = folder; + _comObjects = comObjects; + } + + public static DesktopView? Open() + { + var objects = new List(); + try + { + var type = Type.GetTypeFromCLSID(ClsidShellWindows, throwOnError: true)!; + var windows = (IShellWindows)Activator.CreateInstance(type)!; + objects.Add(windows); + + object location = CsidlDesktop; + object root = null!; + if (windows.FindWindowSW(ref location, ref root, SwcDesktop, out _, SwfoNeedDispatch, out var dispatch) != 0 || dispatch is null) + { + AppLog.Write("Ícones da área de trabalho: a área de trabalho do Explorer não foi encontrada"); + Release(objects); + return null; + } + objects.Add(dispatch); + + var service = SidTopLevelBrowser; + var browserId = typeof(IShellBrowser).GUID; + Marshal.ThrowExceptionForHR(((IComServiceProvider)dispatch).QueryService(ref service, ref browserId, out var browserObject)); + objects.Add(browserObject); + Marshal.ThrowExceptionForHR(((IShellBrowser)browserObject).QueryActiveShellView(out var viewObject)); + objects.Add(viewObject); + var view = (IFolderView)viewObject; + + var folderId = typeof(IShellFolder).GUID; + Marshal.ThrowExceptionForHR(view.GetFolder(ref folderId, out var folderObject)); + objects.Add(folderObject); + return new DesktopView(view, (IShellFolder)folderObject, objects); + } + catch + { + Release(objects); + throw; + } + } + + /// Each icon's parsing name with its item id (valid until Dispose). + public IEnumerable<(string Name, nint Pidl)> Items() + { + if (View.ItemCount(SvgioAllView, out var count) != 0) yield break; + for (var i = 0; i < count; i++) + { + if (View.Item(i, out var pidl) != 0 || pidl == 0) continue; + _pidls.Add(pidl); + var name = ParsingName(pidl); + if (!string.IsNullOrWhiteSpace(name)) yield return (name, pidl); + } + } + + private string? ParsingName(nint pidl) + { + var strret = Marshal.AllocCoTaskMem(StrretSize); + try + { + if (_folder.GetDisplayNameOf(pidl, ShgdnForParsing, strret) != 0) return null; + if (StrRetToStrW(strret, pidl, out var text) != 0 || text == 0) return null; + try { return Marshal.PtrToStringUni(text); } + finally { Marshal.FreeCoTaskMem(text); } + } + finally { Marshal.FreeCoTaskMem(strret); } + } + + public void Dispose() + { + foreach (var pidl in _pidls) Marshal.FreeCoTaskMem(pidl); + _pidls.Clear(); + Release(_comObjects); + } + + private static void Release(List objects) + { + for (var i = objects.Count - 1; i >= 0; i--) + { + try { if (Marshal.IsComObject(objects[i])) Marshal.ReleaseComObject(objects[i]); } + catch { /* already gone */ } + } + objects.Clear(); + } + } + + private static readonly Guid ClsidShellWindows = new("9BA05972-F6A8-11CF-A442-00A0C90A8F39"); + private static readonly Guid SidTopLevelBrowser = new("4C96BE40-915C-11CF-99D3-00AA004AE837"); + private const int CsidlDesktop = 0; + private const int SwcDesktop = 8; + private const int SwfoNeedDispatch = 1; + private const uint SvgioAllView = 2; + private const uint SvsiPositionItem = 0x80; + private const uint ShgdnForParsing = 0x8000; + // STRRET: a UINT and a union whose biggest member is WCHAR[MAX_PATH]; padded for 64-bit. + private const int StrretSize = 8 + 260 * 2; + + [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)] + private static extern int StrRetToStrW(nint pstr, nint pidl, out nint ppsz); + + [StructLayout(LayoutKind.Sequential)] + private struct Point + { + public int X; + public int Y; + } + + // Only the slots up to the method that is called need to be right; the earlier ones are placeholders. + [ComImport, Guid("85CB6900-4D95-11CF-960C-0080C7F4EE85"), InterfaceType(ComInterfaceType.InterfaceIsDual)] + private interface IShellWindows + { + void _Count(); + void _Item(); + void _NewEnum(); + void _Register(); + void _RegisterPending(); + void _Revoke(); + void _OnNavigate(); + void _OnActivated(); + [PreserveSig] + int FindWindowSW(ref object pvarLoc, ref object pvarLocRoot, int swClass, out int phwnd, int swfwOptions, + [MarshalAs(UnmanagedType.IDispatch)] out object? ppdispOut); + } + + [ComImport, Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IComServiceProvider + { + [PreserveSig] + int QueryService(ref Guid guidService, ref Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppvObject); + } + + [ComImport, Guid("000214E2-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellBrowser + { + void _GetWindow(); + void _ContextSensitiveHelp(); + void _InsertMenusSB(); + void _SetMenuSB(); + void _RemoveMenusSB(); + void _SetStatusTextSB(); + void _EnableModelessSB(); + void _TranslateAcceleratorSB(); + void _BrowseObject(); + void _GetViewStateStream(); + void _GetControlWindow(); + void _SendControlMsg(); + [PreserveSig] + int QueryActiveShellView([MarshalAs(UnmanagedType.IUnknown)] out object ppshv); + } + + [ComImport, Guid("CDE725B0-CCC9-4519-917E-325D72FAB4CE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IFolderView + { + void _GetCurrentViewMode(); + void _SetCurrentViewMode(); + [PreserveSig] int GetFolder(ref Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppv); + [PreserveSig] int Item(int iItemIndex, out nint ppidl); + [PreserveSig] int ItemCount(uint uFlags, out int pcItems); + void _Items(); + void _GetSelectionMarkedItem(); + void _GetFocusedItem(); + [PreserveSig] int GetItemPosition(nint pidl, out Point ppt); + void _GetSpacing(); + void _GetDefaultSpacing(); + /// S_OK (0) when the icons are arranged automatically. + [PreserveSig] int GetAutoArrange(); + void _SelectItem(); + [PreserveSig] int SelectAndPositionItems(uint cidl, [MarshalAs(UnmanagedType.LPArray)] nint[] apidl, + [MarshalAs(UnmanagedType.LPArray)] Point[] apt, uint dwFlags); + } + + [ComImport, Guid("000214E6-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellFolder + { + void _ParseDisplayName(); + void _EnumObjects(); + void _BindToObject(); + void _BindToStorage(); + void _CompareIDs(); + void _CreateViewObject(); + void _GetAttributesOf(); + void _GetUIObjectOf(); + [PreserveSig] int GetDisplayNameOf(nint pidl, uint uFlags, nint pName); + } +} diff --git a/src/ConsoleMode/Resources/Strings.de-DE.json b/src/ConsoleMode/Resources/Strings.de-DE.json index 435d76b..3d67f7a 100644 --- a/src/ConsoleMode/Resources/Strings.de-DE.json +++ b/src/ConsoleMode/Resources/Strings.de-DE.json @@ -133,6 +133,8 @@ "ShortcutsOnboardingDone": "Fertig", "CloseSteamCard": "Steam beim Zurückkehren zum PC in den Infobereich minimieren", "CloseSteamDescription": "Wenn du Big Picture verlässt, erhält Steam eine normale Aufforderung zum Schließen des Fensters und kann so in den Infobereich wechseln, ohne den Prozess zu beenden. Wenn ein Spiel läuft oder sein Status nicht ermittelt werden kann, bleibt das Fenster unverändert.", + "RestoreIconsCard": "Desktopsymbole wieder an ihren Platz setzen", + "RestoreIconsDescription": "Speichert vor der Sitzung, wo die Desktopsymbole liegen, und setzt sie bei der Rückkehr zum PC wieder dorthin, falls Windows sie beim Wechsel des Hauptbildschirms durcheinanderbringt. Bei aktivierter automatischer Anordnung passiert nichts.", "HideCursorCard": "Mauszeiger ausblenden", "HideCursorDescription": "Bleibt ausgeblendet, bis du diese Option deaktivierst oder zum PC zurückkehrst. Praktisch für Emulatoren und Spiele, bei denen der Zeiger mitten auf dem Bildschirm stehen bleibt.", "ControllerMouseRow": "Maus mit dem Controller steuern", diff --git a/src/ConsoleMode/Resources/Strings.en-US.json b/src/ConsoleMode/Resources/Strings.en-US.json index 5945df9..e786646 100644 --- a/src/ConsoleMode/Resources/Strings.en-US.json +++ b/src/ConsoleMode/Resources/Strings.en-US.json @@ -133,6 +133,8 @@ "ShortcutsOnboardingDone": "Done", "CloseSteamCard": "Send Steam to the tray when going back to the PC", "CloseSteamDescription": "When you leave Big Picture, Steam receives a normal window-close request so it can move to the tray without exiting the process. If a game is running or its state cannot be checked, the window is left unchanged.", + "RestoreIconsCard": "Put desktop icons back in place", + "RestoreIconsDescription": "Saves where the desktop icons are before the session and puts them back when you return to the PC, in case Windows reshuffles them while the main display changes. Does nothing when auto arrange is on.", "HideCursorCard": "Hide the mouse pointer", "HideCursorDescription": "Stays hidden until you turn this off or go back to the PC. Handy for emulators and games that leave it in the middle of the screen.", "ControllerMouseRow": "Control the mouse with the controller", diff --git a/src/ConsoleMode/Resources/Strings.es-ES.json b/src/ConsoleMode/Resources/Strings.es-ES.json index 6b5da4c..c77c569 100644 --- a/src/ConsoleMode/Resources/Strings.es-ES.json +++ b/src/ConsoleMode/Resources/Strings.es-ES.json @@ -133,6 +133,8 @@ "ShortcutsOnboardingDone": "Listo", "CloseSteamCard": "Enviar Steam a la bandeja al volver al PC", "CloseSteamDescription": "Al salir de Big Picture, Steam recibe una solicitud normal para cerrar la ventana y pasar a la bandeja sin finalizar el proceso. Si hay un juego en ejecución o no se puede comprobar su estado, la ventana no se modifica.", + "RestoreIconsCard": "Devolver los iconos del escritorio a su sitio", + "RestoreIconsDescription": "Guarda la posición de los iconos del escritorio antes de la sesión y los vuelve a colocar al volver al PC, por si Windows los reordena al cambiar la pantalla principal. No hace nada si la organización automática está activada.", "HideCursorCard": "Ocultar el cursor del ratón", "HideCursorDescription": "Queda oculto hasta que lo desactives aquí o vuelvas al PC. Útil en emuladores y juegos que lo dejan en el centro de la pantalla.", "ControllerMouseRow": "Controlar el ratón con el mando", diff --git a/src/ConsoleMode/Resources/Strings.fr-FR.json b/src/ConsoleMode/Resources/Strings.fr-FR.json index 88328f2..6f40641 100644 --- a/src/ConsoleMode/Resources/Strings.fr-FR.json +++ b/src/ConsoleMode/Resources/Strings.fr-FR.json @@ -133,6 +133,8 @@ "ShortcutsOnboardingDone": "Terminé", "CloseSteamCard": "Réduire Steam dans la zone de notification au retour au PC", "CloseSteamDescription": "Quand vous quittez Big Picture, Steam reçoit une demande normale de fermeture de fenêtre pour qu'il passe dans la zone de notification sans quitter le processus. Si un jeu est en cours ou si son état ne peut pas être vérifié, la fenêtre n'est pas modifiée.", + "RestoreIconsCard": "Remettre les icônes du bureau à leur place", + "RestoreIconsDescription": "Enregistre la position des icônes du bureau avant la session et les remet en place au retour au PC, au cas où Windows les mélange en changeant d'écran principal. Sans effet si la réorganisation automatique est activée.", "HideCursorCard": "Masquer le pointeur de la souris", "HideCursorDescription": "Reste masqué jusqu'à ce que vous désactiviez cette option ou reveniez au PC. Pratique pour les émulateurs et les jeux qui le laissent au milieu de l'écran.", "ControllerMouseRow": "Contrôler la souris avec la manette", diff --git a/src/ConsoleMode/Resources/Strings.pt-BR.json b/src/ConsoleMode/Resources/Strings.pt-BR.json index dd0986b..0d622ea 100644 --- a/src/ConsoleMode/Resources/Strings.pt-BR.json +++ b/src/ConsoleMode/Resources/Strings.pt-BR.json @@ -133,6 +133,8 @@ "ShortcutsOnboardingDone": "Concluir", "CloseSteamCard": "Mandar a Steam para a bandeja ao voltar ao PC", "CloseSteamDescription": "Ao sair do Big Picture, envia o fechamento normal da janela da Steam para ela ir à bandeja, sem encerrar o processo. Se houver um jogo em execução ou não for possível verificar, a janela não é alterada.", + "RestoreIconsCard": "Devolver os ícones da área de trabalho ao lugar", + "RestoreIconsDescription": "Salva a posição dos ícones antes da sessão e os coloca de volta ao voltar ao PC, caso o Windows os embaralhe ao trocar a tela principal. Não faz nada quando a organização automática dos ícones está ligada.", "HideCursorCard": "Ocultar o cursor do mouse", "HideCursorDescription": "Fica oculto até você desligar aqui ou voltar ao PC. Útil em emuladores e jogos que deixam o cursor no meio da tela.", "ControllerMouseRow": "Controlar o mouse com o controle", diff --git a/src/ConsoleMode/Resources/Strings.ru-RU.json b/src/ConsoleMode/Resources/Strings.ru-RU.json index 93468b9..05fe910 100644 --- a/src/ConsoleMode/Resources/Strings.ru-RU.json +++ b/src/ConsoleMode/Resources/Strings.ru-RU.json @@ -133,6 +133,8 @@ "ShortcutsOnboardingDone": "Готово", "CloseSteamCard": "Сворачивать Steam в область уведомлений при возврате к ПК", "CloseSteamDescription": "Когда вы выходите из Big Picture, Steam получает обычный запрос на закрытие окна и может свернуться в область уведомлений, не завершая процесс. Если запущена игра или её состояние не удаётся проверить, окно не трогается.", + "RestoreIconsCard": "Возвращать значки рабочего стола на место", + "RestoreIconsDescription": "Запоминает расположение значков рабочего стола перед сеансом и возвращает их при возврате к ПК, если Windows перемешает их при смене основного экрана. Ничего не делает, если включено автоматическое упорядочивание.", "HideCursorCard": "Скрыть указатель мыши", "HideCursorDescription": "Остаётся скрытым, пока вы не выключите этот параметр или не вернётесь к ПК. Удобно для эмуляторов и игр, которые оставляют его посреди экрана.", "ControllerMouseRow": "Управлять мышью с геймпада", diff --git a/src/ConsoleMode/Services/ConsoleEngine.cs b/src/ConsoleMode/Services/ConsoleEngine.cs index 7a1a0f6..8da6ab5 100644 --- a/src/ConsoleMode/Services/ConsoleEngine.cs +++ b/src/ConsoleMode/Services/ConsoleEngine.cs @@ -73,6 +73,10 @@ public void Start(AppConfig config, MonitorInfo? focusInfo, Func 0 } icons) RestoreDesktopIconsLater(icons); Rtss.Restore(State); Rtss.SetOverlay("", hideOthers: false); Monitors.ClearCache(); @@ -373,10 +378,32 @@ public void Stop() State.HdrApplied = false; State.HdrMonitor = null; State.VrrApplied = false; + State.DesktopIcons = null; OnUi(NativeWindows.StopBigPictureExitWatch); } } + /// + /// Explorer rearranges the icons a moment after the screens come back, sometimes more than once, + /// so they are put back in the background a few times instead of holding up the restore. + /// + private static void RestoreDesktopIconsLater(List saved) => Task.Run(async () => + { + var total = 0; + foreach (var delay in new[] { 1500, 2500, 4000 }) + { + await Task.Delay(delay); + var current = DesktopIcons.Read(); + if (current is null) break; + var moves = DesktopIconLayout.Moves(saved, current); + if (moves.Count == 0) continue; + var moved = DesktopIcons.Move(moves); + if (moved < 0) break; + total += moved; + } + AppLog.Write($"Ícones da área de trabalho: {total} reposicionados"); + }); + /// /// Going back to the PC closes Big Picture and Steam's client window to the tray; the process remains running. /// diff --git a/src/ConsoleMode/Services/DesktopIconLayout.cs b/src/ConsoleMode/Services/DesktopIconLayout.cs new file mode 100644 index 0000000..660e64e --- /dev/null +++ b/src/ConsoleMode/Services/DesktopIconLayout.cs @@ -0,0 +1,32 @@ +namespace ConsoleMode.Services; + +/// One desktop icon: the shell's parsing name (a path or a ::{CLSID}) and where it sits. +public readonly record struct DesktopIcon(string Name, int X, int Y); + +/// +/// Windows can reshuffle the desktop icons when the primary display changes or a screen is +/// disconnected (issue #30). The positions are read before the session and put back after it. +/// +public static class DesktopIconLayout +{ + /// + /// The saved icons that are still on the desktop but somewhere else. Icons that were added or + /// removed during the session are left alone. + /// + public static List Moves(IReadOnlyList saved, IReadOnlyList current) + { + var now = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var icon in current) + if (!string.IsNullOrWhiteSpace(icon.Name)) now[icon.Name] = icon; + + var moves = new List(); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var icon in saved) + { + if (string.IsNullOrWhiteSpace(icon.Name) || !seen.Add(icon.Name)) continue; + if (now.TryGetValue(icon.Name, out var there) && (there.X != icon.X || there.Y != icon.Y)) + moves.Add(icon); + } + return moves; + } +} diff --git a/src/ConsoleMode/Services/LocalizationService.cs b/src/ConsoleMode/Services/LocalizationService.cs index 67cb87e..8a45ec8 100644 --- a/src/ConsoleMode/Services/LocalizationService.cs +++ b/src/ConsoleMode/Services/LocalizationService.cs @@ -257,6 +257,8 @@ internal void NotifyAll() public string HomeButtonShortPressCard => LocalizationService.Get(nameof(HomeButtonShortPressCard)); public string CloseSteamCard => LocalizationService.Get(nameof(CloseSteamCard)); public string CloseSteamDescription => LocalizationService.Get(nameof(CloseSteamDescription)); + public string RestoreIconsCard => LocalizationService.Get(nameof(RestoreIconsCard)); + public string RestoreIconsDescription => LocalizationService.Get(nameof(RestoreIconsDescription)); public string HideCursorCard => LocalizationService.Get(nameof(HideCursorCard)); public string HideCursorDescription => LocalizationService.Get(nameof(HideCursorDescription)); public string ControllerMouseRow => LocalizationService.Get(nameof(ControllerMouseRow)); diff --git a/src/ConsoleMode/ViewModels/MainViewModel.ConsoleUi.cs b/src/ConsoleMode/ViewModels/MainViewModel.ConsoleUi.cs index 4037589..27c074e 100644 --- a/src/ConsoleMode/ViewModels/MainViewModel.ConsoleUi.cs +++ b/src/ConsoleMode/ViewModels/MainViewModel.ConsoleUi.cs @@ -264,6 +264,7 @@ private void CycleSetting(string spec) case "updates": CheckUpdates = !CheckUpdates; break; case "betas": BetaUpdates = !BetaUpdates; break; case "closest": CloseSteamOnRestore = !CloseSteamOnRestore; break; + case "desktopicons": RestoreDesktopIcons = !RestoreDesktopIcons; break; case "tvpower": TvTurnOffOnRestore = !TvTurnOffOnRestore; break; } } diff --git a/src/ConsoleMode/ViewModels/MainViewModel.Updates.cs b/src/ConsoleMode/ViewModels/MainViewModel.Updates.cs index 22601cd..3553bbf 100644 --- a/src/ConsoleMode/ViewModels/MainViewModel.Updates.cs +++ b/src/ConsoleMode/ViewModels/MainViewModel.Updates.cs @@ -21,6 +21,7 @@ private enum UpdateStatusKind { InstallKind, Searching, Latest, Available, Faile [ObservableProperty] private bool _autoStartOnController; [ObservableProperty] private bool _interfaceSounds = true; [ObservableProperty] private bool _closeSteamOnRestore = true; + [ObservableProperty] private bool _restoreDesktopIcons = true; [ObservableProperty] private string _homeButtonHint = ""; [ObservableProperty] private bool _startWithWindows; [ObservableProperty] private bool _minimizeToTray; @@ -101,6 +102,7 @@ partial void OnInterfaceSoundsChanged(bool value) if (value && !_applying) UiSounds.Play(UiSound.Confirm); } partial void OnCloseSteamOnRestoreChanged(bool value) => SaveQuietly(); + partial void OnRestoreDesktopIconsChanged(bool value) => SaveQuietly(); partial void OnHomeButtonShortPressChanged(bool value) { diff --git a/src/ConsoleMode/ViewModels/MainViewModel.cs b/src/ConsoleMode/ViewModels/MainViewModel.cs index ff48274..608b69f 100644 --- a/src/ConsoleMode/ViewModels/MainViewModel.cs +++ b/src/ConsoleMode/ViewModels/MainViewModel.cs @@ -325,6 +325,7 @@ private void Apply(LoadResult data) ConsoleBackgroundMode = ConsoleBackgroundService.NormalizeMode(config.ConsoleBackground); ConsoleBackgroundImage = config.ConsoleBackgroundImage ?? ""; CloseSteamOnRestore = config.CloseSteamOnRestore; + RestoreDesktopIcons = config.RestoreDesktopIcons; RefreshHomeButtonHint(); SelectedUiMode = UiModeOptions.FirstOrDefault(o => o.Value == config.UiMode) ?? UiModeOptions.FirstOrDefault(); SelectedControllerLayout = ControllerLayoutOptions.FirstOrDefault(o => o.Value == config.ControllerLayout) ?? ControllerLayoutOptions[0]; @@ -950,6 +951,7 @@ private AppConfig BuildConfig() ConsoleBackground = ConsoleBackgroundMode, ConsoleBackgroundImage = ConsoleBackgroundImage, CloseSteamOnRestore = CloseSteamOnRestore, + RestoreDesktopIcons = RestoreDesktopIcons, UiMode = SelectedUiMode?.Value ?? _loadedConfig.UiMode, ControllerLayout = SelectedControllerLayout?.Value ?? _loadedConfig.ControllerLayout, SkippedUpdateVersion = _loadedConfig.SkippedUpdateVersion, diff --git a/src/ConsoleMode/Views/ConsoleHomeView.xaml b/src/ConsoleMode/Views/ConsoleHomeView.xaml index 12c494b..a1fe11c 100644 --- a/src/ConsoleMode/Views/ConsoleHomeView.xaml +++ b/src/ConsoleMode/Views/ConsoleHomeView.xaml @@ -643,6 +643,12 @@ +