Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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 EverythingToolbar/NativeMethods.txt
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,4 @@ GetCurrentThread
THREAD_POWER_THROTTLING_STATE
THREAD_POWER_THROTTLING_CURRENT_VERSION
THREAD_POWER_THROTTLING_EXECUTION_SPEED
IsWindowVisible
44 changes: 40 additions & 4 deletions EverythingToolbar/Services/TaskbarLayoutProbe.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
using System.Windows;
using System.Windows.Automation;
using NLog;
using Windows.Win32;
using Windows.Win32.Foundation;
using AutomationCondition = System.Windows.Automation.Condition;

namespace EverythingToolbar.Services
Expand All @@ -12,7 +14,7 @@ namespace EverythingToolbar.Services
/// The bounds of the taskbar's icon cluster (Start button plus the task buttons) and the elements a
/// window placed on the taskbar must not overlap, all in screen pixels.
/// </summary>
internal readonly record struct TaskbarLayout(Rect? IconCluster, IReadOnlyList<Rect> Obstacles)
internal readonly record struct TaskbarLayout(Rect? IconCluster, IReadOnlyList<Rect> Obstacles, bool HasTray)
{
public bool IsMeasurable => IconCluster.HasValue || Obstacles.Count > 0;
}
Expand Down Expand Up @@ -45,6 +47,15 @@ public TaskbarLayout Measure(IntPtr taskbarHandle, bool refreshElements)
var obstacles = new List<Rect>();
Rect? iconCluster = null;

// The notification area window covers the whole tray and is cheap to query. The automation
// search below can briefly return nothing (e.g. while Explorer restarts), which would let the
// box run to the taskbar edge.
var notificationArea = GetNotificationAreaRect(taskbarHandle);
if (notificationArea is { } trayRect)
obstacles.Add(trayRect);

bool hasTray = notificationArea.HasValue;

try
{
var taskbar = AutomationElement.FromHandle(taskbarHandle);
Expand All @@ -53,7 +64,11 @@ public TaskbarLayout Measure(IntPtr taskbarHandle, bool refreshElements)
{
var iconRect = icon.Current.BoundingRectangle;
if (iconRect.Width > 0 && iconRect.Height > 0)
obstacles.Add(iconRect);
{
hasTray = true;
if (!IsInNotificationArea(iconRect, notificationArea))
obstacles.Add(iconRect);
}
}

var frame = GetFrame(taskbarHandle, taskbar);
Expand All @@ -72,7 +87,12 @@ AutomationElement child in frame.FindAll(TreeScope.Children, AutomationCondition
if (rect.Width <= 0 || rect.Height <= 0)
continue;

if (child.Current.AutomationId is SystemTrayIconAutomationId or WidgetsButtonAutomationId)
if (child.Current.AutomationId is SystemTrayIconAutomationId)
{
if (!IsInNotificationArea(rect, notificationArea))
obstacles.Add(rect);
}
else if (child.Current.AutomationId is WidgetsButtonAutomationId)
obstacles.Add(rect);
else if ((isVertical ? rect.Height : rect.Width) <= maxIconDimension)
iconCluster = iconCluster.HasValue ? Rect.Union(iconCluster.Value, rect) : rect;
Expand All @@ -87,7 +107,7 @@ AutomationElement child in frame.FindAll(TreeScope.Children, AutomationCondition
Logger.Warn(ex, "Could not measure the taskbar layout");
}

return new TaskbarLayout(iconCluster, obstacles);
return new TaskbarLayout(iconCluster, obstacles, hasTray);
}

/// <summary>
Expand Down Expand Up @@ -124,6 +144,22 @@ private AutomationElement[] GetTrayIcons(IntPtr taskbarHandle, AutomationElement
return _cachedTrayIcons;
}

// Tray icons inside the notification area are already covered by it. Skipping them also ignores the
// press animation of the "Show hidden icons" button, which briefly reports a larger rect.
private static bool IsInNotificationArea(Rect iconRect, Rect? notificationArea) =>
notificationArea is { } area && area.IntersectsWith(iconRect);

private static Rect? GetNotificationAreaRect(IntPtr taskbarHandle)
{
var trayNotify = (HWND)NativeMethods.FindWindowEx(taskbarHandle, IntPtr.Zero, "TrayNotifyWnd", null);
if (trayNotify.IsNull || !PInvoke.IsWindowVisible(trayNotify) || !PInvoke.GetWindowRect(trayNotify, out var r))
return null;

int width = r.right - r.left;
int height = r.bottom - r.top;
return width > 0 && height > 0 ? new Rect(r.left, r.top, width, height) : null;
}

private static PropertyCondition ById(string automationId) =>
new(AutomationElement.AutomationIdProperty, automationId);
}
Expand Down
3 changes: 3 additions & 0 deletions EverythingToolbar/Services/TaskbarWindowAnimator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ internal sealed class TaskbarWindowAnimator
private WidgetBounds? _target;
private WidgetBounds _from;

