diff --git a/installer/PowerToysSetup/Product.wxs b/installer/PowerToysSetup/Product.wxs index f7ff725dd7..df8679462e 100644 --- a/installer/PowerToysSetup/Product.wxs +++ b/installer/PowerToysSetup/Product.wxs @@ -248,11 +248,9 @@ - - - + - + @@ -269,8 +267,7 @@ @@ -290,7 +287,7 @@ - + diff --git a/src/common/monitors.cpp b/src/common/monitors.cpp index e3b4f766d8..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,43 +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; } -static BOOL CALLBACK get_primary_display_enum_cb(HMONITOR monitor, HDC hdc, LPRECT rect, LPARAM data) +static BOOL CALLBACK GetPrimaryDisplayEnumCb(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) + MONITORINFOEX monitorInfo; + monitorInfo.cbSize = sizeof(MONITORINFOEX); + + 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; }; @@ -54,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 616656e737..b375fedd52 100644 --- a/src/common/monitors.h +++ b/src/common/monitors.h @@ -31,15 +31,8 @@ struct MonitorInfo : ScreenSize HMONITOR handle; // Returns monitor rects ordered from left to right - static std::vector GetMonitors(bool include_toolbar); - // 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 ad6207e7e1..620dbae9f5 100644 --- a/src/modules/fancyzones/lib/Zone.cpp +++ b/src/modules/fancyzones/lib/Zone.cpp @@ -1,11 +1,16 @@ #include "pch.h" + +#include + #include #include #include "Zone.h" #include "Settings.h" #include "util.h" +#include "common/monitors.h" + struct Zone : winrt::implements { public: @@ -66,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 @@ -78,14 +122,15 @@ RECT Zone::ComputeActualZoneRect(HWND window, HWND zoneWindow) noexcept const auto level = DPIAware::GetAwarenessLevel(GetWindowDpiAwarenessContext(window)); const bool accountForUnawareness = level < DPIAware::PER_MONITOR_AWARE; + if (SUCCEEDED(DwmGetWindowAttribute(window, DWMWA_EXTENDED_FRAME_BOUNDS, &frameRect, sizeof(frameRect)))) { - const auto left_margin = frameRect.left - windowRect.left; - const auto right_margin = frameRect.right - windowRect.right; - const auto bottom_margin = frameRect.bottom - windowRect.bottom; - newWindowRect.left -= left_margin; - newWindowRect.right -= right_margin; - newWindowRect.bottom -= bottom_margin; + LONG leftMargin = frameRect.left - windowRect.left; + LONG rightMargin = frameRect.right - windowRect.right; + LONG bottomMargin = frameRect.bottom - windowRect.bottom; + newWindowRect.left -= leftMargin; + newWindowRect.right -= rightMargin; + newWindowRect.bottom -= bottomMargin; } // Map to screen coords @@ -97,7 +142,8 @@ RECT Zone::ComputeActualZoneRect(HWND window, HWND zoneWindow) noexcept const auto taskbar_left_size = std::abs(mi.rcMonitor.left - mi.rcWork.left); const auto taskbar_top_size = std::abs(mi.rcMonitor.top - mi.rcWork.top); OffsetRect(&newWindowRect, -taskbar_left_size, -taskbar_top_size); - if (accountForUnawareness) + + 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/modules/powerrename/dll/dllmain.cpp b/src/modules/powerrename/dll/dllmain.cpp index a952629ca1..2629137635 100644 --- a/src/modules/powerrename/dll/dllmain.cpp +++ b/src/modules/powerrename/dll/dllmain.cpp @@ -250,7 +250,7 @@ public: CSettingsInstance().SetMaxMRUSize(values.get_int_value(L"int_max_mru_size").value()); CSettingsInstance().SetShowIconOnMenu(values.get_bool_value(L"bool_show_icon_on_menu").value()); CSettingsInstance().SetExtendedContextMenuOnly(values.get_bool_value(L"bool_show_extended_menu").value()); - CSettingsInstance().SavePowerRenameData(); + CSettingsInstance().Save(); Trace::SettingsChanged(); } @@ -283,7 +283,6 @@ public: void init_settings() { - CSettingsInstance().LoadPowerRenameData(); m_enabled = CSettingsInstance().GetEnabled(); Trace::EnablePowerRename(m_enabled); } @@ -291,7 +290,7 @@ public: void save_settings() { CSettingsInstance().SetEnabled(m_enabled); - CSettingsInstance().SavePowerRenameData(); + CSettingsInstance().Save(); Trace::EnablePowerRename(m_enabled); } diff --git a/src/modules/powerrename/lib/Settings.cpp b/src/modules/powerrename/lib/Settings.cpp index 33d223cc7d..a7f20dde0c 100644 --- a/src/modules/powerrename/lib/Settings.cpp +++ b/src/modules/powerrename/lib/Settings.cpp @@ -5,14 +5,17 @@ #include #include +#include namespace { - const wchar_t c_powerRenameDataFilePath[] = L"power-rename-settings.json"; + const wchar_t c_powerRenameDataFilePath[] = L"\\power-rename-settings.json"; + const wchar_t c_searchMRUListFilePath[] = L"\\search-mru.json"; + const wchar_t c_replaceMRUListFilePath[] = L"\\replace-mru.json"; const wchar_t c_rootRegPath[] = L"Software\\Microsoft\\PowerRename"; - const wchar_t c_mruSearchRegPath[] = L"SearchMRU"; - const wchar_t c_mruReplaceRegPath[] = L"ReplaceMRU"; + const wchar_t c_mruSearchRegPath[] = L"\\SearchMRU"; + const wchar_t c_mruReplaceRegPath[] = L"\\ReplaceMRU"; const wchar_t c_enabled[] = L"Enabled"; const wchar_t c_showIconOnMenu[] = L"ShowIcon"; @@ -23,6 +26,8 @@ namespace const wchar_t c_searchText[] = L"SearchText"; const wchar_t c_replaceText[] = L"ReplaceText"; const wchar_t c_mruEnabled[] = L"MRUEnabled"; + const wchar_t c_mruList[] = L"MRUList"; + const wchar_t c_insertionIdx[] = L"InsertionIdx"; long GetRegNumber(const std::wstring& valueName, long defaultValue) { @@ -52,34 +57,218 @@ namespace SetRegNumber(valueName, value ? 1 : 0); } - std::wstring GetRegString(const std::wstring& valueName) { + std::wstring GetRegString(const std::wstring& valueName,const std::wstring& subPath) + { wchar_t value[CSettings::MAX_INPUT_STRING_LEN]; value[0] = L'\0'; DWORD type = REG_SZ; DWORD size = CSettings::MAX_INPUT_STRING_LEN * sizeof(wchar_t); - if (SUCCEEDED(HRESULT_FROM_WIN32(SHGetValue(HKEY_CURRENT_USER, c_rootRegPath, valueName.c_str(), &type, value, &size) == ERROR_SUCCESS))) + std::wstring completePath = std::wstring(c_rootRegPath) + subPath; + if (SHGetValue(HKEY_CURRENT_USER, completePath.c_str(), valueName.c_str(), &type, value, &size) == ERROR_SUCCESS) { return std::wstring(value); } return std::wstring{}; } + + bool LastModifiedTime(const std::wstring& filePath, FILETIME* lpFileTime) + { + WIN32_FILE_ATTRIBUTE_DATA attr{}; + if (GetFileAttributesExW(filePath.c_str(), GetFileExInfoStandard, &attr)) + { + *lpFileTime = attr.ftLastWriteTime; + return true; + } + return false; + } } -typedef int (CALLBACK* MRUCMPPROC)(LPCWSTR, LPCWSTR); +class MRUListHandler +{ +public: + MRUListHandler(int size, const std::wstring& filePath, const std::wstring& regPath) : + pushIdx(0), + nextIdx(1), + size(size), + jsonFilePath(PTSettingsHelper::get_module_save_folder_location(L"PowerRename") + filePath), + registryFilePath(regPath) + { + items.resize(size); + Load(); + } -typedef struct { - DWORD cbSize; - UINT uMax; - UINT fFlags; - HKEY hKey; - LPCTSTR lpszSubKey; - MRUCMPPROC lpfnCompare; -} MRUINFO; + void Push(const std::wstring& data); + bool Next(std::wstring& data); -typedef HANDLE (*CreateMRUListFn)(MRUINFO* pmi); -typedef int (*AddMRUStringFn)(HANDLE hMRU, LPCWSTR data); -typedef int (*EnumMRUListFn)(HANDLE hMRU, int nItem, void* lpData, UINT uLen); -typedef int (*FreeMRUListFn)(HANDLE hMRU); + void Reset(); + +private: + void Load(); + void Save(); + void MigrateFromRegistry(); + json::JsonArray Serialize(); + void ParseJson(); + + bool Exists(const std::wstring& data); + + std::vector items; + long pushIdx; + long nextIdx; + long size; + const std::wstring jsonFilePath; + const std::wstring registryFilePath; +}; + + +void MRUListHandler::Push(const std::wstring& data) +{ + if (Exists(data)) + { + // TODO: Already existing item should be put on top of MRU list. + return; + } + items[pushIdx] = data; + pushIdx = (pushIdx + 1) % size; + Save(); +} + +bool MRUListHandler::Next(std::wstring& data) +{ + if (nextIdx == size + 1) + { + Reset(); + return false; + } + // Go backwards to consume latest items first. + long idx = (pushIdx + size - nextIdx) % size; + if (items[idx].empty()) + { + Reset(); + return false; + } + data = items[idx]; + ++nextIdx; + return true; +} + +void MRUListHandler::Reset() +{ + nextIdx = 1; +} + +void MRUListHandler::Load() +{ + if (!std::filesystem::exists(jsonFilePath)) + { + MigrateFromRegistry(); + + Save(); + } + else + { + ParseJson(); + } +} + +void MRUListHandler::Save() +{ + json::JsonObject jsonData; + + jsonData.SetNamedValue(c_maxMRUSize, json::value(size)); + jsonData.SetNamedValue(c_insertionIdx, json::value(pushIdx)); + jsonData.SetNamedValue(c_mruList, Serialize()); + + json::to_file(jsonFilePath, jsonData); +} + +json::JsonArray MRUListHandler::Serialize() +{ + json::JsonArray searchMRU{}; + + std::wstring data{}; + for (const std::wstring& item : items) + { + searchMRU.Append(json::value(item)); + } + + return searchMRU; +} + +void MRUListHandler::MigrateFromRegistry() +{ + std::wstring searchListKeys = GetRegString(c_mruList, registryFilePath); + std::sort(std::begin(searchListKeys), std::end(searchListKeys)); + for (const wchar_t& key : searchListKeys) + { + Push(GetRegString(std::wstring(1, key), registryFilePath)); + } +} + +void MRUListHandler::ParseJson() +{ + auto json = json::from_file(jsonFilePath); + if (json) + { + const json::JsonObject& jsonObject = json.value(); + try + { + long oldSize{ size }; + if (json::has(jsonObject, c_maxMRUSize, json::JsonValueType::Number)) + { + oldSize = (long)jsonObject.GetNamedNumber(c_maxMRUSize); + } + long oldPushIdx{ 0 }; + if (json::has(jsonObject, c_insertionIdx, json::JsonValueType::Number)) + { + oldPushIdx = (long)jsonObject.GetNamedNumber(c_insertionIdx); + if (oldPushIdx < 0 || oldPushIdx >= oldSize) + { + oldPushIdx = 0; + } + } + if (json::has(jsonObject, c_mruList, json::JsonValueType::Array)) + { + auto jsonArray = jsonObject.GetNamedArray(c_mruList); + if (oldSize == size) + { + for (uint32_t i = 0; i < jsonArray.Size(); ++i) + { + items[i] = std::wstring(jsonArray.GetStringAt(i)); + } + pushIdx = oldPushIdx; + } + else + { + std::vector temp; + for (uint32_t i = 0; i < min(jsonArray.Size(), size); ++i) + { + int idx = (oldPushIdx + oldSize - (i + 1)) % oldSize; + temp.push_back(std::wstring(jsonArray.GetStringAt(idx))); + } + if (size > oldSize) + { + std::reverse(std::begin(temp), std::end(temp)); + pushIdx = (long)temp.size(); + temp.resize(size); + } + else + { + temp.resize(size); + std::reverse(std::begin(temp), std::end(temp)); + } + items = std::move(temp); + Save(); + } + } + } + catch (const winrt::hresult_error&) { } + } +} + +bool MRUListHandler::Exists(const std::wstring& data) +{ + return std::find(std::begin(items), std::end(items), data) != std::end(items); +} class CRenameMRU : public IEnumString, @@ -100,65 +289,33 @@ public: // IPowerRenameMRU IFACEMETHODIMP AddMRUString(_In_ PCWSTR entry); - static HRESULT CreateInstance(_In_ PCWSTR regPathMRU, _In_ ULONG maxMRUSize, _Outptr_ IUnknown** ppUnk); + static HRESULT CreateInstance(_In_ const std::wstring& filePath, _In_ const std::wstring& regPath, _Outptr_ IUnknown** ppUnk); private: - CRenameMRU(); - ~CRenameMRU(); + CRenameMRU(int size, const std::wstring& filePath, const std::wstring& regPath); - HRESULT _Initialize(_In_ PCWSTR regPathMRU, __in ULONG maxMRUSize); - HRESULT _CreateMRUList(_In_ MRUINFO* pmi); - int _AddMRUString(_In_ PCWSTR data); - int _EnumMRUList(_In_ int nItem, _Out_ void* lpData, _In_ UINT uLen); - void _FreeMRUList(); - - long m_refCount = 0; - HKEY m_hKey = NULL; - ULONG m_maxMRUSize = 0; - ULONG m_mruIndex = 0; - ULONG m_mruSize = 0; - HANDLE m_mruHandle = NULL; - HMODULE m_hComctl32Dll = NULL; - PWSTR m_regPath = nullptr; + std::unique_ptr mruList; + long refCount = 0; }; -CRenameMRU::CRenameMRU() : - m_refCount(1) -{} - -CRenameMRU::~CRenameMRU() +CRenameMRU::CRenameMRU(int size, const std::wstring& filePath, const std::wstring& regPath) : + refCount(1) { - if (m_hKey) - { - RegCloseKey(m_hKey); - } - - _FreeMRUList(); - - if (m_hComctl32Dll) - { - FreeLibrary(m_hComctl32Dll); - } - - CoTaskMemFree(m_regPath); + mruList = std::make_unique(size, filePath, regPath); } -HRESULT CRenameMRU::CreateInstance(_In_ PCWSTR regPathMRU, _In_ ULONG maxMRUSize, _Outptr_ IUnknown** ppUnk) +HRESULT CRenameMRU::CreateInstance(_In_ const std::wstring& filePath, _In_ const std::wstring& regPath, _Outptr_ IUnknown** ppUnk) { *ppUnk = nullptr; - HRESULT hr = (regPathMRU && maxMRUSize > 0) ? S_OK : E_FAIL; + long maxMRUSize = CSettingsInstance().GetMaxMRUSize(); + HRESULT hr = maxMRUSize > 0 ? S_OK : E_FAIL; if (SUCCEEDED(hr)) { - CRenameMRU* renameMRU = new CRenameMRU(); + CRenameMRU* renameMRU = new CRenameMRU(maxMRUSize, filePath, regPath); hr = renameMRU ? S_OK : E_OUTOFMEMORY; if (SUCCEEDED(hr)) { - hr = renameMRU->_Initialize(regPathMRU, maxMRUSize); - if (SUCCEEDED(hr)) - { - hr = renameMRU->QueryInterface(IID_PPV_ARGS(ppUnk)); - } - + renameMRU->QueryInterface(IID_PPV_ARGS(ppUnk)); renameMRU->Release(); } } @@ -166,21 +323,20 @@ HRESULT CRenameMRU::CreateInstance(_In_ PCWSTR regPathMRU, _In_ ULONG maxMRUSize return hr; } -// IUnknown IFACEMETHODIMP_(ULONG) CRenameMRU::AddRef() { - return InterlockedIncrement(&m_refCount); + return InterlockedIncrement(&refCount); } IFACEMETHODIMP_(ULONG) CRenameMRU::Release() { - long refCount = InterlockedDecrement(&m_refCount); + long cnt = InterlockedDecrement(&refCount); - if (refCount == 0) + if (cnt == 0) { delete this; } - return refCount; + return cnt; } IFACEMETHODIMP CRenameMRU::QueryInterface(_In_ REFIID riid, _Outptr_ void** ppv) @@ -193,57 +349,8 @@ IFACEMETHODIMP CRenameMRU::QueryInterface(_In_ REFIID riid, _Outptr_ void** ppv) return QISearch(this, qit, riid, ppv); } -HRESULT CRenameMRU::_Initialize(_In_ PCWSTR regPathMRU, __in ULONG maxMRUSize) -{ - m_maxMRUSize = maxMRUSize; - - wchar_t regPath[MAX_PATH] = { 0 }; - HRESULT hr = StringCchPrintf(regPath, ARRAYSIZE(regPath), L"%s\\%s", c_rootRegPath, regPathMRU); - if (SUCCEEDED(hr)) - { - hr = SHStrDup(regPathMRU, &m_regPath); - - if (SUCCEEDED(hr)) - { - MRUINFO mi = { - sizeof(MRUINFO), - maxMRUSize, - 0, - HKEY_CURRENT_USER, - regPath, - nullptr - }; - - hr = _CreateMRUList(&mi); - if (SUCCEEDED(hr)) - { - m_mruSize = _EnumMRUList(-1, NULL, 0); - } - else - { - hr = E_FAIL; - } - } - } - - return hr; -} - -// IEnumString -IFACEMETHODIMP CRenameMRU::Reset() -{ - m_mruIndex = 0; - return S_OK; -} - -#define MAX_ENTRY_STRING 1024 - IFACEMETHODIMP CRenameMRU::Next(__in ULONG celt, __out_ecount_part(celt, *pceltFetched) LPOLESTR* rgelt, __out_opt ULONG* pceltFetched) { - HRESULT hr = S_OK; - WCHAR mruEntry[MAX_ENTRY_STRING]; - mruEntry[0] = L'\0'; - if (pceltFetched) { *pceltFetched = 0; @@ -259,10 +366,10 @@ IFACEMETHODIMP CRenameMRU::Next(__in ULONG celt, __out_ecount_part(celt, *pceltF return S_FALSE; } - hr = S_FALSE; - if (m_mruIndex <= m_mruSize && _EnumMRUList(m_mruIndex++, (void*)mruEntry, ARRAYSIZE(mruEntry)) > 0) + HRESULT hr = S_FALSE; + if (std::wstring data{}; mruList->Next(data)) { - hr = SHStrDup(mruEntry, rgelt); + hr = SHStrDup(data.c_str(), rgelt); if (SUCCEEDED(hr) && pceltFetched != nullptr) { *pceltFetched = 1; @@ -272,137 +379,30 @@ IFACEMETHODIMP CRenameMRU::Next(__in ULONG celt, __out_ecount_part(celt, *pceltF return hr; } +IFACEMETHODIMP CRenameMRU::Reset() +{ + mruList->Reset(); + return S_OK; +} + IFACEMETHODIMP CRenameMRU::AddMRUString(_In_ PCWSTR entry) { - return (_AddMRUString(entry) < 0) ? E_FAIL : S_OK; -} - -HRESULT CRenameMRU::_CreateMRUList(_In_ MRUINFO* pmi) -{ - if (m_mruHandle != NULL) - { - _FreeMRUList(); - } - - if (m_hComctl32Dll == NULL) - { - m_hComctl32Dll = LoadLibraryEx(L"comctl32.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - } - - if (m_hComctl32Dll != nullptr) - { - CreateMRUListFn pfnCreateMRUList = reinterpret_cast(GetProcAddress(m_hComctl32Dll, (LPCSTR)MAKEINTRESOURCE(400))); - if (pfnCreateMRUList != nullptr) - { - m_mruHandle = pfnCreateMRUList(pmi); - } - } - - return (m_mruHandle != NULL) ? S_OK : E_FAIL; -} - -int CRenameMRU::_AddMRUString(_In_ PCWSTR data) -{ - int retVal = -1; - if (m_mruHandle != NULL) - { - if (m_hComctl32Dll == NULL) - { - m_hComctl32Dll = LoadLibraryEx(L"comctl32.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - } - - if (m_hComctl32Dll != nullptr) - { - AddMRUStringFn pfnAddMRUString = reinterpret_cast(GetProcAddress(m_hComctl32Dll, (LPCSTR)MAKEINTRESOURCE(401))); - if (pfnAddMRUString != nullptr) - { - retVal = pfnAddMRUString(m_mruHandle, data); - } - } - } - - return retVal; -} - -int CRenameMRU::_EnumMRUList(_In_ int nItem, _Out_ void* lpData, _In_ UINT uLen) -{ - int retVal = -1; - if (m_mruHandle != NULL) - { - if (m_hComctl32Dll == NULL) - { - m_hComctl32Dll = LoadLibraryEx(L"comctl32.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - } - - if (m_hComctl32Dll != nullptr) - { - EnumMRUListFn pfnEnumMRUList = reinterpret_cast(GetProcAddress(m_hComctl32Dll, (LPCSTR)MAKEINTRESOURCE(403))); - if (pfnEnumMRUList != nullptr) - { - retVal = pfnEnumMRUList(m_mruHandle, nItem, lpData, uLen); - } - } - } - - return retVal; -} - -void CRenameMRU::_FreeMRUList() -{ - if (m_mruHandle != NULL) - { - if (m_hComctl32Dll == NULL) - { - m_hComctl32Dll = LoadLibraryEx(L"comctl32.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); - } - - if (m_hComctl32Dll != nullptr) - { - FreeMRUListFn pfnFreeMRUList = reinterpret_cast(GetProcAddress(m_hComctl32Dll, (LPCSTR)MAKEINTRESOURCE(152))); - if (pfnFreeMRUList != nullptr) - { - pfnFreeMRUList(m_mruHandle); - } - - } - m_mruHandle = NULL; - } + mruList->Push(entry); + return S_OK; } CSettings::CSettings() { std::wstring result = PTSettingsHelper::get_module_save_folder_location(L"PowerRename"); - jsonFilePath = result + L"\\" + std::wstring(c_powerRenameDataFilePath); + jsonFilePath = result + std::wstring(c_powerRenameDataFilePath); + Load(); } -bool CSettings::GetEnabled() -{ - return GetRegBoolean(c_enabled, true); -} - -void CSettings::SetEnabled(bool enabled) -{ - SetRegBoolean(c_enabled, enabled); -} - -void CSettings::LoadPowerRenameData() -{ - if (!std::filesystem::exists(jsonFilePath)) - { - MigrateSettingsFromRegistry(); - - SavePowerRenameData(); - } - else - { - ParseJsonSettings(); - } -} - -void CSettings::SavePowerRenameData() const +void CSettings::Save() { json::JsonObject jsonData; + jsonData.SetNamedValue(c_enabled, json::value(settings.enabled)); jsonData.SetNamedValue(c_showIconOnMenu, json::value(settings.showIconOnMenu)); jsonData.SetNamedValue(c_extendedContextMenuOnly, json::value(settings.extendedContextMenuOnly)); jsonData.SetNamedValue(c_persistState, json::value(settings.persistState)); @@ -415,19 +415,47 @@ void CSettings::SavePowerRenameData() const json::to_file(jsonFilePath, jsonData); } -void CSettings::MigrateSettingsFromRegistry() +void CSettings::Load() { + if (!std::filesystem::exists(jsonFilePath)) + { + MigrateFromRegistry(); + + Save(); + } + else + { + ParseJson(); + } + GetSystemTimeAsFileTime(&lastLoadedTime); +} + +void CSettings::Reload() +{ + // Load json settings from data file if it is modified in the meantime. + FILETIME lastModifiedTime{}; + if (LastModifiedTime(jsonFilePath, &lastModifiedTime) && + CompareFileTime(&lastModifiedTime, &lastLoadedTime) == 1) + { + Load(); + } +} + + +void CSettings::MigrateFromRegistry() +{ + settings.enabled = GetRegBoolean(c_enabled, true); settings.showIconOnMenu = GetRegBoolean(c_showIconOnMenu, true); settings.extendedContextMenuOnly = GetRegBoolean(c_extendedContextMenuOnly, false); // Disabled by default. settings.persistState = GetRegBoolean(c_persistState, true); settings.MRUEnabled = GetRegBoolean(c_mruEnabled, true); settings.maxMRUSize = GetRegNumber(c_maxMRUSize, 10); settings.flags = GetRegNumber(c_flags, 0); - settings.searchText = GetRegString(c_searchText); - settings.replaceText = GetRegString(c_replaceText); + settings.searchText = GetRegString(c_searchText, L""); + settings.replaceText = GetRegString(c_replaceText, L""); } -void CSettings::ParseJsonSettings() +void CSettings::ParseJson() { auto json = json::from_file(jsonFilePath); if (json) @@ -435,6 +463,10 @@ void CSettings::ParseJsonSettings() const json::JsonObject& jsonSettings = json.value(); try { + if (json::has(jsonSettings, c_enabled, json::JsonValueType::Boolean)) + { + settings.enabled = jsonSettings.GetNamedBoolean(c_enabled); + } if (json::has(jsonSettings, c_showIconOnMenu, json::JsonValueType::Boolean)) { settings.showIconOnMenu = jsonSettings.GetNamedBoolean(c_showIconOnMenu); @@ -480,10 +512,10 @@ CSettings& CSettingsInstance() HRESULT CRenameMRUSearch_CreateInstance(_Outptr_ IUnknown** ppUnk) { - return CRenameMRU::CreateInstance(c_mruSearchRegPath, CSettingsInstance().GetMaxMRUSize(), ppUnk); + return CRenameMRU::CreateInstance(c_searchMRUListFilePath, c_mruSearchRegPath, ppUnk); } HRESULT CRenameMRUReplace_CreateInstance(_Outptr_ IUnknown** ppUnk) { - return CRenameMRU::CreateInstance(c_mruReplaceRegPath, CSettingsInstance().GetMaxMRUSize(), ppUnk); + return CRenameMRU::CreateInstance(c_replaceMRUListFilePath, c_mruReplaceRegPath, ppUnk); } diff --git a/src/modules/powerrename/lib/Settings.h b/src/modules/powerrename/lib/Settings.h index b7e5fa83bf..e82c5c0b65 100644 --- a/src/modules/powerrename/lib/Settings.h +++ b/src/modules/powerrename/lib/Settings.h @@ -2,8 +2,6 @@ #include "json.h" -#include - class CSettings { public: @@ -11,9 +9,17 @@ public: CSettings(); - bool GetEnabled(); + inline bool GetEnabled() + { + Reload(); + return settings.enabled; + } - void SetEnabled(bool enabled); + inline void SetEnabled(bool enabled) + { + settings.enabled = enabled; + Save(); + } inline bool GetShowIconOnMenu() const { @@ -73,6 +79,7 @@ public: inline void SetFlags(long flags) { settings.flags = flags; + Save(); } inline const std::wstring& GetSearchText() const @@ -83,6 +90,7 @@ public: inline void SetSearchText(const std::wstring& text) { settings.searchText = text; + Save(); } inline const std::wstring& GetReplaceText() const @@ -93,14 +101,16 @@ public: inline void SetReplaceText(const std::wstring& text) { settings.replaceText = text; + Save(); } - void LoadPowerRenameData(); - void SavePowerRenameData() const; + void Save(); + void Load(); private: struct Settings { + bool enabled{ true }; bool showIconOnMenu{ true }; bool extendedContextMenuOnly{ false }; // Disabled by default. bool persistState{ true }; @@ -111,11 +121,13 @@ private: std::wstring replaceText{}; }; - void MigrateSettingsFromRegistry(); - void ParseJsonSettings(); + void Reload(); + void MigrateFromRegistry(); + void ParseJson(); Settings settings; std::wstring jsonFilePath; + FILETIME lastLoadedTime; }; CSettings& CSettingsInstance(); diff --git a/src/modules/powerrename/ui/PowerRenameUI.cpp b/src/modules/powerrename/ui/PowerRenameUI.cpp index e43cc9f148..c4bd0b5eaa 100644 --- a/src/modules/powerrename/ui/PowerRenameUI.cpp +++ b/src/modules/powerrename/ui/PowerRenameUI.cpp @@ -5,7 +5,6 @@ #include #include #include -#include #include #include #include @@ -80,6 +79,14 @@ inline int RECT_HEIGHT(RECT& r) return r.bottom - r.top; } +CPowerRenameUI::CPowerRenameUI() : + m_refCount(1) +{ + CSettingsInstance().Load(); + (void)OleInitialize(nullptr); + ModuleAddRef(); +} + // IUnknown IFACEMETHODIMP CPowerRenameUI::QueryInterface(__in REFIID riid, __deref_out void** ppv) { diff --git a/src/modules/powerrename/ui/PowerRenameUI.h b/src/modules/powerrename/ui/PowerRenameUI.h index ec9ef7a091..df46fc6a0a 100644 --- a/src/modules/powerrename/ui/PowerRenameUI.h +++ b/src/modules/powerrename/ui/PowerRenameUI.h @@ -1,5 +1,6 @@ #pragma once #include +#include #include void ModuleAddRef(); @@ -37,12 +38,7 @@ class CPowerRenameUI : public IPowerRenameManagerEvents { public: - CPowerRenameUI() : - m_refCount(1) - { - (void)OleInitialize(nullptr); - ModuleAddRef(); - } + CPowerRenameUI(); // IUnknown IFACEMETHODIMP QueryInterface(__in REFIID riid, __deref_out void** ppv); diff --git a/src/modules/previewpane/MarkdownPreviewHandler/MarkdownPreviewHandlerControl.cs b/src/modules/previewpane/MarkdownPreviewHandler/MarkdownPreviewHandlerControl.cs index f64488125f..ce9d8a443f 100644 --- a/src/modules/previewpane/MarkdownPreviewHandler/MarkdownPreviewHandlerControl.cs +++ b/src/modules/previewpane/MarkdownPreviewHandler/MarkdownPreviewHandlerControl.cs @@ -3,11 +3,8 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics; using System.Drawing; using System.IO; -using System.Linq; -using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using Common; @@ -73,28 +70,29 @@ namespace MarkdownPreviewHandler /// Path to the file. public override void DoPreview(T dataSource) { - this.InvokeOnControlThread(() => + this.infoBarDisplayed = false; + + try { - try + if (!(dataSource is string filePath)) { - this.infoBarDisplayed = false; + throw new ArgumentException($"{nameof(dataSource)} for {nameof(MarkdownPreviewHandler)} must be a string but was a '{typeof(T)}'"); + } - StringBuilder sb = new StringBuilder(); - string filePath = dataSource as string; - string fileText = File.ReadAllText(filePath); - this.extension.BaseUrl = Path.GetDirectoryName(filePath); + string fileText = File.ReadAllText(filePath); + Regex imageTagRegex = new Regex(@"<[ ]*img.*>"); + if (imageTagRegex.IsMatch(fileText)) + { + this.infoBarDisplayed = true; + } - Regex rgx = new Regex(@"<[ ]*img.*>"); - if (rgx.IsMatch(fileText)) - { - this.infoBarDisplayed = true; - } - - MarkdownPipeline pipeline = this.pipelineBuilder.Build(); - string parsedMarkdown = Markdown.ToHtml(fileText, pipeline); - sb.AppendFormat("{0}{1}{2}", this.htmlHeader, parsedMarkdown, this.htmlFooter); - string markdownHTML = sb.ToString(); + this.extension.BaseUrl = Path.GetDirectoryName(filePath); + MarkdownPipeline pipeline = this.pipelineBuilder.Build(); + string parsedMarkdown = Markdown.ToHtml(fileText, pipeline); + string markdownHTML = $"{this.htmlHeader}{parsedMarkdown}{this.htmlFooter}"; + this.InvokeOnControlThread(() => + { this.browser = new WebBrowserExt { DocumentText = markdownHTML, @@ -109,24 +107,30 @@ namespace MarkdownPreviewHandler if (this.infoBarDisplayed) { this.infoBar = this.GetTextBoxControl(Resources.BlockedImageInfoText); + this.Resize += this.FormResized; this.Controls.Add(this.infoBar); } + }); - this.Resize += this.FormResized; - base.DoPreview(dataSource); - MarkdownTelemetry.Log.MarkdownFilePreviewed(); - } - catch (Exception e) + MarkdownTelemetry.Log.MarkdownFilePreviewed(); + } + catch (Exception e) + { + MarkdownTelemetry.Log.MarkdownFilePreviewError(e.Message); + + this.InvokeOnControlThread(() => { - MarkdownTelemetry.Log.MarkdownFilePreviewError(e.Message); + this.Controls.Clear(); this.infoBarDisplayed = true; this.infoBar = this.GetTextBoxControl(Resources.MarkdownNotPreviewedError); this.Resize += this.FormResized; - this.Controls.Clear(); this.Controls.Add(this.infoBar); - base.DoPreview(dataSource); - } - }); + }); + } + finally + { + base.DoPreview(dataSource); + } } /// diff --git a/src/runner/tray_icon.cpp b/src/runner/tray_icon.cpp index ad59463415..6e8e03d574 100644 --- a/src/runner/tray_icon.cpp +++ b/src/runner/tray_icon.cpp @@ -192,7 +192,8 @@ void start_tray_icon() tray_icon_data.hWnd = hwnd; tray_icon_data.uID = id_tray_icon; tray_icon_data.uCallbackMessage = wm_icon_notify; - wcscpy_s(tray_icon_data.szTip, sizeof(tray_icon_data.szTip) / sizeof(WCHAR), L"PowerToys"); + std::wstring about_msg_pt_version = L"PowerToys\n" + get_product_version(); + wcscpy_s(tray_icon_data.szTip, sizeof(tray_icon_data.szTip) / sizeof(WCHAR), about_msg_pt_version.c_str()); tray_icon_data.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE; tray_icon_created = Shell_NotifyIcon(NIM_ADD, &tray_icon_data) == TRUE; 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"); }