diff --git a/docs/DESKTOP-UX.md b/docs/DESKTOP-UX.md
index c651122d..a92bddb2 100644
--- a/docs/DESKTOP-UX.md
+++ b/docs/DESKTOP-UX.md
@@ -6,6 +6,37 @@
Светлая тема использует чёрные основные кнопки на белом, чёрная — белые на чёрном. Серый отделяет области и второстепенный текст. Активное состояние, предупреждение и ошибка обозначаются текстом и значком. Для списков используются строки и разделители; отдельная поверхность выделяет задачу, например подключение или добавление сервера. Короткие переходы между страницами и при раскрытии секций отключаются настройкой «Уменьшить движение».
+## Масштаб интерфейса (#477)
+
+«Настройки → Внешний вид → Масштаб интерфейса» задаёт значение от 80% до 150% с шагом 10%; по умолчанию 100%. Кнопка «Сбросить до 100%» возвращает значение по умолчанию. Выбор сохраняется в `settings.json` и применяется при следующем запуске.
+
+Масштаб применяется один раз — преобразованием раскладки (`LayoutTransformControl`) в корне оболочки. Поэтому текст, кнопки, поля, отступы и значки увеличиваются вместе, а не по отдельности, и остаются векторными: приложение не растягивает готовую картинку, поэтому размытия и двойного масштабирования нет. Системный DPI (Windows «Масштаб», `GDK_SCALE`, Retina) применяется поверх этого значения средствами Avalonia, поэтому 100% означает «как задано системой».
+
+Переключение между боковой и нижней навигацией по-прежнему происходит на 760 логических единицах, но считается по ширине до применения масштаба: при 150% окно шириной 1140 единиц даёт ровно 760 и боковую панель, а 1139 — уже нижнюю. Порог не «уезжает» вместе с настройкой.
+
+### Что проверено автоматически
+
+- Сохранение и чтение значения (`SettingsStore`), восстановление после перезапуска.
+- Ограничение диапазона и выравнивание по шагу для значения из файла настроек, из резервной копии и из интерфейса.
+- Проверка диапазона при импорте резервной копии (`BackupArchive.Validate`) и перенос значения при восстановлении.
+- Расчёт порога навигации по эффективной ширине без масштаба (`LayoutMetrics`).
+- Наличие строк `settings.scale*` в `en.json` и `ru.json`.
+- Разметка: преобразование стоит в корне оболочки и обёртывает всю страницу, а не отдельные элементы.
+
+### Что нужно проверить вручную
+
+Автоматические тесты не запускают окно с реальным DPI, поэтому перед релизом проверьте на каждой платформе:
+
+1. Системный масштаб Windows 100%, 125%, 150% и 200% (параметр «Масштаб» в «Параметры → Дисплей»). На каждом значении: 100% и 150% в настройках приложения, светлая и чёрная темы, русский и английский языки.
+2. Перенос окна между мониторами с разным масштабом (например, 100% и 150%) без перезапуска: расположение элементов не должно «прыгать», текст не должен становиться размытым, окно не должно выходить за пределы экрана.
+3. Минимальный размер окна (380×560) и обычный (1180×780) при масштабе 150%: основные действия (подключение, добавление сервера, сохранение настроек) видны и доступны, ничего не обрезано и не наложено.
+4. Прокрутка и переносы при масштабе 150%: главная, подключения и импорт, инструменты, маршрутизация, настройки, резервные копии, диалоги мастера и редактора цепочек, длинные русские строки.
+5. Клавиатура: Tab и Shift+Tab обходят все поля и кнопки, фокус виден, переключатель масштаба и кнопка сброса доступны без мыши.
+6. Темы галереи: пользовательская тема не должна ломать читаемость при увеличенном масштабе.
+7. Linux (X11 и Wayland) и macOS: те же значения масштаба, а также системное масштабирование (`GDK_SCALE`, Retina). На Wayland размеры окна задаёт композитор — проверьте, что нижняя навигация включается вовремя.
+
+Все проверки интерфейса выполняются только с `--mock` и `BYDLO_SAFE_DEV=1`; реальные движки и настройки сети не используются.
+
Для проверки компоновки и сценариев используйте Mock Mode. Скриншоты рендерятся из реальных представлений Avalonia без запуска VPN или вспомогательных сетевых инструментов:
```powershell
diff --git a/docs/INTERFACE.md b/docs/INTERFACE.md
index 6b6606a2..a3e98d28 100644
--- a/docs/INTERFACE.md
+++ b/docs/INTERFACE.md
@@ -25,6 +25,11 @@
В верхней части настроек есть переходы к оформлению, подключению, резервной
копии, маршрутизации и статистике. «Уменьшить движение интерфейса» в оформлении
отключает переходы между страницами и анимацию раскрытия разделов.
+«Масштаб интерфейса» там же увеличивает текст, кнопки, поля, отступы и значки
+одновременно (80–150%, по умолчанию 100%); кнопка «Сбросить до 100%» возвращает
+значение по умолчанию, выбор сохраняется после перезапуска. Системный DPI
+применяется поверх этого значения. Подробности и список ручных проверок —
+[DESKTOP-UX.md](DESKTOP-UX.md).
Порты, системный прокси, доступ из локальной сети,
тестовый режим и диагностика находятся в «Расширенных настройках».
Там же на Windows можно включить «Запускать с правами администратора». BYDLO запросит подтверждение UAC при запуске.
diff --git a/src/Bydlo.App/Assets/Strings/en.json b/src/Bydlo.App/Assets/Strings/en.json
index 17e9f8dc..eb131d24 100644
--- a/src/Bydlo.App/Assets/Strings/en.json
+++ b/src/Bydlo.App/Assets/Strings/en.json
@@ -576,6 +576,10 @@
"settings.appearance": "Appearance",
"settings.theme": "Theme",
+ "settings.scale": "Interface scale",
+ "settings.scale.hint": "Scales text, buttons, fields, paddings and icons together. 100% matches the system DPI; the system scale is applied on top of this value.",
+ "settings.scale.reset": "Reset to 100%",
+ "settings.scale.reset.done": "Interface scale reset to 100%.",
"settings.language": "Language",
"theme.light": "Light",
"theme.oled": "Black",
diff --git a/src/Bydlo.App/Assets/Strings/ru.json b/src/Bydlo.App/Assets/Strings/ru.json
index 89460462..f66e30ca 100644
--- a/src/Bydlo.App/Assets/Strings/ru.json
+++ b/src/Bydlo.App/Assets/Strings/ru.json
@@ -576,6 +576,10 @@
"settings.appearance": "Внешний вид",
"settings.theme": "Тема",
+ "settings.scale": "Масштаб интерфейса",
+ "settings.scale.hint": "Увеличивает текст, кнопки, поля, отступы и значки одновременно. 100% соответствует системному DPI; системный масштаб применяется поверх этого значения.",
+ "settings.scale.reset": "Сбросить до 100%",
+ "settings.scale.reset.done": "Масштаб интерфейса сброшен до 100%.",
"settings.language": "Язык",
"theme.light": "Светлая",
"theme.oled": "Чёрная",
diff --git a/src/Bydlo.App/Services/LayoutMetrics.cs b/src/Bydlo.App/Services/LayoutMetrics.cs
new file mode 100644
index 00000000..1b9ddb52
--- /dev/null
+++ b/src/Bydlo.App/Services/LayoutMetrics.cs
@@ -0,0 +1,23 @@
+namespace Bydlo.App.Services;
+
+///
+/// Layout math for the interface scale (issue #477). The scale is applied once by a
+/// LayoutTransformControl at the root of the shell, so every control keeps working in
+/// unscaled layout units; only the width available to the shell shrinks as the scale grows.
+///
+public static class LayoutMetrics
+{
+ /// Below this unscaled width the sidebar collapses into bottom navigation (phones, narrow windows).
+ public const double CompactWidth = 760;
+
+ ///
+ /// Unscaled layout width of a shell that occupies at
+ /// . The navigation switch compares this value, so the breakpoint
+ /// stays at the same physical size for every interface scale.
+ ///
+ public static double EffectiveWidth(double scaledWidth, double scale) =>
+ scale > 0 && double.IsFinite(scale) ? scaledWidth / scale : scaledWidth;
+
+ /// True when the sidebar must collapse into bottom navigation.
+ public static bool IsCompact(double effectiveWidth) => effectiveWidth < CompactWidth;
+}
diff --git a/src/Bydlo.App/ViewModels/MainViewModel.cs b/src/Bydlo.App/ViewModels/MainViewModel.cs
index f593b0e5..03d52368 100644
--- a/src/Bydlo.App/ViewModels/MainViewModel.cs
+++ b/src/Bydlo.App/ViewModels/MainViewModel.cs
@@ -1,4 +1,5 @@
using System.Collections.ObjectModel;
+using Avalonia.Media;
using Avalonia.Threading;
using Bydlo.App.Services;
using Bydlo.Core.Connection;
@@ -69,6 +70,7 @@ public MainViewModel(AppServices services, Bydlo.Core.Import.SubscriptionClient?
_isOnboardingVisible = !services.Settings.OnboardingCompleted;
_onboardingLanguage = services.Settings.Language;
_onboardingTheme = services.Settings.Theme;
+ _interfaceScale = services.Settings.InterfaceScale;
_consentAutomaticUpdates = services.Settings.ConsentAutomaticUpdates;
_consentNotifications = services.Settings.ConsentNotifications;
_consentThemes = services.Settings.ConsentThemes;
@@ -271,6 +273,36 @@ private void EditChain(ChainItem item)
[NotifyPropertyChangedFor(nameof(IsSettingsDetail))]
private bool _isCompact;
+ /// Shell width in scaled layout units, reported by the root view (issue #477).
+ [ObservableProperty]
+ private double _layoutWidth;
+
+ /// Interface scale in percent; the root view applies it as a layout transform.
+ [ObservableProperty]
+ [NotifyPropertyChangedFor(nameof(InterfaceScaleFactor))]
+ [NotifyPropertyChangedFor(nameof(InterfaceScaleTransform))]
+ private int _interfaceScale = AppSettings.DefaultInterfaceScale;
+
+ /// Layout multiplier for ; 1.0 is 100%.
+ public double InterfaceScaleFactor => AppSettings.ClampInterfaceScale(InterfaceScale) / 100.0;
+
+ ///
+ /// Layout transform for the shell root. A new instance per change makes the
+ /// LayoutTransformControl re-measure instead of relying on a mutated matrix.
+ ///
+ public ITransform InterfaceScaleTransform => new ScaleTransform(InterfaceScaleFactor, InterfaceScaleFactor);
+
+ partial void OnLayoutWidthChanged(double value) => RefreshCompact();
+
+ partial void OnInterfaceScaleChanged(int value) => RefreshCompact();
+
+ ///
+ /// The scale shrinks the unscaled layout width, so the sidebar/bottom switch must compare the
+ /// effective width instead of the window width.
+ ///
+ private void RefreshCompact() =>
+ IsCompact = LayoutMetrics.IsCompact(LayoutMetrics.EffectiveWidth(LayoutWidth, InterfaceScaleFactor));
+
[ObservableProperty]
private ProfileItem? _selectedProfile;
diff --git a/src/Bydlo.App/ViewModels/SettingsViewModel.cs b/src/Bydlo.App/ViewModels/SettingsViewModel.cs
index 0b8660bb..8c0760a7 100644
--- a/src/Bydlo.App/ViewModels/SettingsViewModel.cs
+++ b/src/Bydlo.App/ViewModels/SettingsViewModel.cs
@@ -58,6 +58,7 @@ public SettingsViewModel(MainViewModel shell)
var s = Services.Settings;
_theme = s.Theme;
_reduceMotion = s.ReduceMotion;
+ _interfaceScale = s.InterfaceScale;
_language = s.Language;
_mockMode = Services.IsMock;
_mockScenario = s.MockScenario;
@@ -93,6 +94,7 @@ public override void OnShown()
var s = Services.Settings;
Theme = s.Theme;
ReduceMotion = s.ReduceMotion;
+ InterfaceScale = s.InterfaceScale;
Language = s.Language;
MockMode = Services.IsMock;
MockScenario = s.MockScenario;
@@ -133,6 +135,31 @@ partial void OnReduceMotionChanged(bool value)
Persist();
}
+ /// Selectable interface scales in percent (issue #477).
+ public static IReadOnlyList InterfaceScales { get; } = AppSettings.InterfaceScaleSteps;
+
+ [ObservableProperty] private int _interfaceScale;
+
+ partial void OnInterfaceScaleChanged(int value)
+ {
+ var clamped = AppSettings.ClampInterfaceScale(value);
+ if (clamped != value)
+ {
+ InterfaceScale = clamped;
+ return;
+ }
+ Services.Settings.InterfaceScale = clamped;
+ Shell.InterfaceScale = clamped;
+ Persist();
+ }
+
+ [RelayCommand]
+ private void ResetInterfaceScale()
+ {
+ InterfaceScale = AppSettings.DefaultInterfaceScale;
+ Shell.ShowToast(L["settings.scale.reset.done"]);
+ }
+
public bool AutostartSupported => new Bydlo.Platform.AutostartService().IsSupported;
[ObservableProperty] private bool _startWithSystem;
diff --git a/src/Bydlo.App/Views/AppearanceSettingsView.axaml b/src/Bydlo.App/Views/AppearanceSettingsView.axaml
index 21532974..461f12a9 100644
--- a/src/Bydlo.App/Views/AppearanceSettingsView.axaml
+++ b/src/Bydlo.App/Views/AppearanceSettingsView.axaml
@@ -17,6 +17,20 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/Bydlo.App/Views/ConnectionsView.axaml b/src/Bydlo.App/Views/ConnectionsView.axaml
index cfb7546f..078dc9f1 100644
--- a/src/Bydlo.App/Views/ConnectionsView.axaml
+++ b/src/Bydlo.App/Views/ConnectionsView.axaml
@@ -87,7 +87,7 @@
-
+
-
+
diff --git a/src/Bydlo.App/Views/MainView.axaml b/src/Bydlo.App/Views/MainView.axaml
index f5fba25b..5e419a11 100644
--- a/src/Bydlo.App/Views/MainView.axaml
+++ b/src/Bydlo.App/Views/MainView.axaml
@@ -36,276 +36,280 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
+
+
+
+
+
+
+
-
-
-
+
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
+
-
-
-
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
diff --git a/src/Bydlo.App/Views/MainView.axaml.cs b/src/Bydlo.App/Views/MainView.axaml.cs
index e29682e4..14dade16 100644
--- a/src/Bydlo.App/Views/MainView.axaml.cs
+++ b/src/Bydlo.App/Views/MainView.axaml.cs
@@ -3,6 +3,7 @@
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
+using Bydlo.App.Services;
using Bydlo.Core.Import;
using Bydlo.App.ViewModels;
@@ -11,7 +12,7 @@ namespace Bydlo.App.Views;
public sealed partial class MainView : UserControl
{
/// Below this width the sidebar collapses into bottom navigation (phones, narrow windows).
- public const double CompactWidth = 760;
+ public const double CompactWidth = LayoutMetrics.CompactWidth;
public MainView()
{
@@ -107,7 +108,9 @@ protected override void OnSizeChanged(SizeChangedEventArgs e)
base.OnSizeChanged(e);
if (DataContext is MainViewModel vm)
{
- vm.IsCompact = e.NewSize.Width < CompactWidth;
+ // The interface scale shrinks the layout width, so the shell reports its scaled width
+ // and the view model compares the effective unscaled width (issue #477).
+ vm.LayoutWidth = e.NewSize.Width;
}
}
}
diff --git a/src/Bydlo.App/Views/RoutingView.axaml b/src/Bydlo.App/Views/RoutingView.axaml
index 18506a9d..43abcc90 100644
--- a/src/Bydlo.App/Views/RoutingView.axaml
+++ b/src/Bydlo.App/Views/RoutingView.axaml
@@ -131,7 +131,7 @@
-
+
@@ -159,15 +159,15 @@
-
+
-
-
-
-
+
+
+
+
diff --git a/src/Bydlo.Core/Backup/BackupArchive.cs b/src/Bydlo.Core/Backup/BackupArchive.cs
index 653470d0..e95cfa64 100644
--- a/src/Bydlo.Core/Backup/BackupArchive.cs
+++ b/src/Bydlo.Core/Backup/BackupArchive.cs
@@ -207,6 +207,8 @@ public static AppSettings ImportSettings(BackupData data, AppSettings current, B
settings.ConsentsInitialized = current.ConsentsInitialized;
// Custom theme files live next to the data directory and are not part of the backup.
settings.CustomThemeId = current.CustomThemeId;
+ // The interface scale is a display preference, so a restored value is snapped to a supported step.
+ settings.NormalizeInterfaceScale();
settings.MigrateLegacyTheme();
if (settings.Theme == ThemePreference.Custom && settings.CustomThemeId is null)
{
@@ -282,6 +284,7 @@ s.Routing.RemoteDnsRuleSets is null || s.Routing.DirectDnsRuleSets is null || s.
s.TgWsProxy.DcIps is null || s.TgWsProxy.CfProxyDomains is null || s.TgWsProxy.Host is null || s.TgWsProxy.FakeTlsDomain is null ||
s.LocalProxyUsername is null ||
s.LocalProxyPort is < 1 or > 65534 || s.TgWsProxy.Port is < 1 or > 65535 ||
+ s.InterfaceScale is < AppSettings.MinInterfaceScale or > AppSettings.MaxInterfaceScale ||
!Enum.IsDefined(s.Theme) || !Enum.IsDefined(s.Mode) || !Enum.IsDefined(s.MockScenario) || !Enum.IsDefined(s.IpCheckProvider) ||
s.Language is not ("auto" or "en" or "ru"))
{ throw new InvalidDataException("Invalid settings."); }
diff --git a/src/Bydlo.Core/Backup/BackupCopy.cs b/src/Bydlo.Core/Backup/BackupCopy.cs
index 6e2f89e1..6cf9b5d8 100644
--- a/src/Bydlo.Core/Backup/BackupCopy.cs
+++ b/src/Bydlo.Core/Backup/BackupCopy.cs
@@ -94,6 +94,7 @@ internal static class BackupCopy
SuggestClipboardLinks = source.SuggestClipboardLinks,
Theme = source.Theme,
ReduceMotion = source.ReduceMotion,
+ InterfaceScale = source.InterfaceScale,
CustomThemeId = source.CustomThemeId,
Language = source.Language,
OnboardingCompleted = source.OnboardingCompleted,
diff --git a/src/Bydlo.Core/Models/AppSettings.cs b/src/Bydlo.Core/Models/AppSettings.cs
index 2e57c123..a9752851 100644
--- a/src/Bydlo.Core/Models/AppSettings.cs
+++ b/src/Bydlo.Core/Models/AppSettings.cs
@@ -53,6 +53,52 @@ public sealed class AppSettings
public bool ReduceMotion { get; set; }
+ ///
+ /// Interface scale in percent (issue #477). The shell applies it once through a layout transform,
+ /// so text, buttons, fields, paddings and icons grow together and stay vector-sharp.
+ ///
+ public int InterfaceScale { get; set; } = DefaultInterfaceScale;
+
+ public const int DefaultInterfaceScale = 100;
+
+ public const int MinInterfaceScale = 80;
+
+ public const int MaxInterfaceScale = 150;
+
+ public const int InterfaceScaleStep = 10;
+
+ /// Every selectable scale, ascending. The default is in the middle of the list.
+ public static IReadOnlyList InterfaceScaleSteps { get; } =
+ [.. Enumerable.Range(0, (MaxInterfaceScale - MinInterfaceScale) / InterfaceScaleStep + 1)
+ .Select(index => MinInterfaceScale + index * InterfaceScaleStep)];
+
+ ///
+ /// Clamps a stored, imported or hand-edited scale to the supported range and snaps it to the
+ /// nearest step, so the UI never shows a value it cannot offer.
+ ///
+ public static int ClampInterfaceScale(int value)
+ {
+ var clamped = Math.Clamp(value, MinInterfaceScale, MaxInterfaceScale);
+ var steps = (clamped - MinInterfaceScale + InterfaceScaleStep / 2) / InterfaceScaleStep;
+ return MinInterfaceScale + steps * InterfaceScaleStep;
+ }
+
+ /// Layout multiplier for ; 1.0 is 100%.
+ [System.Text.Json.Serialization.JsonIgnore]
+ public double InterfaceScaleFactor => ClampInterfaceScale(InterfaceScale) / 100.0;
+
+ /// Repairs a scale written by an older build or edited by hand. Returns true when changed.
+ public bool NormalizeInterfaceScale()
+ {
+ var clamped = ClampInterfaceScale(InterfaceScale);
+ if (clamped == InterfaceScale)
+ {
+ return false;
+ }
+ InterfaceScale = clamped;
+ return true;
+ }
+
/// Installed custom theme id (file themes/<id>.json). Used only when is Custom.
public string? CustomThemeId { get; set; }
diff --git a/src/Bydlo.Core/Storage/JsonFileStore.cs b/src/Bydlo.Core/Storage/JsonFileStore.cs
index 63c489f7..9973a20c 100644
--- a/src/Bydlo.Core/Storage/JsonFileStore.cs
+++ b/src/Bydlo.Core/Storage/JsonFileStore.cs
@@ -191,6 +191,7 @@ public async Task LoadAsync(CancellationToken ct = default)
LoadStatus = status;
var result = settings ?? new AppSettings();
result.MigrateLegacyTheme();
+ result.NormalizeInterfaceScale();
return result;
}
diff --git a/tests/Bydlo.Tests/InterfaceScaleTests.cs b/tests/Bydlo.Tests/InterfaceScaleTests.cs
new file mode 100644
index 00000000..f48d1519
--- /dev/null
+++ b/tests/Bydlo.Tests/InterfaceScaleTests.cs
@@ -0,0 +1,238 @@
+using System.Text.Json;
+using Bydlo.App.Services;
+using Bydlo.App.Views;
+using Bydlo.Core.Backup;
+using Bydlo.Core.Models;
+using Bydlo.Core.Storage;
+
+namespace Bydlo.Tests;
+
+/// Issue #477: interface scale setting, persistence, backup validation and the navigation breakpoint.
+public class InterfaceScaleTests
+{
+ [Fact]
+ public void Fresh_settings_use_100_percent()
+ {
+ var settings = new AppSettings();
+ Assert.Equal(100, settings.InterfaceScale);
+ Assert.Equal(1.0, settings.InterfaceScaleFactor);
+ Assert.Equal(AppSettings.DefaultInterfaceScale, settings.InterfaceScale);
+ }
+
+ [Fact]
+ public void Selectable_steps_cover_the_supported_range()
+ {
+ var steps = AppSettings.InterfaceScaleSteps;
+ Assert.Equal(AppSettings.MinInterfaceScale, steps[0]);
+ Assert.Equal(AppSettings.MaxInterfaceScale, steps[^1]);
+ Assert.Contains(AppSettings.DefaultInterfaceScale, steps);
+ Assert.All(steps, step => Assert.Equal(0, (step - AppSettings.MinInterfaceScale) % AppSettings.InterfaceScaleStep));
+ Assert.Equal(steps.Count, steps.Distinct().Count());
+ Assert.Equal(steps.Order(), steps);
+ }
+
+ [Theory]
+ [InlineData(0, 80)]
+ [InlineData(-40, 80)]
+ [InlineData(79, 80)]
+ [InlineData(80, 80)]
+ [InlineData(84, 80)]
+ [InlineData(85, 90)]
+ [InlineData(100, 100)]
+ [InlineData(104, 100)]
+ [InlineData(105, 110)]
+ [InlineData(130, 130)]
+ [InlineData(149, 150)]
+ [InlineData(150, 150)]
+ [InlineData(151, 150)]
+ [InlineData(1000, 150)]
+ public void Out_of_range_values_are_clamped_and_snapped(int stored, int expected)
+ {
+ Assert.Equal(expected, AppSettings.ClampInterfaceScale(stored));
+ Assert.Contains(expected, AppSettings.InterfaceScaleSteps);
+ }
+
+ [Fact]
+ public void Normalize_repairs_a_hand_edited_value()
+ {
+ var settings = new AppSettings { InterfaceScale = 999 };
+ Assert.True(settings.NormalizeInterfaceScale());
+ Assert.Equal(150, settings.InterfaceScale);
+ Assert.False(settings.NormalizeInterfaceScale());
+
+ settings.InterfaceScale = 0;
+ Assert.True(settings.NormalizeInterfaceScale());
+ Assert.Equal(80, settings.InterfaceScale);
+ }
+
+ [Fact]
+ public async Task Scale_survives_a_settings_round_trip()
+ {
+ var path = Path.Combine(TestDirs.New("interface-scale"), "settings.json");
+ await new SettingsStore(path).SaveAsync(new AppSettings { InterfaceScale = 130 });
+ var reloaded = await new SettingsStore(path).LoadAsync();
+ Assert.Equal(130, reloaded.InterfaceScale);
+ Assert.Equal(1.3, reloaded.InterfaceScaleFactor, 3);
+ }
+
+ [Fact]
+ public async Task Loading_repairs_an_unsupported_stored_scale()
+ {
+ var path = Path.Combine(TestDirs.New("interface-scale-repair"), "settings.json");
+ await File.WriteAllTextAsync(path, """{"InterfaceScale": 500}""");
+ var reloaded = await new SettingsStore(path).LoadAsync();
+ Assert.Equal(AppSettings.MaxInterfaceScale, reloaded.InterfaceScale);
+ }
+
+ [Fact]
+ public async Task Settings_without_the_field_keep_the_default()
+ {
+ var path = Path.Combine(TestDirs.New("interface-scale-legacy"), "settings.json");
+ await File.WriteAllTextAsync(path, """{"LocalProxyPort": 2080}""");
+ var reloaded = await new SettingsStore(path).LoadAsync();
+ Assert.Equal(AppSettings.DefaultInterfaceScale, reloaded.InterfaceScale);
+ }
+
+ [Theory]
+ [InlineData(80)]
+ [InlineData(100)]
+ [InlineData(150)]
+ public void Backup_validation_accepts_supported_scales(int scale)
+ {
+ var data = new BackupData();
+ data.Settings.InterfaceScale = scale;
+ BackupArchive.Validate(data);
+ }
+
+ [Theory]
+ [InlineData(0)]
+ [InlineData(79)]
+ [InlineData(151)]
+ [InlineData(1000)]
+ public void Backup_validation_rejects_out_of_range_scales(int scale)
+ {
+ var data = new BackupData();
+ data.Settings.InterfaceScale = scale;
+ Assert.Throws(() => BackupArchive.Validate(data));
+ }
+
+ [Fact]
+ public void Backup_import_copies_the_scale()
+ {
+ var data = new BackupData();
+ data.Settings.InterfaceScale = 120;
+ var restored = BackupArchive.ImportSettings(data, new AppSettings { InterfaceScale = 80 }, BackupImportMode.Replace);
+ Assert.Equal(120, restored.InterfaceScale);
+ }
+
+ [Fact]
+ public void Backup_import_snaps_an_unsupported_scale()
+ {
+ var data = new BackupData();
+ data.Settings.InterfaceScale = 145;
+ var restored = BackupArchive.ImportSettings(data, new AppSettings(), BackupImportMode.Merge);
+ Assert.Equal(150, restored.InterfaceScale);
+ }
+
+ [Fact]
+ public void Backup_round_trip_keeps_the_scale()
+ {
+ var data = new BackupData();
+ data.Settings.InterfaceScale = 90;
+ var decrypted = BackupArchive.Decrypt(BackupArchive.Encrypt(data, "correct horse battery staple"), "correct horse battery staple");
+ Assert.Equal(90, decrypted.Settings.InterfaceScale);
+ }
+
+ [Theory]
+ [InlineData(1180, 1.0, false)]
+ [InlineData(760, 1.0, false)]
+ [InlineData(759, 1.0, true)]
+ [InlineData(1180, 1.5, false)]
+ [InlineData(1140, 1.5, false)]
+ [InlineData(1139, 1.5, true)]
+ [InlineData(1180, 0.8, false)]
+ [InlineData(608, 0.8, false)]
+ [InlineData(607, 0.8, true)]
+ public void Navigation_switch_uses_the_effective_unscaled_width(double windowWidth, double scale, bool compact)
+ {
+ var effective = LayoutMetrics.EffectiveWidth(windowWidth, scale);
+ Assert.Equal(compact, LayoutMetrics.IsCompact(effective));
+ }
+
+ [Fact]
+ public void Effective_width_ignores_a_broken_scale()
+ {
+ Assert.Equal(900, LayoutMetrics.EffectiveWidth(900, 0));
+ Assert.Equal(900, LayoutMetrics.EffectiveWidth(900, double.NaN));
+ Assert.Equal(900, LayoutMetrics.EffectiveWidth(900, double.PositiveInfinity));
+ }
+
+ [Fact]
+ public void Shell_recomputes_the_navigation_switch_when_the_scale_changes()
+ {
+ // 1180 at 100% is a sidebar layout; the same window at 150% leaves 786 unscaled units,
+ // and 1140 at 150% lands exactly on the breakpoint.
+ Assert.False(LayoutMetrics.IsCompact(LayoutMetrics.EffectiveWidth(1180, 1.0)));
+ Assert.False(LayoutMetrics.IsCompact(LayoutMetrics.EffectiveWidth(1180, 1.5)));
+ Assert.True(LayoutMetrics.IsCompact(LayoutMetrics.EffectiveWidth(1100, 1.5)));
+ Assert.Equal(MainView.CompactWidth, LayoutMetrics.CompactWidth);
+ }
+
+ [Fact]
+ public void Shell_applies_the_scale_as_a_layout_transform()
+ {
+ var root = RepositoryRoot();
+ var view = File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Views", "MainView.axaml"));
+ Assert.Contains("", view, StringComparison.Ordinal);
+ Assert.Contains("", view, StringComparison.Ordinal);
+ // The transform must wrap the whole shell, not a single page.
+ Assert.True(view.IndexOf(" new ScaleTransform(", shell, StringComparison.Ordinal);
+ Assert.Contains("LayoutMetrics.IsCompact(LayoutMetrics.EffectiveWidth(LayoutWidth, InterfaceScaleFactor))", shell, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void Appearance_page_offers_the_scale_and_a_reset()
+ {
+ var root = RepositoryRoot();
+ var view = File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Views", "AppearanceSettingsView.axaml"));
+ Assert.Contains("ItemsSource=\"{x:Static vm:SettingsViewModel.InterfaceScales}\"", view, StringComparison.Ordinal);
+ Assert.Contains("SelectedItem=\"{Binding InterfaceScale}\"", view, StringComparison.Ordinal);
+ Assert.Contains("Command=\"{Binding ResetInterfaceScaleCommand}\"", view, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public void Scale_strings_exist_in_both_languages()
+ {
+ var root = RepositoryRoot();
+ var en = JsonSerializer.Deserialize>(
+ File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Assets", "Strings", "en.json")))!;
+ var ru = JsonSerializer.Deserialize>(
+ File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Assets", "Strings", "ru.json")))!;
+ string[] keys = ["settings.scale", "settings.scale.hint", "settings.scale.reset", "settings.scale.reset.done"];
+ foreach (var key in keys)
+ {
+ Assert.True(en.TryGetValue(key, out var english) && !string.IsNullOrWhiteSpace(english), "Missing en: " + key);
+ Assert.True(ru.TryGetValue(key, out var russian) && !string.IsNullOrWhiteSpace(russian), "Missing ru: " + key);
+ }
+ }
+
+ private static string RepositoryRoot()
+ {
+ for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent)
+ {
+ if (File.Exists(Path.Combine(dir.FullName, "BYDLO.slnx")))
+ {
+ return dir.FullName;
+ }
+ }
+ throw new DirectoryNotFoundException("Repository root not found.");
+ }
+}
diff --git a/tests/Bydlo.Tests/WindowScalingTests.cs b/tests/Bydlo.Tests/WindowScalingTests.cs
index 12b5edb5..f4e5dc7f 100644
--- a/tests/Bydlo.Tests/WindowScalingTests.cs
+++ b/tests/Bydlo.Tests/WindowScalingTests.cs
@@ -8,7 +8,7 @@ public class WindowScalingTests
{
private static double ReadCompactWidth(string root)
{
- var code = File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Views", "MainView.axaml.cs"));
+ var code = File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Services", "LayoutMetrics.cs"));
var m = Regex.Match(code, @"CompactWidth\s*=\s*(\d+(?:\.\d+)?)");
Assert.True(m.Success);
return double.Parse(m.Groups[1].Value, System.Globalization.CultureInfo.InvariantCulture);
@@ -20,8 +20,9 @@ public void Compact_breakpoint_parsed_from_code_and_used_for_iscompact()
var root = RepositoryRoot();
var width = ReadCompactWidth(root);
Assert.Equal(760, width);
+ // The shell reports its scaled width; the view model compares the effective unscaled width (issue #477).
var code = File.ReadAllText(Path.Combine(root, "src", "Bydlo.App", "Views", "MainView.axaml.cs"));
- Assert.Contains("IsCompact = e.NewSize.Width < CompactWidth", code, StringComparison.Ordinal);
+ Assert.Contains("vm.LayoutWidth = e.NewSize.Width", code, StringComparison.Ordinal);
// Real condition, not literals: just below switches, at and above do not.
Assert.True(759 < width);
Assert.False(760 < width);
diff --git a/tools/Bydlo.Screenshots/InterfaceScaleVerification.cs b/tools/Bydlo.Screenshots/InterfaceScaleVerification.cs
new file mode 100644
index 00000000..c9b573e9
--- /dev/null
+++ b/tools/Bydlo.Screenshots/InterfaceScaleVerification.cs
@@ -0,0 +1,126 @@
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Headless;
+using Avalonia.Threading;
+using Avalonia.VisualTree;
+using Bydlo.App.Services;
+using Bydlo.App.ViewModels;
+using Bydlo.App.Views;
+
+///
+/// Issue #477: the interface scale is one layout transform at the shell root, so the content keeps
+/// working in unscaled units and the navigation breakpoint does not move with the setting.
+/// Runs in Mock Mode only; no engine, no network.
+///
+internal static class InterfaceScaleVerification
+{
+ public static void Run(MainViewModel shell, string output)
+ {
+ shell.FinishOnboardingCommand.Execute(null);
+ Wait(shell.Connections.ImportTextAsync("trojan://pw@scale.example.invalid:443#Scale"));
+ Require(shell.Profiles.Count >= 1, "A mock profile is listed");
+
+ foreach (var scale in new[] { 80, 100, 150 })
+ {
+ shell.Settings.InterfaceScale = scale;
+ Pump();
+ Require(shell.InterfaceScale == scale, "The setting reaches the shell: " + scale);
+ Require(shell.Services.Settings.InterfaceScale == scale, "The setting is persisted: " + scale);
+
+ var window = Open(shell, 1180, 780);
+ var content = Content(window);
+ var expected = window.ClientSize.Width / (scale / 100.0);
+ Require(Math.Abs(content.Bounds.Width - expected) < 2,
+ $"The layout transform divides the width at {scale}%: {content.Bounds.Width:0.#} vs {expected:0.#}");
+ Require(!shell.IsCompact, "A 1180-wide window keeps the sidebar at " + scale + "%");
+ Require(ConnectAction(window).IsEffectivelyVisible, "The connect action stays visible at " + scale + "%");
+ Shoot(window, Path.Combine(output, $"interface-scale-{scale}.png"));
+ window.Close();
+ }
+
+ // The breakpoint compares the unscaled width: 1140 / 1.5 = 760 keeps the sidebar, 1139 switches.
+ shell.Settings.InterfaceScale = 150;
+ Pump();
+ var wide = Open(shell, 1140, 780);
+ Require(!shell.IsCompact, "1140 at 150% is exactly the breakpoint and keeps the sidebar");
+ wide.Close();
+ var narrow = Open(shell, 1139, 780);
+ Require(shell.IsCompact, "1139 at 150% switches to bottom navigation");
+ Require(BottomNavigation(narrow).IsEffectivelyVisible, "Bottom navigation is visible below the breakpoint");
+ Shoot(narrow, Path.Combine(output, "interface-scale-150-compact.png"));
+ narrow.Close();
+
+ // 80% must not switch earlier than 100%: the same window keeps the sidebar at both scales.
+ shell.Settings.InterfaceScale = 80;
+ Pump();
+ var small = Open(shell, 700, 780);
+ Require(!shell.IsCompact, "700 at 80% leaves 875 unscaled units and keeps the sidebar");
+ small.Close();
+
+ // The appearance page must offer the scale and the reset at the largest scale, keyboard included.
+ shell.Settings.InterfaceScale = 150;
+ shell.Navigate("settings");
+ Pump();
+ var settings = Open(shell, 1180, 780);
+ var picker = settings.GetVisualDescendants().OfType()
+ .Single(combo => ReferenceEquals(combo.ItemsSource, SettingsViewModel.InterfaceScales));
+ Require(picker.IsEffectivelyVisible && picker.Focusable, "The scale picker is visible and focusable");
+ Require(Equals(picker.SelectedItem, 150), "The scale picker shows the saved value");
+ var reset = settings.GetVisualDescendants().OfType