/// <summary>The bounds the window is at or moving to, or null while it is hidden.</summary>
public WidgetBounds? Target => _target;

public TaskbarWindowAnimator(IntPtr handle, Func<bool> animationsDisabled)
{
_hwnd = (HWND)handle;
Expand Down
104 changes: 102 additions & 2 deletions EverythingToolbar/TaskbarWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ public partial class TaskbarWindow
private readonly TaskbarLayoutProbe _layoutProbe = new();
private DateTime _settleDeadline;
private bool _refreshLayoutElements = true;
private readonly DispatcherTimer _incompleteLayoutTimer;
private int _incompleteLayoutRetries;
private readonly DispatcherTimer _stableMoveTimer;
private WidgetBounds? _pendingBounds;
private DateTime _pendingSince;
private (int Start, int End, bool IsVertical)? _lastGap;

private const double MaxSearchBoxWidthDip = 240;

Expand All @@ -49,6 +55,16 @@ public partial class TaskbarWindow

private const int RepositionIntervalMilliseconds = 150;

// A layout without tray is retried a few times (about 8 s in total) before it is used, since the
// tray is usually just not ready yet.
private const int MaxIncompleteLayoutRetries = 5;
private static readonly TimeSpan IncompleteLayoutFirstRetry = TimeSpan.FromMilliseconds(250);

// How long a new position has to be stable before the box moves there, as long as its current
// position is still free. Prevents the box from jumping back and forth while the taskbar reflows
// or a tray icon briefly disappears (e.g. when its app restarts).
private static readonly TimeSpan StableMoveDelay = TimeSpan.FromSeconds(5);

// The taskbar reports a layout change before it animates the buttons into their new places.
// On window close the only event arrives well before the reflow even starts, so a single
// measurement would read the old geometry. Keep re-measuring for this long instead.
Expand All @@ -71,6 +87,20 @@ public TaskbarWindow(WindowsPolicy windowsPolicy, ISettings settings)
};
_repositionTimer.Tick += OnRepositionTick;

_stableMoveTimer = new DispatcherTimer { Interval = StableMoveDelay };
_stableMoveTimer.Tick += (_, _) =>
{
_stableMoveTimer.Stop();
UpdatePosition();
};

_incompleteLayoutTimer = new DispatcherTimer();
_incompleteLayoutTimer.Tick += (_, _) =>
{
_incompleteLayoutTimer.Stop();
UpdatePosition();
};

