diff --git a/src/common/monitors.cpp b/src/common/monitors.cpp index c96a78c86e..4acb0d0484 100644 --- a/src/common/monitors.cpp +++ b/src/common/monitors.cpp @@ -1,8 +1,9 @@ #include "pch.h" -#include "common.h" #include "monitors.h" +#include "common.h" + bool operator==(const ScreenSize& lhs, const ScreenSize& rhs) { auto lhs_tuple = std::make_tuple(lhs.rect.left, lhs.rect.right, lhs.rect.top, lhs.rect.bottom); @@ -10,48 +11,47 @@ bool operator==(const ScreenSize& lhs, const ScreenSize& rhs) return lhs_tuple == rhs_tuple; } -static BOOL CALLBACK get_displays_enum_cb(HMONITOR monitor, HDC hdc, LPRECT rect, LPARAM data) +static BOOL CALLBACK GetDisplaysEnumCb(HMONITOR monitor, HDC hdc, LPRECT rect, LPARAM data) { - MONITORINFOEX monitor_info; - monitor_info.cbSize = sizeof(MONITORINFOEX); - GetMonitorInfo(monitor, &monitor_info); - reinterpret_cast*>(data)->emplace_back(monitor, monitor_info.rcWork); + MONITORINFOEX monitorInfo; + monitorInfo.cbSize = sizeof(MONITORINFOEX); + if (GetMonitorInfo(monitor, &monitorInfo)) + { + reinterpret_cast*>(data)->emplace_back(monitor, monitorInfo.rcWork); + } return true; }; -static BOOL CALLBACK get_displays_enum_cb_with_toolbar(HMONITOR monitor, HDC hdc, LPRECT rect, LPARAM data) +static BOOL CALLBACK GetDisplaysEnumCbWithNonWorkingArea(HMONITOR monitor, HDC hdc, LPRECT rect, LPARAM data) { - MONITORINFOEX monitor_info; - monitor_info.cbSize = sizeof(MONITORINFOEX); - GetMonitorInfo(monitor, &monitor_info); - reinterpret_cast*>(data)->emplace_back(monitor, monitor_info.rcMonitor); + MONITORINFOEX monitorInfo; + monitorInfo.cbSize = sizeof(MONITORINFOEX); + if (GetMonitorInfo(monitor, &monitorInfo)) + { + reinterpret_cast*>(data)->emplace_back(monitor, monitorInfo.rcMonitor); + } return true; }; -std::vector MonitorInfo::GetMonitors(bool include_toolbar) +std::vector MonitorInfo::GetMonitors(bool includeNonWorkingArea) { std::vector monitors; - EnumDisplayMonitors(NULL, NULL, include_toolbar ? get_displays_enum_cb_with_toolbar : get_displays_enum_cb, reinterpret_cast(&monitors)); + EnumDisplayMonitors(NULL, NULL, includeNonWorkingArea ? GetDisplaysEnumCbWithNonWorkingArea : GetDisplaysEnumCb, reinterpret_cast(&monitors)); std::sort(begin(monitors), end(monitors), [](const MonitorInfo& lhs, const MonitorInfo& rhs) { return lhs.rect < rhs.rect; }); return monitors; } -int MonitorInfo::GetMonitorsCount() +static BOOL CALLBACK GetPrimaryDisplayEnumCb(HMONITOR monitor, HDC hdc, LPRECT rect, LPARAM data) { - return GetMonitors(true).size(); -} + MONITORINFOEX monitorInfo; + monitorInfo.cbSize = sizeof(MONITORINFOEX); -static BOOL CALLBACK get_primary_display_enum_cb(HMONITOR monitor, HDC hdc, LPRECT rect, LPARAM data) -{ - MONITORINFOEX monitor_info; - monitor_info.cbSize = sizeof(MONITORINFOEX); - GetMonitorInfo(monitor, &monitor_info); - if (monitor_info.dwFlags & MONITORINFOF_PRIMARY) + if (GetMonitorInfo(monitor, &monitorInfo) && (monitorInfo.dwFlags & MONITORINFOF_PRIMARY)) { reinterpret_cast(data)->handle = monitor; - reinterpret_cast(data)->rect = monitor_info.rcWork; + reinterpret_cast(data)->rect = monitorInfo.rcWork; } return true; }; @@ -59,26 +59,6 @@ static BOOL CALLBACK get_primary_display_enum_cb(HMONITOR monitor, HDC hdc, LPRE MonitorInfo MonitorInfo::GetPrimaryMonitor() { MonitorInfo primary({}, {}); - EnumDisplayMonitors(NULL, NULL, get_primary_display_enum_cb, reinterpret_cast(&primary)); + EnumDisplayMonitors(NULL, NULL, GetPrimaryDisplayEnumCb, reinterpret_cast(&primary)); return primary; } - -MonitorInfo MonitorInfo::GetFromWindow(HWND hwnd) -{ - auto monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); - return GetFromHandle(monitor); -} - -MonitorInfo MonitorInfo::GetFromPoint(POINT p) -{ - auto monitor = MonitorFromPoint(p, MONITOR_DEFAULTTONEAREST); - return GetFromHandle(monitor); -} - -MonitorInfo MonitorInfo::GetFromHandle(HMONITOR monitor) -{ - MONITORINFOEX monitor_info; - monitor_info.cbSize = sizeof(MONITORINFOEX); - GetMonitorInfo(monitor, &monitor_info); - return MonitorInfo(monitor, monitor_info.rcWork); -} diff --git a/src/common/monitors.h b/src/common/monitors.h index ebe77fabd2..b375fedd52 100644 --- a/src/common/monitors.h +++ b/src/common/monitors.h @@ -31,16 +31,8 @@ struct MonitorInfo : ScreenSize HMONITOR handle; // Returns monitor rects ordered from left to right - static std::vector GetMonitors(bool include_toolbar); - static int GetMonitorsCount(); - // Return primary display + static std::vector GetMonitors(bool includeNonWorkingArea); static MonitorInfo GetPrimaryMonitor(); - // Return monitor on which hwnd window is displayed - static MonitorInfo GetFromWindow(HWND hwnd); - // Return monitor nearest to a point - static MonitorInfo GetFromPoint(POINT p); - // Return monitor info given a HMONITOR - static MonitorInfo GetFromHandle(HMONITOR monitor); }; bool operator==(const ScreenSize& lhs, const ScreenSize& rhs); diff --git a/src/modules/fancyzones/editor/FancyZonesEditor/GridEditor.xaml.cs b/src/modules/fancyzones/editor/FancyZonesEditor/GridEditor.xaml.cs index dac0d88816..b4eb37d084 100644 --- a/src/modules/fancyzones/editor/FancyZonesEditor/GridEditor.xaml.cs +++ b/src/modules/fancyzones/editor/FancyZonesEditor/GridEditor.xaml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation +// Copyright (c) Microsoft Corporation // The Microsoft Corporation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. @@ -222,6 +222,7 @@ namespace FancyZonesEditor int newChildIndex = AddZone(); double offset = e.Offset; + double space = e.Space; if (e.Orientation == Orientation.Vertical) { @@ -294,22 +295,28 @@ namespace FancyZonesEditor model.CellChildMap = newCellChildMap; sourceCol = 0; + double newTotalExtent = ActualWidth - (space * (cols + 1)); for (int col = 0; col < cols; col++) { if (col == foundCol) { - RowColInfo[] split = _colInfo[col].Split(offset); + RowColInfo[] split = _colInfo[col].Split(offset, space); + newColInfo[col] = split[0]; newColPercents[col] = split[0].Percent; - newColInfo[col++] = split[0]; - newColPercents[col] = split[1].Percent; + col++; + newColInfo[col] = split[1]; - sourceCol++; + newColPercents[col] = split[1].Percent; } else { + newColInfo[col] = _colInfo[sourceCol]; + newColInfo[col].RecalculatePercent(newTotalExtent); + newColPercents[col] = model.ColumnPercents[sourceCol]; - newColInfo[col] = _colInfo[sourceCol++]; } + + sourceCol++; } _colInfo = newColInfo; @@ -389,22 +396,28 @@ namespace FancyZonesEditor model.CellChildMap = newCellChildMap; sourceRow = 0; + double newTotalExtent = ActualHeight - (space * (rows + 1)); for (int row = 0; row < rows; row++) { if (row == foundRow) { - RowColInfo[] split = _rowInfo[row].Split(offset); + RowColInfo[] split = _rowInfo[row].Split(offset, space); + newRowInfo[row] = split[0]; newRowPercents[row] = split[0].Percent; - newRowInfo[row++] = split[0]; - newRowPercents[row] = split[1].Percent; + row++; + newRowInfo[row] = split[1]; - sourceRow++; + newRowPercents[row] = split[1].Percent; } else { + newRowInfo[row] = _rowInfo[sourceRow]; + newRowInfo[row].RecalculatePercent(newTotalExtent); + newRowPercents[row] = model.RowPercents[sourceRow]; - newRowInfo[row] = _rowInfo[sourceRow++]; } + + sourceRow++; } _rowInfo = newRowInfo; diff --git a/src/modules/fancyzones/editor/FancyZonesEditor/GridZone.xaml.cs b/src/modules/fancyzones/editor/FancyZonesEditor/GridZone.xaml.cs index 5a8e330010..3cabac7190 100644 --- a/src/modules/fancyzones/editor/FancyZonesEditor/GridZone.xaml.cs +++ b/src/modules/fancyzones/editor/FancyZonesEditor/GridZone.xaml.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation +// Copyright (c) Microsoft Corporation // The Microsoft Corporation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. @@ -276,8 +276,15 @@ namespace FancyZonesEditor } private void DoSplit(Orientation orientation, double offset) - { - Split?.Invoke(this, new SplitEventArgs(orientation, offset)); + { + int spacing = 0; + Settings settings = ((App)Application.Current).ZoneSettings; + if (settings.ShowSpacing) + { + spacing = settings.Spacing; + } + + Split?.Invoke(this, new SplitEventArgs(orientation, offset, spacing)); } private void FullSplit_Click(object sender, RoutedEventArgs e) diff --git a/src/modules/fancyzones/editor/FancyZonesEditor/RowColInfo.cs b/src/modules/fancyzones/editor/FancyZonesEditor/RowColInfo.cs index a585e64387..861bd0f53a 100644 --- a/src/modules/fancyzones/editor/FancyZonesEditor/RowColInfo.cs +++ b/src/modules/fancyzones/editor/FancyZonesEditor/RowColInfo.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation +// Copyright (c) Microsoft Corporation // The Microsoft Corporation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. @@ -34,13 +34,24 @@ namespace FancyZonesEditor return Extent; } - public RowColInfo[] Split(double offset) + public void RecalculatePercent(double newTotalExtent) + { + Percent = (int)(Extent * _multiplier / newTotalExtent); + } + + public RowColInfo[] Split(double offset, double space) { RowColInfo[] info = new RowColInfo[2]; - int newPercent = (int)(Percent * offset / Extent); - info[0] = new RowColInfo(newPercent); - info[1] = new RowColInfo(Percent - newPercent); + double totalExtent = Extent * _multiplier / Percent; + totalExtent -= space; + + int percent0 = (int)(offset * _multiplier / totalExtent); + int percent1 = (int)((Extent - space - offset) * _multiplier / totalExtent); + + info[0] = new RowColInfo(percent0); + info[1] = new RowColInfo(percent1); + return info; } } diff --git a/src/modules/fancyzones/editor/FancyZonesEditor/SplitEventArgs.cs b/src/modules/fancyzones/editor/FancyZonesEditor/SplitEventArgs.cs index a8b2ef0bd2..239a1b92d7 100644 --- a/src/modules/fancyzones/editor/FancyZonesEditor/SplitEventArgs.cs +++ b/src/modules/fancyzones/editor/FancyZonesEditor/SplitEventArgs.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft Corporation +// Copyright (c) Microsoft Corporation // The Microsoft Corporation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. @@ -13,15 +13,18 @@ namespace FancyZonesEditor { } - public SplitEventArgs(Orientation orientation, double offset) + public SplitEventArgs(Orientation orientation, double offset, double thickness) { Orientation = orientation; Offset = offset; + Space = thickness; } public Orientation Orientation { get; } public double Offset { get; } + + public double Space { get; } } public delegate void SplitEventHandler(object sender, SplitEventArgs args); diff --git a/src/modules/fancyzones/lib/Zone.cpp b/src/modules/fancyzones/lib/Zone.cpp index 5460bbe82e..620dbae9f5 100644 --- a/src/modules/fancyzones/lib/Zone.cpp +++ b/src/modules/fancyzones/lib/Zone.cpp @@ -1,5 +1,8 @@ #include "pch.h" + +#include + #include #include #include "Zone.h" @@ -68,6 +71,45 @@ void Zone::SizeWindowToZone(HWND window, HWND zoneWindow) noexcept SizeWindowToRect(window, ComputeActualZoneRect(window, zoneWindow)); } +static BOOL CALLBACK saveDisplayToVector(HMONITOR monitor, HDC hdc, LPRECT rect, LPARAM data) +{ + reinterpret_cast*>(data)->emplace_back(monitor); + return true; +} + +bool allMonitorsHaveSameDpiScaling() +{ + std::vector monitors; + EnumDisplayMonitors(NULL, NULL, saveDisplayToVector, reinterpret_cast(&monitors)); + + if (monitors.size() < 2) + { + return true; + } + + UINT firstMonitorDpiX; + UINT firstMonitorDpiY; + + if (S_OK != GetDpiForMonitor(monitors[0], MDT_EFFECTIVE_DPI, &firstMonitorDpiX, &firstMonitorDpiY)) + { + return false; + } + + for (int i = 1; i < monitors.size(); i++) + { + UINT iteratedMonitorDpiX; + UINT iteratedMonitorDpiY; + + if (S_OK != GetDpiForMonitor(monitors[i], MDT_EFFECTIVE_DPI, &iteratedMonitorDpiX, &iteratedMonitorDpiY) || + iteratedMonitorDpiX != firstMonitorDpiX) + { + return false; + } + } + + return true; +} + RECT Zone::ComputeActualZoneRect(HWND window, HWND zoneWindow) noexcept { // Take care of 1px border @@ -101,7 +143,7 @@ RECT Zone::ComputeActualZoneRect(HWND window, HWND zoneWindow) noexcept const auto taskbar_top_size = std::abs(mi.rcMonitor.top - mi.rcWork.top); OffsetRect(&newWindowRect, -taskbar_left_size, -taskbar_top_size); - if (accountForUnawareness && MonitorInfo::GetMonitorsCount() > 1) + if (accountForUnawareness && !allMonitorsHaveSameDpiScaling()) { newWindowRect.left = max(mi.rcMonitor.left, newWindowRect.left); newWindowRect.right = min(mi.rcMonitor.right - taskbar_left_size, newWindowRect.right); diff --git a/src/modules/fancyzones/lib/ZoneWindow.cpp b/src/modules/fancyzones/lib/ZoneWindow.cpp index 81cd60ac22..711b33e623 100644 --- a/src/modules/fancyzones/lib/ZoneWindow.cpp +++ b/src/modules/fancyzones/lib/ZoneWindow.cpp @@ -213,7 +213,7 @@ public: IFACEMETHODIMP_(void) RestoreOrginalTransparency() noexcept; IFACEMETHODIMP_(bool) - IsDragEnabled() noexcept { return m_dragEnabled; } + IsDragEnabled() noexcept; IFACEMETHODIMP_(void) MoveWindowIntoZoneByIndex(HWND window, int index) noexcept; IFACEMETHODIMP_(void) @@ -223,13 +223,13 @@ public: IFACEMETHODIMP_(void) CycleActiveZoneSet(DWORD vkCode) noexcept; IFACEMETHODIMP_(std::wstring) - UniqueId() noexcept { return { m_uniqueId }; } + UniqueId() noexcept; IFACEMETHODIMP_(std::wstring) - WorkAreaKey() noexcept { return { m_workArea }; } + WorkAreaKey() noexcept; IFACEMETHODIMP_(void) SaveWindowProcessToZoneIndex(HWND window) noexcept; IFACEMETHODIMP_(IZoneSet*) - ActiveZoneSet() noexcept { return m_activeZoneSet.get(); } + ActiveZoneSet() noexcept; IFACEMETHODIMP_(void) ShowZoneWindow() noexcept; IFACEMETHODIMP_(void) @@ -267,13 +267,15 @@ private: static const UINT m_showAnimationDuration = 200; // ms static const UINT m_flashDuration = 700; // ms - HWND draggedWindow = nullptr; - long draggedWindowExstyle = 0; - COLORREF draggedWindowCrKey = RGB(0, 0, 0); - DWORD draggedWindowDwFlags = 0; - BYTE draggedWindowInitialAlpha = 0; + HWND m_draggedWindow = nullptr; + long m_draggedWindowExstyle = 0; + COLORREF m_draggedWindowCrKey = RGB(0, 0, 0); + DWORD m_draggedWindowDwFlags = 0; + BYTE m_draggedWindowInitialAlpha = 0; - ULONG_PTR gdiplusToken; + ULONG_PTR m_gdiplusToken; + + mutable std::shared_mutex m_mutex; }; ZoneWindow::ZoneWindow(HINSTANCE hinstance) @@ -287,14 +289,14 @@ ZoneWindow::ZoneWindow(HINSTANCE hinstance) RegisterClassExW(&wcex); Gdiplus::GdiplusStartupInput gdiplusStartupInput; - Gdiplus::GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); + Gdiplus::GdiplusStartup(&m_gdiplusToken, &gdiplusStartupInput, NULL); } ZoneWindow::~ZoneWindow() { RestoreOrginalTransparency(); - Gdiplus::GdiplusShutdown(gdiplusToken); + Gdiplus::GdiplusShutdown(m_gdiplusToken); } bool ZoneWindow::Init(IZoneWindowHost* host, HINSTANCE hinstance, HMONITOR monitor, const std::wstring& uniqueId, bool flashZones, bool newWorkArea) @@ -347,13 +349,24 @@ bool ZoneWindow::Init(IZoneWindowHost* host, HINSTANCE hinstance, HMONITOR monit IFACEMETHODIMP ZoneWindow::MoveSizeEnter(HWND window, bool dragEnabled) noexcept { - if (m_windowMoveSize) + std::shared_lock lock(m_mutex); + auto windowMoveSize = m_windowMoveSize; + auto hostTransparentActive = m_host->isMakeDraggedWindowTransparentActive(); + lock.unlock(); + + if (windowMoveSize) { return E_INVALIDARG; } - if (m_host->isMakeDraggedWindowTransparentActive()) + if (hostTransparentActive) { + decltype(m_draggedWindowExstyle) draggedWindowExstyle; + decltype(m_draggedWindow) draggedWindow; + decltype(m_draggedWindowCrKey) draggedWindowCrKey; + decltype(m_draggedWindowInitialAlpha) draggedWindowInitialAlpha; + decltype(m_draggedWindowDwFlags) draggedWindowDwFlags; + RestoreOrginalTransparency(); draggedWindowExstyle = GetWindowLong(window, GWL_EXSTYLE); @@ -366,27 +379,45 @@ IFACEMETHODIMP ZoneWindow::MoveSizeEnter(HWND window, bool dragEnabled) noexcept GetLayeredWindowAttributes(window, &draggedWindowCrKey, &draggedWindowInitialAlpha, &draggedWindowDwFlags); SetLayeredWindowAttributes(window, 0, (255 * 50) / 100, LWA_ALPHA); + + std::unique_lock writeLock(m_mutex); + m_draggedWindowExstyle = draggedWindowExstyle; + m_draggedWindow = draggedWindow; + m_draggedWindowCrKey = draggedWindowCrKey; + m_draggedWindowInitialAlpha = draggedWindowInitialAlpha; + m_draggedWindowDwFlags = draggedWindowDwFlags; } - m_dragEnabled = dragEnabled; - m_windowMoveSize = window; - m_drawHints = true; - m_highlightZone = {}; + { + std::unique_lock writeLock(m_mutex); + m_dragEnabled = dragEnabled; + m_windowMoveSize = window; + m_drawHints = true; + m_highlightZone = {}; + } + ShowZoneWindow(); return S_OK; } IFACEMETHODIMP ZoneWindow::MoveSizeUpdate(POINT const& ptScreen, bool dragEnabled) noexcept { + std::shared_lock lock(m_mutex); + auto window = m_window.get(); + lock.unlock(); + bool redraw = false; POINT ptClient = ptScreen; - MapWindowPoints(nullptr, m_window.get(), &ptClient, 1); + MapWindowPoints(nullptr, window, &ptClient, 1); + std::unique_lock writeLock(m_mutex); m_dragEnabled = dragEnabled; if (dragEnabled) { + writeLock.unlock(); auto highlightZone = ZonesFromPoint(ptClient); + writeLock.lock(); redraw = (highlightZone != m_highlightZone); m_highlightZone = std::move(highlightZone); } @@ -396,9 +427,11 @@ IFACEMETHODIMP ZoneWindow::MoveSizeUpdate(POINT const& ptScreen, bool dragEnable redraw = true; } + writeLock.unlock(); + if (redraw) { - InvalidateRect(m_window.get(), nullptr, true); + InvalidateRect(window, nullptr, true); } return S_OK; } @@ -407,30 +440,74 @@ IFACEMETHODIMP ZoneWindow::MoveSizeEnd(HWND window, POINT const& ptScreen) noexc { RestoreOrginalTransparency(); - if (m_windowMoveSize != window) + std::shared_lock lock(m_mutex); + auto windowMoveSize = m_windowMoveSize; + auto thisWindow = m_window.get(); + auto activeZoneSet = m_activeZoneSet; + lock.unlock(); + + if (windowMoveSize != window) { return E_INVALIDARG; } - if (m_activeZoneSet) + if (activeZoneSet) { POINT ptClient = ptScreen; - MapWindowPoints(nullptr, m_window.get(), &ptClient, 1); - m_activeZoneSet->MoveWindowIntoZoneByPoint(window, m_window.get(), ptClient); + MapWindowPoints(nullptr, thisWindow, &ptClient, 1); + activeZoneSet->MoveWindowIntoZoneByPoint(window, thisWindow, ptClient); SaveWindowProcessToZoneIndex(window); } - Trace::ZoneWindow::MoveSizeEnd(m_activeZoneSet); + Trace::ZoneWindow::MoveSizeEnd(activeZoneSet); HideZoneWindow(); + std::unique_lock writeLock(m_mutex); m_windowMoveSize = nullptr; return S_OK; } +IFACEMETHODIMP_(bool) +ZoneWindow::IsDragEnabled() noexcept +{ + std::shared_lock lock(m_mutex); + return m_dragEnabled; +} + +IFACEMETHODIMP_(std::wstring) +ZoneWindow::UniqueId() noexcept +{ + std::shared_lock lock(m_mutex); + return m_uniqueId; +} + +IFACEMETHODIMP_(std::wstring) +ZoneWindow::WorkAreaKey() noexcept +{ + std::shared_lock lock(m_mutex); + return m_workArea; +} + +IFACEMETHODIMP_(IZoneSet*) +ZoneWindow::ActiveZoneSet() noexcept +{ + std::shared_lock lock(m_mutex); + return m_activeZoneSet.get(); +} + IFACEMETHODIMP_(void) ZoneWindow::RestoreOrginalTransparency() noexcept { - if (m_host->isMakeDraggedWindowTransparentActive() && draggedWindow != nullptr) + std::shared_lock lock(m_mutex); + auto hostTransparentActive = m_host->isMakeDraggedWindowTransparentActive(); + auto draggedWindow = m_draggedWindow; + auto draggedWindowCrKey = m_draggedWindowCrKey; + auto draggedWindowInitialAlpha = m_draggedWindowInitialAlpha; + auto draggedWindowDwFlags = m_draggedWindowDwFlags; + auto draggedWindowExstyle = m_draggedWindowExstyle; + lock.unlock(); + + if (hostTransparentActive && draggedWindow != nullptr) { SetLayeredWindowAttributes(draggedWindow, draggedWindowCrKey, draggedWindowInitialAlpha, draggedWindowDwFlags); SetWindowLong(draggedWindow, GWL_EXSTYLE, draggedWindowExstyle); @@ -447,18 +524,28 @@ ZoneWindow::MoveWindowIntoZoneByIndex(HWND window, int index) noexcept IFACEMETHODIMP_(void) ZoneWindow::MoveWindowIntoZoneByIndexSet(HWND window, const std::vector& indexSet) noexcept { - if (m_activeZoneSet) + std::shared_lock lock(m_mutex); + auto thisWindow = m_window.get(); + auto activeZoneSet = m_activeZoneSet; + lock.unlock(); + + if (activeZoneSet) { - m_activeZoneSet->MoveWindowIntoZoneByIndexSet(window, m_window.get(), indexSet, false); + activeZoneSet->MoveWindowIntoZoneByIndexSet(window, thisWindow, indexSet, false); } } IFACEMETHODIMP_(bool) ZoneWindow::MoveWindowIntoZoneByDirection(HWND window, DWORD vkCode, bool cycle) noexcept { - if (m_activeZoneSet) + std::shared_lock lock(m_mutex); + auto thisWindow = m_window.get(); + auto activeZoneSet = m_activeZoneSet; + lock.unlock(); + + if (activeZoneSet) { - if (m_activeZoneSet->MoveWindowIntoZoneByDirection(window, m_window.get(), vkCode, cycle)) + if (activeZoneSet->MoveWindowIntoZoneByDirection(window, thisWindow, vkCode, cycle)) { SaveWindowProcessToZoneIndex(window); return true; @@ -472,9 +559,14 @@ ZoneWindow::CycleActiveZoneSet(DWORD wparam) noexcept { CycleActiveZoneSetInternal(wparam, Trace::ZoneWindow::InputMode::Keyboard); - if (m_windowMoveSize) + std::shared_lock lock(m_mutex); + auto windowMoveSize = m_windowMoveSize; + auto window = m_window.get(); + lock.unlock(); + + if (windowMoveSize) { - InvalidateRect(m_window.get(), nullptr, true); + InvalidateRect(window, nullptr, true); } else { @@ -485,15 +577,19 @@ ZoneWindow::CycleActiveZoneSet(DWORD wparam) noexcept IFACEMETHODIMP_(void) ZoneWindow::SaveWindowProcessToZoneIndex(HWND window) noexcept { - if (m_activeZoneSet) + std::shared_lock lock(m_mutex); + auto activeZoneSet = m_activeZoneSet; + lock.unlock(); + + if (activeZoneSet) { - DWORD zoneIndex = static_cast(m_activeZoneSet->GetZoneIndexFromWindow(window)); + DWORD zoneIndex = static_cast(activeZoneSet->GetZoneIndexFromWindow(window)); if (zoneIndex != -1) { OLECHAR* guidString; - if (StringFromCLSID(m_activeZoneSet->Id(), &guidString) == S_OK) + if (StringFromCLSID(activeZoneSet->Id(), &guidString) == S_OK) { - JSONHelpers::FancyZonesDataInstance().SetAppLastZone(window, m_uniqueId, guidString, zoneIndex); + JSONHelpers::FancyZonesDataInstance().SetAppLastZone(window, UniqueId(), guidString, zoneIndex); } CoTaskMemFree(guidString); @@ -504,31 +600,43 @@ ZoneWindow::SaveWindowProcessToZoneIndex(HWND window) noexcept IFACEMETHODIMP_(void) ZoneWindow::ShowZoneWindow() noexcept { - if (m_window) + std::shared_lock lock(m_mutex); + auto window = m_window.get(); + HWND windowInsertAfter = m_windowMoveSize; + lock.unlock(); + + if (window) { - m_flashMode = false; + { + std::unique_lock writeLock(m_mutex); + m_flashMode = false; + } UINT flags = SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE; - HWND windowInsertAfter = m_windowMoveSize; if (windowInsertAfter == nullptr) { windowInsertAfter = HWND_TOPMOST; } - SetWindowPos(m_window.get(), windowInsertAfter, 0, 0, 0, 0, flags); + SetWindowPos(window, windowInsertAfter, 0, 0, 0, 0, flags); - AnimateWindow(m_window.get(), m_showAnimationDuration, AW_BLEND); - InvalidateRect(m_window.get(), nullptr, true); + AnimateWindow(window, m_showAnimationDuration, AW_BLEND); + InvalidateRect(window, nullptr, true); } } IFACEMETHODIMP_(void) ZoneWindow::HideZoneWindow() noexcept { - if (m_window) + std::shared_lock lock(m_mutex); + auto window = m_window.get(); + lock.unlock(); + + if (window) { - ShowWindow(m_window.get(), SW_HIDE); + ShowWindow(window, SW_HIDE); + std::unique_lock writeLock(m_mutex); m_keyLast = 0; m_windowMoveSize = nullptr; m_drawHints = false; @@ -540,27 +648,34 @@ ZoneWindow::HideZoneWindow() noexcept void ZoneWindow::LoadSettings() noexcept { - JSONHelpers::FancyZonesDataInstance().AddDevice(m_uniqueId); + JSONHelpers::FancyZonesDataInstance().AddDevice(UniqueId()); } void ZoneWindow::InitializeZoneSets(bool newWorkArea) noexcept { + std::shared_lock lock(m_mutex); auto parent = m_host->GetParentZoneWindow(m_monitor); + lock.unlock(); + if (newWorkArea && parent) { // Update device info with device info from parent virtual desktop (if empty). - JSONHelpers::FancyZonesDataInstance().CloneDeviceInfo(parent->UniqueId(), m_uniqueId); + JSONHelpers::FancyZonesDataInstance().CloneDeviceInfo(parent->UniqueId(), UniqueId()); } CalculateZoneSet(); } void ZoneWindow::CalculateZoneSet() noexcept { + std::unique_lock lock(m_mutex); + auto monitor = m_monitor; + lock.unlock(); + const auto& fancyZonesData = JSONHelpers::FancyZonesDataInstance(); - const auto deviceInfoData = fancyZonesData.FindDeviceInfo(m_uniqueId); + const auto deviceInfoData = fancyZonesData.FindDeviceInfo(UniqueId()); const auto& activeDeviceId = fancyZonesData.GetActiveDeviceId(); - if (!activeDeviceId.empty() && activeDeviceId != m_uniqueId) + if (!activeDeviceId.empty() && activeDeviceId != UniqueId()) { return; } @@ -583,11 +698,11 @@ void ZoneWindow::CalculateZoneSet() noexcept auto zoneSet = MakeZoneSet(ZoneSetConfig( zoneSetId, activeZoneSet.type, - m_monitor, - m_workArea)); + monitor, + WorkAreaKey().c_str())); MONITORINFO monitorInfo{}; monitorInfo.cbSize = sizeof(monitorInfo); - if (GetMonitorInfoW(m_monitor, &monitorInfo)) + if (GetMonitorInfoW(monitor, &monitorInfo)) { bool showSpacing = deviceInfoData->showSpacing; int spacing = showSpacing ? deviceInfoData->spacing : 0; @@ -600,30 +715,37 @@ void ZoneWindow::CalculateZoneSet() noexcept void ZoneWindow::UpdateActiveZoneSet(_In_opt_ IZoneSet* zoneSet) noexcept { - m_activeZoneSet.copy_from(zoneSet); + { + std::unique_lock writeLock(m_mutex); + m_activeZoneSet.copy_from(zoneSet); + } - if (m_activeZoneSet) + if (zoneSet) { wil::unique_cotaskmem_string zoneSetId; - if (SUCCEEDED_LOG(StringFromCLSID(m_activeZoneSet->Id(), &zoneSetId))) + if (SUCCEEDED_LOG(StringFromCLSID(zoneSet->Id(), &zoneSetId))) { JSONHelpers::ZoneSetData data{ .uuid = zoneSetId.get(), - .type = m_activeZoneSet->LayoutType() + .type = zoneSet->LayoutType() }; - JSONHelpers::FancyZonesDataInstance().SetActiveZoneSet(m_uniqueId, data); + JSONHelpers::FancyZonesDataInstance().SetActiveZoneSet(UniqueId(), data); } } } LRESULT ZoneWindow::WndProc(UINT message, WPARAM wparam, LPARAM lparam) noexcept { + std::shared_lock lock(m_mutex); + auto window = m_window.get(); + lock.unlock(); + switch (message) { case WM_NCDESTROY: { - ::DefWindowProc(m_window.get(), message, wparam, lparam); - SetWindowLongPtr(m_window.get(), GWLP_USERDATA, 0); + ::DefWindowProc(window, message, wparam, lparam); + SetWindowLongPtr(window, GWLP_USERDATA, 0); } break; @@ -637,14 +759,14 @@ LRESULT ZoneWindow::WndProc(UINT message, WPARAM wparam, LPARAM lparam) noexcept wil::unique_hdc hdc{ reinterpret_cast(wparam) }; if (!hdc) { - hdc.reset(BeginPaint(m_window.get(), &ps)); + hdc.reset(BeginPaint(window, &ps)); } OnPaint(hdc); if (wparam == 0) { - EndPaint(m_window.get(), &ps); + EndPaint(window, &ps); } hdc.release(); @@ -653,7 +775,7 @@ LRESULT ZoneWindow::WndProc(UINT message, WPARAM wparam, LPARAM lparam) noexcept default: { - return DefWindowProc(m_window.get(), message, wparam, lparam); + return DefWindowProc(window, message, wparam, lparam); } } return 0; @@ -661,8 +783,17 @@ LRESULT ZoneWindow::WndProc(UINT message, WPARAM wparam, LPARAM lparam) noexcept void ZoneWindow::OnPaint(wil::unique_hdc& hdc) noexcept { + std::shared_lock lock(m_mutex); + auto host = m_host; + auto highlightZone = m_highlightZone; + auto flashMode = m_flashMode; + auto drawHints = m_drawHints; + HWND window = m_window.get(); + auto activeZoneSet = m_activeZoneSet; + lock.unlock(); + RECT clientRect; - GetClientRect(m_window.get(), &clientRect); + GetClientRect(window, &clientRect); wil::unique_hdc hdcMem; HPAINTBUFFER bufferedPaint = BeginBufferedPaint(hdc.get(), &clientRect, BPBF_TOPDOWNDIB, nullptr, &hdcMem); @@ -670,17 +801,17 @@ void ZoneWindow::OnPaint(wil::unique_hdc& hdc) noexcept { ZoneWindowDrawUtils::DrawBackdrop(hdcMem, clientRect); - if (m_activeZoneSet && m_host) + if (activeZoneSet && host) { ZoneWindowDrawUtils::DrawActiveZoneSet(hdcMem, - m_host->GetZoneColor(), - m_host->GetZoneBorderColor(), - m_host->GetZoneHighlightColor(), - m_host->GetZoneHighlightOpacity(), - m_activeZoneSet->GetZones(), - m_highlightZone, - m_flashMode, - m_drawHints); + host->GetZoneColor(), + host->GetZoneBorderColor(), + host->GetZoneHighlightColor(), + host->GetZoneHighlightOpacity(), + activeZoneSet->GetZones(), + highlightZone, + flashMode, + drawHints); } EndBufferedPaint(bufferedPaint, TRUE); @@ -689,43 +820,56 @@ void ZoneWindow::OnPaint(wil::unique_hdc& hdc) noexcept void ZoneWindow::OnKeyUp(WPARAM wparam) noexcept { + std::shared_lock lock(m_mutex); + auto window = m_window.get(); + lock.unlock(); + bool fRedraw = false; Trace::ZoneWindow::KeyUp(wparam); if ((wparam >= '0') && (wparam <= '9')) { CycleActiveZoneSetInternal(static_cast(wparam), Trace::ZoneWindow::InputMode::Keyboard); - InvalidateRect(m_window.get(), nullptr, true); + InvalidateRect(window, nullptr, true); } } std::vector ZoneWindow::ZonesFromPoint(POINT pt) noexcept { - if (m_activeZoneSet) + auto activeZoneSet = ActiveZoneSet(); + if (activeZoneSet) { - return m_activeZoneSet->ZonesFromPoint(pt); + return activeZoneSet->ZonesFromPoint(pt); } return {}; } void ZoneWindow::CycleActiveZoneSetInternal(DWORD wparam, Trace::ZoneWindow::InputMode mode) noexcept { - Trace::ZoneWindow::CycleActiveZoneSet(m_activeZoneSet, mode); - if (m_keyLast != wparam) + std::shared_lock lock(m_mutex); + auto activeZoneSet = m_activeZoneSet; + auto keyLast = m_keyLast; + auto keyCycle = m_keyCycle; + auto zoneSets = m_zoneSets; + auto host = m_host; + lock.unlock(); + + Trace::ZoneWindow::CycleActiveZoneSet(activeZoneSet, mode); + if (keyLast != wparam) { - m_keyCycle = 0; + keyCycle = 0; } - m_keyLast = wparam; + keyLast = wparam; bool loopAround = true; size_t const val = static_cast(wparam - L'0'); size_t i = 0; - for (auto zoneSet : m_zoneSets) + for (auto zoneSet : zoneSets) { if (zoneSet->GetZones().size() == val) { - if (i < m_keyCycle) + if (i < keyCycle) { i++; } @@ -738,21 +882,25 @@ void ZoneWindow::CycleActiveZoneSetInternal(DWORD wparam, Trace::ZoneWindow::Inp } } - if ((m_keyCycle > 0) && loopAround) + if ((keyCycle > 0) && loopAround) { // Cycling through a non-empty group and hit the end - m_keyCycle = 0; + keyCycle = 0; OnKeyUp(wparam); } else { - m_keyCycle++; + keyCycle++; } - if (m_host) + if (host) { - m_host->MoveWindowsOnActiveZoneSetChange(); + host->MoveWindowsOnActiveZoneSetChange(); } + + std::unique_lock writeLock(m_mutex); + m_keyLast = keyLast; + m_keyCycle = keyCycle; m_highlightZone = {}; } @@ -764,10 +912,13 @@ void ZoneWindow::FlashZones() noexcept return; } + std::unique_lock writeLock(m_mutex); m_flashMode = true; + auto window = m_window.get(); + writeLock.unlock(); - ShowWindow(m_window.get(), SW_SHOWNA); - std::thread([window = m_window.get()]() { + ShowWindow(window, SW_SHOWNA); + std::thread([window]() { AnimateWindow(window, m_flashDuration, AW_HIDE | AW_BLEND); }).detach(); } diff --git a/src/tests/win-app-driver/FancyZonesTests/EditorGridZoneResizeTests.cs b/src/tests/win-app-driver/FancyZonesTests/EditorGridZoneResizeTests.cs index cbec624d4d..79f6287853 100644 --- a/src/tests/win-app-driver/FancyZonesTests/EditorGridZoneResizeTests.cs +++ b/src/tests/win-app-driver/FancyZonesTests/EditorGridZoneResizeTests.cs @@ -1,4 +1,4 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium.Appium; using OpenQA.Selenium.Appium.Windows; using OpenQA.Selenium.Interactions; @@ -161,23 +161,67 @@ namespace PowerToysTests public void CreateSplitter() { OpenCreatorWindow("Columns", "Custom table layout creator", "EditTemplateButton"); - WindowsElement gridEditor = session.FindElementByClassName("GridEditor"); - Assert.IsNotNull(gridEditor); - - ReadOnlyCollection thumbs = gridEditor.FindElementsByClassName("Thumb"); - Assert.AreEqual(3, session.FindElementsByClassName("GridZone").Count); - Assert.AreEqual(2, thumbs.Count); - - new Actions(session).MoveToElement(thumbs[0]).MoveByOffset(-30, 0).Click().Perform(); - Assert.AreEqual(3, gridEditor.FindElementsByClassName("Thumb").Count); + WaitSeconds(2); ReadOnlyCollection zones = session.FindElementsByClassName("GridZone"); + Assert.AreEqual(3, zones.Count, "Zones count invalid"); + + const int defaultSpacing = 16; + int splitPos = zones[0].Rect.Y + zones[0].Rect.Height / 2; + + new Actions(session).MoveToElement(zones[0]).Click().Perform(); + + zones = session.FindElementsByClassName("GridZone"); Assert.AreEqual(4, zones.Count); - //check that zone was splitted horizontally - Assert.AreNotEqual(zones[0].Rect.Height, zones[1].Rect.Height); - Assert.AreNotEqual(zones[3].Rect.Height, zones[1].Rect.Height); - Assert.AreEqual(zones[1].Rect.Height, zones[2].Rect.Height); + //check splitted zone + Assert.AreEqual(zones[0].Rect.Top, defaultSpacing); + Assert.IsTrue(Math.Abs(zones[0].Rect.Bottom - splitPos + defaultSpacing / 2) <= 2); + Assert.IsTrue(Math.Abs(zones[3].Rect.Top - splitPos - defaultSpacing / 2) <= 2); + Assert.AreEqual(zones[3].Rect.Bottom, Screen.PrimaryScreen.Bounds.Bottom - defaultSpacing); + } + + [TestMethod] + public void TestSplitterShiftAfterCreation() + { + OpenCreatorWindow("Columns", "Custom table layout creator", "EditTemplateButton"); + WaitSeconds(2); + + ReadOnlyCollection zones = session.FindElementsByClassName("GridZone"); + Assert.AreEqual(3, zones.Count, "Zones count invalid"); + + const int defaultSpacing = 16; + + //create first split + int firstSplitPos = zones[0].Rect.Y + zones[0].Rect.Height / 4; + new Actions(session).MoveToElement(zones[0]).MoveByOffset(0, -(zones[0].Rect.Height / 4)).Click().Perform(); + + zones = session.FindElementsByClassName("GridZone"); + Assert.AreEqual(4, zones.Count); + + Assert.AreEqual(zones[0].Rect.Top, defaultSpacing); + Assert.IsTrue(Math.Abs(zones[0].Rect.Bottom - firstSplitPos + defaultSpacing / 2) <= 2); + Assert.IsTrue(Math.Abs(zones[3].Rect.Top - firstSplitPos - defaultSpacing / 2) <= 2); + Assert.AreEqual(zones[3].Rect.Bottom, Screen.PrimaryScreen.Bounds.Bottom - defaultSpacing); + + //create second split + int secondSplitPos = zones[3].Rect.Y + zones[3].Rect.Height / 2; + int expectedTop = zones[3].Rect.Top; + + new Actions(session).MoveToElement(zones[3]).Click().Perform(); + + zones = session.FindElementsByClassName("GridZone"); + Assert.AreEqual(5, zones.Count); + + //check first split on same position + Assert.AreEqual(zones[0].Rect.Top, defaultSpacing); + Assert.IsTrue(Math.Abs(zones[0].Rect.Bottom - firstSplitPos + defaultSpacing / 2) <= 2); + + //check second split + Assert.AreEqual(zones[3].Rect.Top, expectedTop); + Assert.IsTrue(Math.Abs(zones[3].Rect.Bottom - secondSplitPos + defaultSpacing / 2) <= 2); + Assert.IsTrue(Math.Abs(zones[4].Rect.Top - secondSplitPos - defaultSpacing / 2) <= 2); + Assert.AreEqual(zones[4].Rect.Bottom, Screen.PrimaryScreen.Bounds.Bottom - defaultSpacing); } [TestMethod] diff --git a/src/tests/win-app-driver/FancyZonesTests/FancyZonesEditor.cs b/src/tests/win-app-driver/FancyZonesTests/FancyZonesEditor.cs index ba98f1a991..beb8dd3694 100644 --- a/src/tests/win-app-driver/FancyZonesTests/FancyZonesEditor.cs +++ b/src/tests/win-app-driver/FancyZonesTests/FancyZonesEditor.cs @@ -17,9 +17,11 @@ namespace PowerToysTests protected static void OpenEditor() { new Actions(session).KeyDown(OpenQA.Selenium.Keys.Command).SendKeys("`").KeyUp(OpenQA.Selenium.Keys.Command).Perform(); + WaitSeconds(2); //editorWindow = WaitElementByXPath("//Window[@Name=\"FancyZones Editor\"]"); + editorWindow = WaitElementByName("FancyZones Editor"); //may not find editor by name in 0.16.1 - editorWindow = WaitElementByAccessibilityId("MainWindow1"); + //editorWindow = WaitElementByAccessibilityId("MainWindow1"); Assert.IsNotNull(editorWindow, "Couldn't find editor window"); } @@ -57,10 +59,10 @@ namespace PowerToysTests protected static void OpenCreatorWindow(string tabName, string creatorWindowName, string buttonId = "EditCustomButton") { string elementXPath = "//Text[@Name=\"" + tabName + "\"]"; - session.FindElementByXPath(elementXPath).Click(); - session.FindElementByAccessibilityId(buttonId).Click(); + WaitElementByXPath(elementXPath).Click(); + WaitElementByAccessibilityId(buttonId).Click(); - WindowsElement creatorWindow = session.FindElementByName(creatorWindowName); + WindowsElement creatorWindow = WaitElementByName(creatorWindowName); Assert.IsNotNull(creatorWindow, "Creator window didn't open"); }