Skip to content
Closed
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
18 changes: 16 additions & 2 deletions ApplicationUpdateService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,26 @@ internal sealed class ApplicationUpdateService
internal Version CurrentVersion =>
Assembly.GetExecutingAssembly().GetName().Version ?? new Version(0, 0);

internal async Task<ApplicationUpdateCheck> CheckAsync(CancellationToken cancellationToken = default)
/// <summary>
/// Ответ на вопрос "есть ли обновление". null - проверка не состоялась:
/// такой ответ ничего не говорит ни о наличии, ни об отсутствии обновления,
/// поэтому вызывающие должны оставить то, что знали раньше.
/// </summary>
internal async Task<ApplicationUpdateCheck?> CheckAsync(CancellationToken cancellationToken = default)
{
using var checkCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
checkCancellation.CancelAfter(TimeSpan.FromSeconds(30));
using var response = await Http.GetAsync(LatestReleaseApi, checkCancellation.Token);
response.EnsureSuccessStatusCode();
if (!response.IsSuccessStatusCode)
{
// The release API answers with a redirect or a throttled status now and
// then. EnsureSuccessStatusCode turned every such answer into an error
// entry in the log, and the log is the first thing a user is asked to
// send; report "no answer this round" instead, which is also what the
// callers below already do with a failed check.
AppLog.Info($"Release check answered {(int)response.StatusCode} {response.ReasonPhrase}");
return null;
}
await using var stream = await response.Content.ReadAsStreamAsync(checkCancellation.Token);
using var document = await JsonDocument.ParseAsync(stream, cancellationToken: checkCancellation.Token);
var root = document.RootElement;
Expand Down
6 changes: 5 additions & 1 deletion ApplicationUpdateWatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,11 @@ private async Task RunAsync(CancellationToken cancellationToken)
try
{
await Task.Delay(delay, cancellationToken);
Publish((await _service.CheckAsync(cancellationToken)).Update);
// Отсутствующий ответ ничего не говорит об обновлении, поэтому
// точку на значке он не трогает - как и сорвавшаяся проверка.
var check = await _service.CheckAsync(cancellationToken);
if (check is not null)
Publish(check.Update);
}
catch (OperationCanceledException)
{
Expand Down
103 changes: 87 additions & 16 deletions DiagnosticsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,44 @@ private sealed record PowerSample(double? Watts, long Ticks);
// обоих языковых вариантов сразу удваивала бы аллокации.
[ThreadStatic] private static System.Text.StringBuilder? _buffer;

/// <summary>
/// Tooltip text for the tray icon. The Russian wording overruns the 127
/// characters NotifyIcon.Text accepts as soon as the performance mode and the
/// hardware lines are shown together, and the readings at the end are exactly
/// what the user is looking for, so an overflowing tooltip is rebuilt once more
/// with short labels before anything is dropped.
/// </summary>
internal static string BuildCompactToolTip()
{
var text = BuildTooltip(compact: false);
if (text.Length <= MaxTooltipLength)
return text;

var compact = BuildTooltip(compact: true);
if (compact.Length <= MaxTooltipLength)
return compact;

// Still too long: keep the leading lines that fit whole rather than
// chopping a reading in half.
var cut = compact[..MaxTooltipLength];
var lastLineBreak = cut.LastIndexOfAny(['\r', '\n']);
return lastLineBreak > 0 ? cut[..lastLineBreak] : cut;
}

/// <summary>
/// Variant of <see cref="L.T"/> for wording that only needs shortening where
/// it is long - Russian. The English and Chinese texts already fit.
/// </summary>
private static string Label(bool compact, string compactRussian, string russian, string english, string? chinese = null)
=> L.T(compact ? compactRussian : russian, english, chinese);

private static string BuildTooltip(bool compact)
{
var state = HardwareSettings.ReadTooltipState();
var hasHardwareState = HardwareSensorSnapshot.TryParse(
state.SensorSnapshot, out var hardwareState) && hardwareState.IsFresh;
var mode = state.PerformanceModeActive
? L.T("производительный", "performance", "高性能")
? Label(compact, "произв.", "производительный", "performance", "高性能")
: L.T("умный", "smart", "智能");
var backlightLevel = hasHardwareState
? hardwareState.KeyboardBacklightMode switch
Expand Down Expand Up @@ -55,14 +86,17 @@ internal static string BuildCompactToolTip()
};
var text = _buffer ??= new System.Text.StringBuilder(MaxTooltipLength + 32);
text.Clear();
text.Append(L.T("Режим: ", "Mode: ", "模式:")).Append(mode);
text.AppendLine().Append(L.T("Подсветка: ", "Backlight: ", "背光:")).Append(backlight);
text.AppendLine().Append(L.T("Ограничение заряда: ", "Charge limit: ", "充电限制:")).Append(protection);
text.Append(Label(compact, "Реж.: ", "Режим: ", "Mode: ", "模式:")).Append(mode);
text.AppendLine().Append(Label(compact, "Свет: ", "Подсветка: ", "Backlight: ", "背光:")).Append(backlight);
text.AppendLine().Append(Label(compact, "Огр. заряда: ", "Ограничение заряда: ", "Charge limit: ", "充电限制:")).Append(protection);

var power = ReadBatteryPowerWatts();
if (power.HasValue)
{
text.AppendLine().Append(L.T("Питание: ", "Power: ", "功率:"));
// This is the battery's charge/discharge rate, not the machine's
// power draw: the EC exposes nothing else without administrator
// rights. Saying so keeps a held battery from looking like a fault.
text.AppendLine().Append(Label(compact, "Бат.: ", "Батарея: ", "Battery: ", "电池功率:"));
AppendPower(text, power.Value);
}

Expand All @@ -72,21 +106,49 @@ internal static string BuildCompactToolTip()
{
text.AppendLine().Append("CPU: ");
AppendTemperature(text, hardwareState.CpuTemperature);
text.Append(L.T("; батарея: ", "; battery: ", ";电池:"));
text.Append(Label(compact, "; бат.: ", "; батарея: ", "; battery: ", ";电池:"));
AppendTemperature(text, hardwareState.BatteryTemperature);
if (hardwareState.MemoryTemperature.HasValue)
{
// Zone 0x0B (DDRS in the firmware): the sensor this machine's
// right fan actually ramps for, so it explains noise that CPU
// temperature alone does not.
text.Append(Label(compact, "; пам.: ", "; память: ", "; memory: ", ";内存:"));
AppendTemperature(text, hardwareState.MemoryTemperature);
}
}
if (hardwareState.Fan1Rpm.HasValue || hardwareState.Fan2Rpm.HasValue)
if (hardwareState.Fan1Rpm.HasValue || hardwareState.Fan2Rpm.HasValue
|| hardwareState.Fan1Duty.HasValue || hardwareState.Fan2Duty.HasValue)
{
text.AppendLine().Append(L.T("Вентиляторы: ", "Fans: ", "风扇:"));
AppendFan(text, hardwareState.Fan1Rpm);
text.Append('/');
AppendFan(text, hardwareState.Fan2Rpm);
text.Append(L.T(" об/мин", " RPM", " 转/分"));
var hasRpm = hardwareState.Fan1Rpm.HasValue || hardwareState.Fan2Rpm.HasValue;
text.AppendLine().Append(Label(compact, "Вент.: ", "Вентиляторы: ", "Fans: ", "风扇:"));
if (hasRpm)
{
AppendFanValue(text, hardwareState.Fan1Rpm);
text.Append('/');
AppendFanValue(text, hardwareState.Fan2Rpm);
text.Append(L.T(" об/мин", " RPM", " 转/分"));
}
if (hardwareState.Fan1Duty.HasValue || hardwareState.Fan2Duty.HasValue)
{
// What the EC actually drives the fans with. The tach is a pair
// of non-atomic bytes the firmware latches once a second, so it
// can be torn and can stay unknown while the median waits for a
// second sample; the duty is valid in every reading. Showing it
// next to the speed tells whether silence means "idling" (duty
// near 0) or "the speed readout is lying" (duty is high).
if (hasRpm)
text.Append(Label(compact, "; ШИМ ", "; цикл ШИМ ", "; duty ", ",占空 "));
else
text.Append(Label(compact, "ШИМ ", "Цикл ШИМ ", "Duty ", "占空 "));
AppendFanValue(text, hardwareState.Fan1Duty);
text.Append('/');
AppendFanValue(text, hardwareState.Fan2Duty);
text.Append('%');
}
}
}

if (text.Length > MaxTooltipLength)
text.Length = MaxTooltipLength;
return text.ToString();
}