Loaded += OnLoaded;
_settings.PropertyChanged += OnSettingsChanged;
Microsoft.Win32.SystemEvents.DisplaySettingsChanged += OnDisplaySettingsChanged;
Expand Down Expand Up @@ -98,6 +128,8 @@ protected override void OnClosed(EventArgs e)
Logger.Error(error, "Could not restore the OLE message filter");
}
_repositionTimer.Stop();
_incompleteLayoutTimer.Stop();
_stableMoveTimer.Stop();
_animator?.StopAnimation();
UnhookTaskbarEvents();
_settings.PropertyChanged -= OnSettingsChanged;
Expand Down Expand Up @@ -286,24 +318,90 @@ private void ApplyMeasuredLayout(IntPtr taskbarHandle, TaskbarLayout layout, int
if (!layout.IsMeasurable)
return;

// Without the tray the box would end up at the taskbar edge, so keep the last position and retry.
if (!layout.HasTray && _incompleteLayoutRetries < MaxIncompleteLayoutRetries)
{
_incompleteLayoutTimer.Interval = IncompleteLayoutFirstRetry * (1 << _incompleteLayoutRetries);
_incompleteLayoutRetries++;
Logger.Debug(
"Tray not found, retrying in {Delay} ms ({Retry}/{Max})",
_incompleteLayoutTimer.Interval.TotalMilliseconds,
_incompleteLayoutRetries,
MaxIncompleteLayoutRetries
);
_incompleteLayoutTimer.Stop();
_incompleteLayoutTimer.Start();
return;
}

_incompleteLayoutRetries = 0;

try
{
if (!TryGetVisibleTaskbarRect(taskbarHandle, out var taskbarRect))
return;

if (CalculateBounds(taskbarHandle, taskbarRect, layout) is { } bounds)
{
if (ShouldWaitForStableLayout(bounds))
return;

_pendingBounds = null;
_stableMoveTimer.Stop();
_animator?.MoveTo(bounds);
}
else if (_animator?.Hide() == true)
Logger.Debug("Not enough free space on the taskbar; hiding the search box.");
else
{
_pendingBounds = null;
_stableMoveTimer.Stop();
if (_animator?.Hide() == true)
Logger.Debug("Not enough free space on the taskbar; hiding the search box.");
}
}
catch (Exception ex)
{
Logger.Error(ex, "Error updating position");
}
}

/// <summary>
/// Returns true if the box can stay where it is for now, i.e. its current position is still free
/// and the new position has not been stable for <see cref="StableMoveDelay"/> yet.
/// </summary>
private bool ShouldWaitForStableLayout(WidgetBounds bounds)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think the increasing timeouts actually work as intended in practice here.

During an Explorer restart Windows fires taskbar events that keep the existing _repositionTimer active (firing every 150 ms). Because _repositionTimer triggers ApplyMeasuredLayout so quickly, it will increment _incompleteLayoutRetries every 150 ms and burn through all 5 retries in under a second so the increasing timeouts never really get used anyway.

Wouldn't it be much simpler to just drop the extra timer and retries and do something like:

if (!layout.HasTray)
    return;

If the tray really isn't ready yet for a split second while Explorer loads, we simply do nothing and keep our current position. As soon as Explorer finishes setting up the tray, it will fire fresh taskbar events anyway, which will automatically trigger UpdatePosition() and place the box properly.

What do you think?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, they burned through in under a second anyway. Replaced with if (!layout.HasTray) return;.

{
if (_animator?.Target is not { } current || current == bounds || _lastGap is not { } gap)
return false;

bool sameCrossAxis = gap.IsVertical
? current.Left == bounds.Left && current.Width == bounds.Width
: current.Top == bounds.Top && current.Height == bounds.Height;

int start = gap.IsVertical ? current.Top : current.Left;
int end = start + (gap.IsVertical ? current.Height : current.Width);
bool isCurrentPositionFree = sameCrossAxis && start >= gap.Start && end <= gap.End;

if (!isCurrentPositionFree)
return false;

var now = DateTime.UtcNow;
if (_pendingBounds != bounds)
{
_pendingBounds = bounds;
_pendingSince = now;
}
else if (now - _pendingSince >= StableMoveDelay)
{
return false;
}

// Check again once the delay has passed.
_stableMoveTimer.Stop();
_stableMoveTimer.Interval = StableMoveDelay - (now - _pendingSince);
_stableMoveTimer.Start();
return true;
}

/// <summary>
/// Fits the box into the free stretch of taskbar between the icon cluster and the nearest thing
/// on the aligned side of it. Returns null when that gap is too narrow to be useful.
Expand Down Expand Up @@ -354,6 +452,7 @@ int taskbarHeight
int padding = (int)(HorizontalPaddingDip * dpiScale);
var (gapLeft, gapRight) = ProjectSpan(taskbarHandle, gapStart, gapEnd, padding, isVertical: false);
int available = gapRight - gapLeft;
_lastGap = (gapLeft, gapRight, false);

int width;
int height;
Expand Down Expand Up @@ -426,6 +525,7 @@ int taskbarWidth
if (available < buttonSize)
return null;

_lastGap = (gapTop, gapBottom, true);
int width = buttonSize;
int height = Math.Min(available, buttonSize);
int x = (taskbarWidth - width) / 2;
Expand Down
Loading