Expand All @@ -98,7 +160,10 @@ private static void AppendTemperature(System.Text.StringBuilder text, int? value
text.Append('?');
}

private static void AppendFan(System.Text.StringBuilder text, int? value)
// Shared by the fan speed and the fan duty: a missing reading stays "?",
// because 0 would look like a stalled fan rather than a sensor that answered
// nothing.
private static void AppendFanValue(System.Text.StringBuilder text, int? value)
{
if (value.HasValue)
text.Append(value.Value);
Expand All @@ -110,7 +175,13 @@ private static void AppendPower(System.Text.StringBuilder text, double watts)
{
if (Math.Abs(watts) < 0.05)
{
text.Append(L.T("0 Вт", "0 W", "0 瓦"));
// A charge limiter that already holds the battery inside its range, or
// a fully charged one, legitimately reports neither charge nor
// discharge. Spelling that out keeps "0 W" from reading as a dead
// sensor on machines whose EC reports no rate at all.
text.Append(L.T("0 Вт, без тока",
"0 W, idle",
"0 瓦(未充放电)"));
return;
}

Expand Down
28 changes: 22 additions & 6 deletions DriverUpdateService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -500,21 +500,37 @@ private static List<DriverComponent> ReadInstalledComponents()
Options = ForwardOnly()
};
using var missingResults = missingSearcher.Get();
// A forward-only enumerator releases each row as it moves on, so sorting
// the live ManagementObject sequence ran the key selector over rows that
// were already gone. On a machine with an orphaned device (here
// ROOT\SYSTEM\0002, CM_PROB_FAILED_INSTALL, with no Name and no PNPClass)
// that threw a NullReferenceException out of the whole inventory. Copy the
// three values while enumerating and sort the copies.
var missingDevices = new List<(string Name, string DeviceId, string PnpClass)>();
foreach (var item in missingResults)
{
using var device = item;
if (device is null)
continue;

missingDevices.Add((
Convert.ToString(device["Name"]) ?? string.Empty,
Convert.ToString(device["DeviceID"]) ?? string.Empty,
Convert.ToString(device["PNPClass"]) ?? string.Empty));
}

var missingDeviceId = -1;
foreach (var item in missingResults.Cast<ManagementObject>()
.OrderBy(item => Convert.ToString(item["DeviceID"]), StringComparer.OrdinalIgnoreCase))
foreach (var (name, deviceId, pnpClass) in missingDevices
.OrderBy(device => device.DeviceId, StringComparer.OrdinalIgnoreCase))
{
var name = Convert.ToString(item["Name"]);
var deviceId = Convert.ToString(item["DeviceID"]);
var pnpClass = Convert.ToString(item["PNPClass"]);
components.Add(new DriverComponent(
missingDeviceId--,
"MissingDevice",
string.IsNullOrWhiteSpace(name)
? L.T("Неизвестное устройство", "Unknown device", "未知设备")
: name,
"0",
pnpClass ?? string.Empty,
pnpClass,
deviceId));
}

Expand Down
Loading