From 1fb7cf7b8bc5a9a5b0cf7ff393c7c571eca66efb Mon Sep 17 00:00:00 2001 From: BornToBeRoot <16019165+BornToBeRoot@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:08:51 +0100 Subject: [PATCH 01/52] Chore: Copy Dragablz into the repository instead of the submodule The library (fork BornToBeRoot/Dragablz 5415e71, based on upstream ButchersBoy/Dragablz e493913) is now maintained in Source/3rdparty/Dragablz, flattened to one project. No demos, tests, solution or NuGet package. LICENSE (MIT) is kept, README.md documents the origin, CHANGELOG.md all changes compared to the original. Assembly, namespaces and pack URIs are unchanged. AppVeyor stamps the file version at the new path. Co-Authored-By: Claude Opus 5.5 --- .gitmodules | 3 - Source/.editorconfig | 4 + Source/3rdparty/Dragablz | 1 - Source/3rdparty/Dragablz/CHANGELOG.md | 38 + Source/3rdparty/Dragablz/CanvasOrganiser.cs | 72 + .../Dragablz/ContainerCustomisations.cs | 34 + .../BooleanAndToVisibilityConverter.cs | 36 + .../Converters/EqualityToBooleanConverter.cs | 19 + .../EqualityToVisibilityConverter.cs | 26 + .../ShowDefaultCloseButtonConverter.cs | 32 + .../Dragablz/Core/CollectionTeaser.cs | 65 + Source/3rdparty/Dragablz/Core/Extensions.cs | 127 ++ Source/3rdparty/Dragablz/Core/FuncComparer.cs | 22 + Source/3rdparty/Dragablz/Core/HitTest.cs | 33 + .../Dragablz/Core/InterTabTransfer.cs | 112 + .../3rdparty/Dragablz/Core/MultiComparer.cs | 77 + Source/3rdparty/Dragablz/Core/Native.cs | 131 ++ .../3rdparty/Dragablz/Core/SystemCommand.cs | 26 + .../Core/TabHeaderDragStartInformation.cs | 51 + .../3rdparty/Dragablz/Core/WindowMessage.cs | 245 ++ .../Dragablz/DefaultInterLayoutClient.cs | 48 + .../Dragablz/DefaultInterTabClient.cs | 34 + Source/3rdparty/Dragablz/Dockablz/Branch.cs | 98 + .../Dragablz/Dockablz/BranchAccessor.cs | 129 ++ .../3rdparty/Dragablz/Dockablz/BranchItem.cs | 8 + .../Dragablz/Dockablz/BranchResult.cs | 35 + .../Dockablz/CouldBeHeaderedStyleSelector.cs | 19 + Source/3rdparty/Dragablz/Dockablz/DropZone.cs | 37 + .../Dragablz/Dockablz/DropZoneLocation.cs | 11 + .../3rdparty/Dragablz/Dockablz/Extensions.cs | 86 + Source/3rdparty/Dragablz/Dockablz/Finder.cs | 53 + .../Dragablz/Dockablz/FloatRequestedEvent.cs | 22 + .../Dragablz/Dockablz/FloatTransfer.cs | 46 + .../Dragablz/Dockablz/FloatingItemSnapShot.cs | 74 + Source/3rdparty/Dragablz/Dockablz/Layout.cs | 999 +++++++++ .../Dragablz/Dockablz/LayoutAccessor.cs | 110 + .../Dragablz/Dockablz/LocationReport.cs | 65 + .../Dockablz/LocationReportBuilder.cs | 54 + .../Dockablz/LocationReportException.cs | 22 + .../Dragablz/Dockablz/LocationSnapShot.cs | 38 + Source/3rdparty/Dragablz/Dockablz/Tiler.cs | 83 + .../Dragablz/Dockablz/TilerCalculator.cs | 29 + Source/3rdparty/Dragablz/Dragablz.csproj | 10 + Source/3rdparty/Dragablz/DragablzColors.cs | 74 + .../DragablzDragCompletedEventArgs.cs | 54 + .../Dragablz/DragablzDragDeltaEventArgs.cs | 44 + .../Dragablz/DragablzDragStartedEventArgs.cs | 38 + Source/3rdparty/Dragablz/DragablzIcon.cs | 25 + Source/3rdparty/Dragablz/DragablzItem.cs | 639 ++++++ .../Dragablz/DragablzItemEventArgs.cs | 37 + .../3rdparty/Dragablz/DragablzItemsControl.cs | 401 ++++ Source/3rdparty/Dragablz/DragablzWindow.cs | 367 +++ .../Dragablz/EmptyHeaderSizingHint.cs | 22 + .../3rdparty/Dragablz/HeaderedDragablzItem.cs | 49 + .../Dragablz/HeaderedItemViewModel.cs | 83 + .../3rdparty/Dragablz/HorizontalOrganiser.cs | 16 + .../Dragablz/HorizontalPositionMonitor.cs | 11 + .../3rdparty/Dragablz/IInterLayoutClient.cs | 19 + Source/3rdparty/Dragablz/IInterTabClient.cs | 27 + Source/3rdparty/Dragablz/IItemsOrganiser.cs | 21 + .../Dragablz/IManualInterTabClient.cs | 8 + Source/3rdparty/Dragablz/INewTabHost.cs | 10 + .../3rdparty/Dragablz/InterTabController.cs | 72 + .../Dragablz/ItemActionCallbackArgs.cs | 47 + Source/3rdparty/Dragablz/LICENSE | 21 + .../Dragablz/LocationChangedEventArgs.cs | 29 + Source/3rdparty/Dragablz/LocationHint.cs | 26 + Source/3rdparty/Dragablz/MergeTargetArea.cs | 18 + .../Dragablz/MergeTargetCalculator.cs | 66 + Source/3rdparty/Dragablz/MoveItemRequest.cs | 31 + Source/3rdparty/Dragablz/NewTabHost.cs | 30 + .../Dragablz/OrderChangedEventArgs.cs | 28 + Source/3rdparty/Dragablz/PositionMonitor.cs | 31 + .../Dragablz/Properties/AssemblyInfo.cs | 63 + .../Dragablz/Properties/Resources.Designer.cs | 63 + .../Dragablz/Properties/Resources.resx | 117 + .../Dragablz/Properties/Settings.Designer.cs | 26 + .../Dragablz/Properties/Settings.settings | 7 + Source/3rdparty/Dragablz/README.md | 27 + .../Referenceless/AnonymousDisposable.cs | 31 + .../Referenceless/DefaultDisposable.cs | 21 + .../Dragablz/Referenceless/Disposable.cs | 23 + .../Dragablz/Referenceless/ICancelable.cs | 9 + .../Referenceless/SerialDisposable.cs | 84 + Source/3rdparty/Dragablz/StackOrganiser.cs | 309 +++ .../3rdparty/Dragablz/StackPositionMonitor.cs | 46 + .../Dragablz/StoryboardCompletionListener.cs | 41 + .../3rdparty/Dragablz/TabEmptiedResponse.cs | 20 + Source/3rdparty/Dragablz/TabablzControl.cs | 1821 +++++++++++++++ .../Dragablz/TabablzHeaderSizeConverter.cs | 50 + .../Dragablz/TabablzItemStyleSelector.cs | 27 + .../BrushToRadialGradientBrushConverter.cs | 31 + Source/3rdparty/Dragablz/Themes/Dockablz.xaml | 8 + Source/3rdparty/Dragablz/Themes/Generic.xaml | 1980 +++++++++++++++++ Source/3rdparty/Dragablz/Themes/MahApps.xaml | 443 ++++ .../Dragablz/Themes/MaterialDesign.xaml | 872 ++++++++ .../Dragablz/Themes/MaterialDesignAssist.cs | 42 + Source/3rdparty/Dragablz/Themes/Ripple.cs | 218 ++ .../3rdparty/Dragablz/Themes/RippleAssist.cs | 74 + .../Dragablz/Themes/SystemCommandIcon.cs | 34 + Source/3rdparty/Dragablz/Trapezoid.cs | 143 ++ Source/3rdparty/Dragablz/VerticalOrganiser.cs | 11 + .../Dragablz/VerticalPositionMonitor.cs | 11 + Source/NETworkManager.sln | 2 +- Source/NETworkManager/NETworkManager.csproj | 2 +- appveyor.yml | 4 +- 106 files changed, 12260 insertions(+), 8 deletions(-) delete mode 100644 .gitmodules delete mode 160000 Source/3rdparty/Dragablz create mode 100644 Source/3rdparty/Dragablz/CHANGELOG.md create mode 100644 Source/3rdparty/Dragablz/CanvasOrganiser.cs create mode 100644 Source/3rdparty/Dragablz/ContainerCustomisations.cs create mode 100644 Source/3rdparty/Dragablz/Converters/BooleanAndToVisibilityConverter.cs create mode 100644 Source/3rdparty/Dragablz/Converters/EqualityToBooleanConverter.cs create mode 100644 Source/3rdparty/Dragablz/Converters/EqualityToVisibilityConverter.cs create mode 100644 Source/3rdparty/Dragablz/Converters/ShowDefaultCloseButtonConverter.cs create mode 100644 Source/3rdparty/Dragablz/Core/CollectionTeaser.cs create mode 100644 Source/3rdparty/Dragablz/Core/Extensions.cs create mode 100644 Source/3rdparty/Dragablz/Core/FuncComparer.cs create mode 100644 Source/3rdparty/Dragablz/Core/HitTest.cs create mode 100644 Source/3rdparty/Dragablz/Core/InterTabTransfer.cs create mode 100644 Source/3rdparty/Dragablz/Core/MultiComparer.cs create mode 100644 Source/3rdparty/Dragablz/Core/Native.cs create mode 100644 Source/3rdparty/Dragablz/Core/SystemCommand.cs create mode 100644 Source/3rdparty/Dragablz/Core/TabHeaderDragStartInformation.cs create mode 100644 Source/3rdparty/Dragablz/Core/WindowMessage.cs create mode 100644 Source/3rdparty/Dragablz/DefaultInterLayoutClient.cs create mode 100644 Source/3rdparty/Dragablz/DefaultInterTabClient.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/Branch.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/BranchAccessor.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/BranchItem.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/BranchResult.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/CouldBeHeaderedStyleSelector.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/DropZone.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/DropZoneLocation.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/Extensions.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/Finder.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/FloatRequestedEvent.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/FloatTransfer.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/FloatingItemSnapShot.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/Layout.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/LayoutAccessor.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/LocationReport.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/LocationReportBuilder.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/LocationReportException.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/LocationSnapShot.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/Tiler.cs create mode 100644 Source/3rdparty/Dragablz/Dockablz/TilerCalculator.cs create mode 100644 Source/3rdparty/Dragablz/Dragablz.csproj create mode 100644 Source/3rdparty/Dragablz/DragablzColors.cs create mode 100644 Source/3rdparty/Dragablz/DragablzDragCompletedEventArgs.cs create mode 100644 Source/3rdparty/Dragablz/DragablzDragDeltaEventArgs.cs create mode 100644 Source/3rdparty/Dragablz/DragablzDragStartedEventArgs.cs create mode 100644 Source/3rdparty/Dragablz/DragablzIcon.cs create mode 100644 Source/3rdparty/Dragablz/DragablzItem.cs create mode 100644 Source/3rdparty/Dragablz/DragablzItemEventArgs.cs create mode 100644 Source/3rdparty/Dragablz/DragablzItemsControl.cs create mode 100644 Source/3rdparty/Dragablz/DragablzWindow.cs create mode 100644 Source/3rdparty/Dragablz/EmptyHeaderSizingHint.cs create mode 100644 Source/3rdparty/Dragablz/HeaderedDragablzItem.cs create mode 100644 Source/3rdparty/Dragablz/HeaderedItemViewModel.cs create mode 100644 Source/3rdparty/Dragablz/HorizontalOrganiser.cs create mode 100644 Source/3rdparty/Dragablz/HorizontalPositionMonitor.cs create mode 100644 Source/3rdparty/Dragablz/IInterLayoutClient.cs create mode 100644 Source/3rdparty/Dragablz/IInterTabClient.cs create mode 100644 Source/3rdparty/Dragablz/IItemsOrganiser.cs create mode 100644 Source/3rdparty/Dragablz/IManualInterTabClient.cs create mode 100644 Source/3rdparty/Dragablz/INewTabHost.cs create mode 100644 Source/3rdparty/Dragablz/InterTabController.cs create mode 100644 Source/3rdparty/Dragablz/ItemActionCallbackArgs.cs create mode 100644 Source/3rdparty/Dragablz/LICENSE create mode 100644 Source/3rdparty/Dragablz/LocationChangedEventArgs.cs create mode 100644 Source/3rdparty/Dragablz/LocationHint.cs create mode 100644 Source/3rdparty/Dragablz/MergeTargetArea.cs create mode 100644 Source/3rdparty/Dragablz/MergeTargetCalculator.cs create mode 100644 Source/3rdparty/Dragablz/MoveItemRequest.cs create mode 100644 Source/3rdparty/Dragablz/NewTabHost.cs create mode 100644 Source/3rdparty/Dragablz/OrderChangedEventArgs.cs create mode 100644 Source/3rdparty/Dragablz/PositionMonitor.cs create mode 100644 Source/3rdparty/Dragablz/Properties/AssemblyInfo.cs create mode 100644 Source/3rdparty/Dragablz/Properties/Resources.Designer.cs create mode 100644 Source/3rdparty/Dragablz/Properties/Resources.resx create mode 100644 Source/3rdparty/Dragablz/Properties/Settings.Designer.cs create mode 100644 Source/3rdparty/Dragablz/Properties/Settings.settings create mode 100644 Source/3rdparty/Dragablz/README.md create mode 100644 Source/3rdparty/Dragablz/Referenceless/AnonymousDisposable.cs create mode 100644 Source/3rdparty/Dragablz/Referenceless/DefaultDisposable.cs create mode 100644 Source/3rdparty/Dragablz/Referenceless/Disposable.cs create mode 100644 Source/3rdparty/Dragablz/Referenceless/ICancelable.cs create mode 100644 Source/3rdparty/Dragablz/Referenceless/SerialDisposable.cs create mode 100644 Source/3rdparty/Dragablz/StackOrganiser.cs create mode 100644 Source/3rdparty/Dragablz/StackPositionMonitor.cs create mode 100644 Source/3rdparty/Dragablz/StoryboardCompletionListener.cs create mode 100644 Source/3rdparty/Dragablz/TabEmptiedResponse.cs create mode 100644 Source/3rdparty/Dragablz/TabablzControl.cs create mode 100644 Source/3rdparty/Dragablz/TabablzHeaderSizeConverter.cs create mode 100644 Source/3rdparty/Dragablz/TabablzItemStyleSelector.cs create mode 100644 Source/3rdparty/Dragablz/Themes/BrushToRadialGradientBrushConverter.cs create mode 100644 Source/3rdparty/Dragablz/Themes/Dockablz.xaml create mode 100644 Source/3rdparty/Dragablz/Themes/Generic.xaml create mode 100644 Source/3rdparty/Dragablz/Themes/MahApps.xaml create mode 100644 Source/3rdparty/Dragablz/Themes/MaterialDesign.xaml create mode 100644 Source/3rdparty/Dragablz/Themes/MaterialDesignAssist.cs create mode 100644 Source/3rdparty/Dragablz/Themes/Ripple.cs create mode 100644 Source/3rdparty/Dragablz/Themes/RippleAssist.cs create mode 100644 Source/3rdparty/Dragablz/Themes/SystemCommandIcon.cs create mode 100644 Source/3rdparty/Dragablz/Trapezoid.cs create mode 100644 Source/3rdparty/Dragablz/VerticalOrganiser.cs create mode 100644 Source/3rdparty/Dragablz/VerticalPositionMonitor.cs diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 9041dc8f9f..0000000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "Source/3rdparty/Dragablz"] - path = Source/3rdparty/Dragablz - url = https://github.com/BornToBeRoot/Dragablz diff --git a/Source/.editorconfig b/Source/.editorconfig index 410e0c68e8..3c856da581 100644 --- a/Source/.editorconfig +++ b/Source/.editorconfig @@ -2,3 +2,7 @@ # CA1416: Plattformkompatibilität überprüfen dotnet_diagnostic.CA1416.severity = silent + +# Vendored third-party code (Dragablz): keep its original style, no analyzer / format findings +[3rdparty/**.cs] +generated_code = true diff --git a/Source/3rdparty/Dragablz b/Source/3rdparty/Dragablz deleted file mode 160000 index 5415e719c0..0000000000 --- a/Source/3rdparty/Dragablz +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 5415e719c0d289f375bcb7f1a3e69f50616c45dc diff --git a/Source/3rdparty/Dragablz/CHANGELOG.md b/Source/3rdparty/Dragablz/CHANGELOG.md new file mode 100644 index 0000000000..0efb95b5b2 --- /dev/null +++ b/Source/3rdparty/Dragablz/CHANGELOG.md @@ -0,0 +1,38 @@ +# Changelog + +All changes compared to the original [ButchersBoy/Dragablz](https://github.com/ButchersBoy/Dragablz) (`e493913`, +2022-09-09). Newest first. Add an entry for every change made in this folder. + +## NETworkManager (`Source/3rdparty/Dragablz`) + +- Copied the library from the fork (`5415e71`) into the repository (replaces the git submodule). Not included: demos + (`DragablzDemo`, `DragablzModernUIDemo`), tests (`Dragablz.Test`), solution, NuGet package (`Dragablz.nuspec`), + `Resources/` (logos). The project is flattened (`Dragablz.csproj` in this folder), the NuGet metadata, the output path + `..\bin` and `InternalsVisibleTo("Dragablz.Test")` are removed. + +## Fork ([BornToBeRoot/Dragablz](https://github.com/BornToBeRoot/Dragablz), 2022-11 to 2026-11) + +- Merge hint and larger merge area for tabs dragged as a window (opt-in, defaults unchanged): + - `MergeTargetArea` (`HeaderItems` (default) / `HeaderPanel`): `HeaderPanel` also accepts a tab over the empty area of + the tab bar (optional template part `PART_HeaderPanel`, renamed from `HeaderContainerGrid`). + - `ShowMergeHint`, `MergeHintProximity` (default 48 DIPs) and `MergeHintTemplate` show a hint in the tab bar of every + tab control the dragged tab can be merged into; read-only `IsMergeTargetParticipating` / `IsMergeTargetOffered` + for custom templates. + - Vertical tab strips with fixed headers are respected when searching a merge target; a tab dropped behind the last + tab is inserted after it. +- Fix `NullReferenceException` when a tab drag starts while `InterTabController.Partition` is `null` + (`TabablzControl.ItemDragStarted`). +- Fix `NullReferenceException` when dragging a maximized `DragablzWindow` (`WindowInteropHelper` instead of reading a + private `Window` property via reflection). +- Fix MahApps theme (`MahApps.xaml`): `MahApps.Brushes.*` / `MahApps.Colors.*` resource keys of MahApps.Metro 2.x + (`MahApps.Colors.Accent2`, `MahApps.Brushes.IdealForeground` instead of `WhiteBrush`). +- Wider hit area for the grid splitters between layout branches (`Generic.xaml`). +- `DisableBranchConsolidation` (`TabablzControl`): don't consolidate a branch when its tab control is emptied (e.g. to + keep the main tab control that creates new tabs). +- Fix closing a tab in a layout branch with `TabEmptiedResponse.DoNothing` (`TabEmptiedResponse`, `TabablzControl`). +- `InterTabController.Partition` and `Layout.Partition` are dependency properties (bindable), from + [Dragablz#275](https://github.com/ButchersBoy/Dragablz/pull/275). +- Fix [right click and drag "locks" the tab item](https://github.com/ButchersBoy/Dragablz/issues/132) + (`DragablzItem`), from [Dragablz#275](https://github.com/ButchersBoy/Dragablz/pull/275). +- .NET 6 → 8 → 10: SDK-style project, target framework `net10.0-windows` (no Windows SDK version, no + `RuntimeIdentifier` / `PlatformTarget`, so it builds for x64 and arm64). diff --git a/Source/3rdparty/Dragablz/CanvasOrganiser.cs b/Source/3rdparty/Dragablz/CanvasOrganiser.cs new file mode 100644 index 0000000000..198dc155fe --- /dev/null +++ b/Source/3rdparty/Dragablz/CanvasOrganiser.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Windows; +using System.Windows.Controls; + +namespace Dragablz +{ + public class CanvasOrganiser : IItemsOrganiser + { + public virtual void Organise(DragablzItemsControl requestor, Size measureBounds, IEnumerable items) + { + + } + + public virtual void Organise(DragablzItemsControl requestor, Size measureBounds, IOrderedEnumerable items) + { + + } + + public virtual void OrganiseOnMouseDownWithin(DragablzItemsControl requestor, Size measureBounds, List siblingItems, DragablzItem dragablzItem) + { + var zIndex = int.MaxValue; + foreach (var source in siblingItems.OrderByDescending(Panel.GetZIndex)) + { + Panel.SetZIndex(source, --zIndex); + + } + Panel.SetZIndex(dragablzItem, int.MaxValue); + } + + public virtual void OrganiseOnDragStarted(DragablzItemsControl requestor, Size measureBounds, IEnumerable siblingItems, DragablzItem dragItem) + { + + } + + public virtual void OrganiseOnDrag(DragablzItemsControl requestor, Size measureBounds, IEnumerable siblingItems, DragablzItem dragItem) + { + + } + + public virtual void OrganiseOnDragCompleted(DragablzItemsControl requestor, Size measureBounds, IEnumerable siblingItems, DragablzItem dragItem) + { + + } + + public virtual Point ConstrainLocation(DragablzItemsControl requestor, Size measureBounds, Point itemCurrentLocation, Size itemCurrentSize, Point itemDesiredLocation, Size itemDesiredSize) + { + //we will stop it pushing beyond the bounds...unless it's already beyond... + var reduceBoundsWidth = itemCurrentLocation.X + itemCurrentSize.Width > measureBounds.Width + ? 0 + : itemDesiredSize.Width; + var reduceBoundsHeight = itemCurrentLocation.Y + itemCurrentSize.Height > measureBounds.Height + ? 0 + : itemDesiredSize.Height; + + return new Point( + Math.Min(Math.Max(itemDesiredLocation.X, 0), measureBounds.Width - reduceBoundsWidth), + Math.Min(Math.Max(itemDesiredLocation.Y, 0), measureBounds.Height - reduceBoundsHeight)); + } + + public virtual Size Measure(DragablzItemsControl requestor, Size availableSize, IEnumerable items) + { + return availableSize; + } + + public virtual IEnumerable Sort(IEnumerable items) + { + return items; + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/ContainerCustomisations.cs b/Source/3rdparty/Dragablz/ContainerCustomisations.cs new file mode 100644 index 0000000000..1cb8442b13 --- /dev/null +++ b/Source/3rdparty/Dragablz/ContainerCustomisations.cs @@ -0,0 +1,34 @@ +using System; +using System.Windows; + +namespace Dragablz +{ + internal class ContainerCustomisations + { + private readonly Func _getContainerForItemOverride; + private readonly Action _prepareContainerForItemOverride; + private readonly Action _clearingContainerForItemOverride; + + public ContainerCustomisations(Func getContainerForItemOverride = null, Action prepareContainerForItemOverride = null, Action clearingContainerForItemOverride = null) + { + _getContainerForItemOverride = getContainerForItemOverride; + _prepareContainerForItemOverride = prepareContainerForItemOverride; + _clearingContainerForItemOverride = clearingContainerForItemOverride; + } + + public Func GetContainerForItemOverride + { + get { return _getContainerForItemOverride; } + } + + public Action PrepareContainerForItemOverride + { + get { return _prepareContainerForItemOverride; } + } + + public Action ClearingContainerForItemOverride + { + get { return _clearingContainerForItemOverride; } + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Converters/BooleanAndToVisibilityConverter.cs b/Source/3rdparty/Dragablz/Converters/BooleanAndToVisibilityConverter.cs new file mode 100644 index 0000000000..77a4d1b270 --- /dev/null +++ b/Source/3rdparty/Dragablz/Converters/BooleanAndToVisibilityConverter.cs @@ -0,0 +1,36 @@ +using System; +using System.Globalization; +using System.Linq; +using System.Windows; +using System.Windows.Data; + +namespace Dragablz.Converters +{ + public class BooleanAndToVisibilityConverter : IMultiValueConverter + { + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + if (values == null) + return Visibility.Collapsed; + + return values.Select(GetBool).All(b => b) + ? Visibility.Visible + : Visibility.Collapsed; + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + return null; + } + + private static bool GetBool(object value) + { + if (value is bool) + { + return (bool)value; + } + + return false; + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Converters/EqualityToBooleanConverter.cs b/Source/3rdparty/Dragablz/Converters/EqualityToBooleanConverter.cs new file mode 100644 index 0000000000..7e10301df5 --- /dev/null +++ b/Source/3rdparty/Dragablz/Converters/EqualityToBooleanConverter.cs @@ -0,0 +1,19 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace Dragablz.Converters +{ + public class EqualityToBooleanConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return Equals(value, parameter); + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return Binding.DoNothing; + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Converters/EqualityToVisibilityConverter.cs b/Source/3rdparty/Dragablz/Converters/EqualityToVisibilityConverter.cs new file mode 100644 index 0000000000..a276402fbe --- /dev/null +++ b/Source/3rdparty/Dragablz/Converters/EqualityToVisibilityConverter.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; + +namespace Dragablz.Converters +{ + public class EqualityToVisibilityConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + return Equals(value, parameter) + ? Visibility.Visible + : Visibility.Collapsed; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return Binding.DoNothing; + } + } +} diff --git a/Source/3rdparty/Dragablz/Converters/ShowDefaultCloseButtonConverter.cs b/Source/3rdparty/Dragablz/Converters/ShowDefaultCloseButtonConverter.cs new file mode 100644 index 0000000000..8bc70c43e1 --- /dev/null +++ b/Source/3rdparty/Dragablz/Converters/ShowDefaultCloseButtonConverter.cs @@ -0,0 +1,32 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; + +namespace Dragablz.Converters +{ + public class ShowDefaultCloseButtonConverter : IMultiValueConverter + { + /// + /// [0] is owning tabcontrol ShowDefaultCloseButton value. + /// [1] is owning tabcontrol FixedHeaderCount value. + /// [2] is item LogicalIndex + /// + /// + /// + /// + /// + /// + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + return ((values[0] == DependencyProperty.UnsetValue ? false : (bool)values[0]) && + (values[2] == DependencyProperty.UnsetValue ? 0 : (int)values[2]) >= + (values[1] == DependencyProperty.UnsetValue ? 0 : (int)values[1])) ? Visibility.Visible : Visibility.Collapsed; + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + return null; + } + } +} diff --git a/Source/3rdparty/Dragablz/Core/CollectionTeaser.cs b/Source/3rdparty/Dragablz/Core/CollectionTeaser.cs new file mode 100644 index 0000000000..465ab08813 --- /dev/null +++ b/Source/3rdparty/Dragablz/Core/CollectionTeaser.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace Dragablz.Core +{ + internal class CollectionTeaser + { + private readonly Action _addMethod; + private readonly Action _removeMethod; + + private CollectionTeaser(Action addMethod, Action removeMethod) + { + _addMethod = addMethod; + _removeMethod = removeMethod; + } + + public static bool TryCreate(object items, out CollectionTeaser collectionTeaser) + { + collectionTeaser = null; + + var list = items as IList; + if (list != null) + { + collectionTeaser = new CollectionTeaser(i => list.Add(i), list.Remove); + } + else if (items != null) + { + var itemsType = items.GetType(); + var genericCollectionType = typeof(ICollection<>); + + //TODO, *IF* we really wanted to we could get the consumer to inform us of the correct type + //if there are multiple impls. havent got time for this edge case right now though + var collectionImplType = itemsType.GetInterfaces().SingleOrDefault(x => + x.IsGenericType && + x.GetGenericTypeDefinition() == genericCollectionType); + + if (collectionImplType != null) + { + var genericArgType = collectionImplType.GetGenericArguments().First(); + + var addMethodInfo = collectionImplType.GetMethod("Add", new[] { genericArgType }); + var removeMethodInfo = collectionImplType.GetMethod("Remove", new[] { genericArgType }); + + collectionTeaser = new CollectionTeaser( + i => addMethodInfo.Invoke(items, new[] { i }), + i => removeMethodInfo.Invoke(items, new[] { i })); + } + } + + return collectionTeaser != null; + } + + public void Add(object item) + { + _addMethod(item); + } + + public void Remove(object item) + { + _removeMethod(item); + } + } +} diff --git a/Source/3rdparty/Dragablz/Core/Extensions.cs b/Source/3rdparty/Dragablz/Core/Extensions.cs new file mode 100644 index 0000000000..eaa6e5a6f7 --- /dev/null +++ b/Source/3rdparty/Dragablz/Core/Extensions.cs @@ -0,0 +1,127 @@ +#if NET40 +using System.Collections; +using System.Reflection; +#endif +using System; +using System.Collections.Generic; +using System.Linq; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; + +namespace Dragablz.Core +{ + internal static class Extensions + { + public static IEnumerable Containers(this ItemsControl itemsControl) where TContainer : class + { +#if NET40 + var fieldInfo = typeof(ItemContainerGenerator).GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance); + var list = (IList)fieldInfo.GetValue(itemsControl.ItemContainerGenerator); + for (var i = 0; i < list.Count; i++) +#else + for (var i = 0; i < itemsControl.ItemContainerGenerator.Items.Count; i++) +#endif + { + var container = itemsControl.ItemContainerGenerator.ContainerFromIndex(i) as TContainer; + if (container != null) + yield return container; + } + } + + public static IEnumerable Except(this IEnumerable first, params TObject[] second) + { + return first.Except((IEnumerable)second); + } + + public static IEnumerable LogicalTreeDepthFirstTraversal(this DependencyObject node) + { + if (node == null) yield break; + yield return node; + + foreach (var child in LogicalTreeHelper.GetChildren(node).OfType() + .SelectMany(depObj => depObj.LogicalTreeDepthFirstTraversal())) + yield return child; + } + + public static IEnumerable VisualTreeDepthFirstTraversal(this DependencyObject node) + { + if (node == null) yield break; + yield return node; + + for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++) + { + var child = VisualTreeHelper.GetChild(node, i); + foreach (var d in child.VisualTreeDepthFirstTraversal()) + { + yield return d; + } + } + } + + /// + /// Yields the visual ancestory (including the starting point). + /// + /// + /// + public static IEnumerable VisualTreeAncestory(this DependencyObject dependencyObject) + { + if (dependencyObject == null) throw new ArgumentNullException("dependencyObject"); + + while (dependencyObject != null) + { + yield return dependencyObject; + dependencyObject = VisualTreeHelper.GetParent(dependencyObject); + } + } + + /// + /// Yields the logical ancestory (including the starting point). + /// + /// + /// + public static IEnumerable LogicalTreeAncestory(this DependencyObject dependencyObject) + { + if (dependencyObject == null) throw new ArgumentNullException("dependencyObject"); + + while (dependencyObject != null) + { + yield return dependencyObject; + dependencyObject = LogicalTreeHelper.GetParent(dependencyObject); + } + } + + /// + /// Returns the actual Left of the Window independently from the WindowState + /// + /// + /// + public static double GetActualLeft(this Window window) + { + if (window.WindowState == WindowState.Maximized) + { + var leftField = typeof(Window).GetField("_actualLeft", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); + return leftField?.GetValue(window) as double? ?? 0; + } + + return window.Left; + } + + /// + /// Returns the actual Top of the Window independently from the WindowState + /// + /// + /// + public static double GetActualTop(this Window window) + { + if (window.WindowState == WindowState.Maximized) + { + var topField = typeof(Window).GetField("_actualTop", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); + return topField?.GetValue(window) as double? ?? 0; + } + + return window.Top; + } + + } +} diff --git a/Source/3rdparty/Dragablz/Core/FuncComparer.cs b/Source/3rdparty/Dragablz/Core/FuncComparer.cs new file mode 100644 index 0000000000..487f62f434 --- /dev/null +++ b/Source/3rdparty/Dragablz/Core/FuncComparer.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; + +namespace Dragablz.Core +{ + internal class FuncComparer : IComparer + { + private readonly Func _comparer; + + public FuncComparer(Func comparer) + { + if (comparer == null) throw new ArgumentNullException("comparer"); + + _comparer = comparer; + } + + public int Compare(TObject x, TObject y) + { + return _comparer(x, y); + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Core/HitTest.cs b/Source/3rdparty/Dragablz/Core/HitTest.cs new file mode 100644 index 0000000000..261233c064 --- /dev/null +++ b/Source/3rdparty/Dragablz/Core/HitTest.cs @@ -0,0 +1,33 @@ +namespace Dragablz.Core +{ + /// + /// Non-client hit test values, HT* + /// + internal enum HitTest + { + HT_ERROR = -2, + HT_TRANSPARENT = -1, + HT_NOWHERE = 0, + HT_CLIENT = 1, + HT_CAPTION = 2, + HT_SYSMENU = 3, + HT_GROWBOX = 4, + HT_MENU = 5, + HT_HSCROLL = 6, + HT_VSCROLL = 7, + HT_MINBUTTON = 8, + HT_MAXBUTTON = 9, + HT_LEFT = 10, + HT_RIGHT = 11, + HT_TOP = 12, + HT_TOPLEFT = 13, + HT_TOPRIGHT = 14, + HT_BOTTOM = 15, + HT_BOTTOMLEFT = 16, + HT_BOTTOMRIGHT = 17, + HT_BORDER = 18, + HT_OBJECT = 19, + HT_CLOSE = 20, + HT_HELP = 21 + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Core/InterTabTransfer.cs b/Source/3rdparty/Dragablz/Core/InterTabTransfer.cs new file mode 100644 index 0000000000..2d54acb6a1 --- /dev/null +++ b/Source/3rdparty/Dragablz/Core/InterTabTransfer.cs @@ -0,0 +1,112 @@ +using System; +using System.Collections.Generic; +using System.Windows; +using System.Windows.Controls; +using Dragablz.Dockablz; + +namespace Dragablz.Core +{ + internal enum InterTabTransferReason + { + Breach, + Reentry + } + + internal class InterTabTransfer + { + private readonly object _item; + private readonly DragablzItem _originatorContainer; + private readonly Orientation _breachOrientation; + private readonly Point _dragStartWindowOffset; + private readonly Point _dragStartItemOffset; + private readonly Point _itemPositionWithinHeader; + private readonly Size _itemSize; + private readonly IList _floatingItemSnapShots; + private readonly bool _isTransposing; + private readonly InterTabTransferReason _transferReason; + + public InterTabTransfer(object item, DragablzItem originatorContainer, Orientation breachOrientation, Point dragStartWindowOffset, Point dragStartItemOffset, Point itemPositionWithinHeader, Size itemSize, IList floatingItemSnapShots, bool isTransposing) + { + if (item == null) throw new ArgumentNullException("item"); + if (originatorContainer == null) throw new ArgumentNullException("originatorContainer"); + if (floatingItemSnapShots == null) throw new ArgumentNullException("floatingItemSnapShots"); + + _transferReason = InterTabTransferReason.Breach; + + _item = item; + _originatorContainer = originatorContainer; + _breachOrientation = breachOrientation; + _dragStartWindowOffset = dragStartWindowOffset; + _dragStartItemOffset = dragStartItemOffset; + _itemPositionWithinHeader = itemPositionWithinHeader; + _itemSize = itemSize; + _floatingItemSnapShots = floatingItemSnapShots; + _isTransposing = isTransposing; + } + + public InterTabTransfer(object item, DragablzItem originatorContainer, Point dragStartItemOffset, + IList floatingItemSnapShots) + { + if (item == null) throw new ArgumentNullException("item"); + if (originatorContainer == null) throw new ArgumentNullException("originatorContainer"); + if (floatingItemSnapShots == null) throw new ArgumentNullException("floatingItemSnapShots"); + + _transferReason = InterTabTransferReason.Reentry; + + _item = item; + _originatorContainer = originatorContainer; + _dragStartItemOffset = dragStartItemOffset; + _floatingItemSnapShots = floatingItemSnapShots; + } + + public Orientation BreachOrientation + { + get { return _breachOrientation; } + } + + public Point DragStartWindowOffset + { + get { return _dragStartWindowOffset; } + } + + public object Item + { + get { return _item; } + } + + public DragablzItem OriginatorContainer + { + get { return _originatorContainer; } + } + + public InterTabTransferReason TransferReason + { + get { return _transferReason; } + } + + public Point DragStartItemOffset + { + get { return _dragStartItemOffset; } + } + + public Point ItemPositionWithinHeader + { + get { return _itemPositionWithinHeader; } + } + + public Size ItemSize + { + get { return _itemSize; } + } + + public IList FloatingItemSnapShots + { + get { return _floatingItemSnapShots; } + } + + public bool IsTransposing + { + get { return _isTransposing; } + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Core/MultiComparer.cs b/Source/3rdparty/Dragablz/Core/MultiComparer.cs new file mode 100644 index 0000000000..5289216dff --- /dev/null +++ b/Source/3rdparty/Dragablz/Core/MultiComparer.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Dragablz.Core +{ + internal class MultiComparer : IComparer + { + private readonly IList> _attributeComparers; + + private MultiComparer(FuncComparer firstComparer) + { + _attributeComparers = new List> + { + firstComparer + }; + } + + public static MultiComparer Ascending(Func accessor) + where TAttribute : IComparable + { + if (accessor == null) throw new ArgumentNullException("accessor"); + + return new MultiComparer(BuildAscendingComparer(accessor)); + } + + public static MultiComparer Descending(Func accessor) + where TAttribute : IComparable + { + if (accessor == null) throw new ArgumentNullException("accessor"); + + return new MultiComparer(BuildDescendingComparer(accessor)); + } + + public MultiComparer ThenAscending(Func accessor) + where TAttribute : IComparable + { + if (accessor == null) throw new ArgumentNullException("accessor"); + + _attributeComparers.Add(BuildAscendingComparer(accessor)); + + return this; + } + + public MultiComparer ThenDescending(Func accessor) + where TAttribute : IComparable + { + if (accessor == null) throw new ArgumentNullException("accessor"); + + _attributeComparers.Add(BuildDescendingComparer(accessor)); + + return this; + } + + public int Compare(TObject x, TObject y) + { + var nonEqual = _attributeComparers.Select(c => new { result = c.Compare(x, y) }).FirstOrDefault(a => a.result != 0); + + return nonEqual == null ? 0 : nonEqual.result; + } + + private static FuncComparer BuildAscendingComparer(Func accessor) + where TAttribute : IComparable + { + //TODO handle ref types better + return new FuncComparer((x, y) => accessor(x).CompareTo(accessor(y))); + + } + + private static FuncComparer BuildDescendingComparer(Func accessor) + where TAttribute : IComparable + { + //TODO handle ref types better + return new FuncComparer((x, y) => accessor(y).CompareTo(accessor(x))); + } + } +} diff --git a/Source/3rdparty/Dragablz/Core/Native.cs b/Source/3rdparty/Dragablz/Core/Native.cs new file mode 100644 index 0000000000..4b0f9c5afe --- /dev/null +++ b/Source/3rdparty/Dragablz/Core/Native.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.InteropServices; +using System.Windows; +using System.Windows.Interop; + +namespace Dragablz.Core +{ + internal static class Native + { + [StructLayout(LayoutKind.Sequential)] + public struct POINT + { + public int X; + public int Y; + + public static implicit operator Point(POINT point) + { + return new Point(point.X, point.Y); + } + } + + [StructLayout(LayoutKind.Sequential)] + public struct RECT + { + public int left; + public int top; + public int right; + public int bottom; + } + + [DllImport("user32.dll")] + private static extern bool GetCursorPos(out POINT lpPoint); + + public static POINT GetRawCursorPos() + { + POINT lpPoint; + GetCursorPos(out lpPoint); + return lpPoint; + } + + public static Point GetCursorPos() + { + POINT lpPoint; + GetCursorPos(out lpPoint); + return lpPoint; + } + + [DllImport("User32.dll")] + private static extern IntPtr GetDC(IntPtr hwnd); + + [DllImport("gdi32.dll")] + private static extern int GetDeviceCaps(IntPtr hdc, int nIndex); + + [DllImport("user32.dll")] + private static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC); + + public static Point ToWpf(this Point pixelPoint) + { + var desktop = GetDC(IntPtr.Zero); + var dpi = GetDeviceCaps(desktop, 88); + ReleaseDC(IntPtr.Zero, desktop); + + var physicalUnitSize = 96d / dpi; + var wpfPoint = new Point(physicalUnitSize * pixelPoint.X, physicalUnitSize * pixelPoint.Y); + + return wpfPoint; + } + + public static IEnumerable SortWindowsTopToBottom(IEnumerable windows) + { + var windowsByHandle = windows.Select(window => + { + var hwndSource = PresentationSource.FromVisual(window) as HwndSource; + var handle = hwndSource != null ? hwndSource.Handle : IntPtr.Zero; + return new { window, handle }; + }).Where(x => x.handle != IntPtr.Zero) + .ToDictionary(x => x.handle, x => x.window); + + for (var hWnd = GetTopWindow(IntPtr.Zero); hWnd != IntPtr.Zero; hWnd = GetWindow(hWnd, GW_HWNDNEXT)) + if (windowsByHandle.ContainsKey((hWnd))) + yield return windowsByHandle[hWnd]; + } + + public const int SW_SHOWNORMAL = 1; + [DllImport("user32.dll")] + public static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl); + + private const uint GW_HWNDNEXT = 2; + [DllImport("User32")] + public static extern IntPtr GetTopWindow(IntPtr hWnd); + + [DllImport("User32")] + public static extern IntPtr GetWindow(IntPtr hWnd, uint wCmd); + + [Serializable] + [StructLayout(LayoutKind.Sequential)] + public struct WINDOWPLACEMENT + { + public int length; + public int flags; + public int showCmd; + public POINT minPosition; + public POINT maxPosition; + public RECT normalPosition; + } + + [DllImport("user32.dll", CharSet = CharSet.Auto)] + internal static extern IntPtr SendMessage(IntPtr hWnd, WindowMessage msg, IntPtr wParam, IntPtr lParam); + [DllImport("user32.dll", CharSet = CharSet.Auto)] + internal static extern IntPtr PostMessage(IntPtr hWnd, WindowMessage msg, IntPtr wParam, IntPtr lParam); + + + [DllImport("dwmapi.dll", EntryPoint = "#127")] + internal static extern void DwmGetColorizationParameters(ref DWMCOLORIZATIONPARAMS dp); + + [StructLayout(LayoutKind.Sequential)] + internal struct DWMCOLORIZATIONPARAMS + { + public UInt32 ColorizationColor; + public UInt32 ColorizationAfterglow; + public UInt32 ColorizationColorBalance; + public UInt32 ColorizationAfterglowBalance; + public UInt32 ColorizationBlurBalance; + public UInt32 ColorizationGlassReflectionIntensity; + public UInt32 ColorizationOpaqueBlend; + } + + } +} diff --git a/Source/3rdparty/Dragablz/Core/SystemCommand.cs b/Source/3rdparty/Dragablz/Core/SystemCommand.cs new file mode 100644 index 0000000000..95d4589fc0 --- /dev/null +++ b/Source/3rdparty/Dragablz/Core/SystemCommand.cs @@ -0,0 +1,26 @@ +namespace Dragablz.Core +{ + internal enum SystemCommand + { + SC_CLOSE = 0xF060, + SC_CONTEXTHELP = 0xF180, + SC_DEFAULT = 0xF160, + SC_HOTKEY = 0xF150, + SC_HSCROLL = 0xF080, + SCF_ISSECURE = 0x00000001, + SC_KEYMENU = 0xF100, + SC_MAXIMIZE = 0xF030, + SC_MINIMIZE = 0xF020, + SC_MONITORPOWER = 0xF170, + SC_MOUSEMENU = 0xF090, + SC_MOVE = 0xF010, + SC_MOUSEMOVE = 0xF012, + SC_NEXTWINDOW = 0xF040, + SC_PREVWINDOW = 0xF050, + SC_RESTORE = 0xF120, + SC_SCREENSAVE = 0xF140, + SC_SIZE = 0xF000, + SC_TASKLIST = 0xF130, + SC_VSCROLL = 0xF070 + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Core/TabHeaderDragStartInformation.cs b/Source/3rdparty/Dragablz/Core/TabHeaderDragStartInformation.cs new file mode 100644 index 0000000000..6edd409991 --- /dev/null +++ b/Source/3rdparty/Dragablz/Core/TabHeaderDragStartInformation.cs @@ -0,0 +1,51 @@ +using System; + +namespace Dragablz.Core +{ + internal class TabHeaderDragStartInformation + { + private readonly DragablzItem _dragItem; + private readonly double _dragablzItemsControlHorizontalOffset; + private readonly double _dragablzItemControlVerticalOffset; + private readonly double _dragablzItemHorizontalOffset; + private readonly double _dragablzItemVerticalOffset; + + public TabHeaderDragStartInformation( + DragablzItem dragItem, + double dragablzItemsControlHorizontalOffset, double dragablzItemControlVerticalOffset, double dragablzItemHorizontalOffset, double dragablzItemVerticalOffset) + { + if (dragItem == null) throw new ArgumentNullException("dragItem"); + + _dragItem = dragItem; + _dragablzItemsControlHorizontalOffset = dragablzItemsControlHorizontalOffset; + _dragablzItemControlVerticalOffset = dragablzItemControlVerticalOffset; + _dragablzItemHorizontalOffset = dragablzItemHorizontalOffset; + _dragablzItemVerticalOffset = dragablzItemVerticalOffset; + } + + public double DragablzItemsControlHorizontalOffset + { + get { return _dragablzItemsControlHorizontalOffset; } + } + + public double DragablzItemControlVerticalOffset + { + get { return _dragablzItemControlVerticalOffset; } + } + + public double DragablzItemHorizontalOffset + { + get { return _dragablzItemHorizontalOffset; } + } + + public double DragablzItemVerticalOffset + { + get { return _dragablzItemVerticalOffset; } + } + + public DragablzItem DragItem + { + get { return _dragItem; } + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Core/WindowMessage.cs b/Source/3rdparty/Dragablz/Core/WindowMessage.cs new file mode 100644 index 0000000000..fab013402a --- /dev/null +++ b/Source/3rdparty/Dragablz/Core/WindowMessage.cs @@ -0,0 +1,245 @@ +namespace Dragablz.Core +{ + internal enum WindowMessage + { + WM_NULL = 0, + WM_CREATE = 1, + WM_DESTROY = 2, + WM_MOVE = 3, + WM_SIZE = 5, + WM_ACTIVATE = 6, + WM_SETFOCUS = 7, + WM_KILLFOCUS = 8, + WM_ENABLE = 10, + WM_SETREDRAW = 11, + WM_SETTEXT = 12, + WM_GETTEXT = 13, + WM_GETTEXTLENGTH = 14, + WM_PAINT = 15, + WM_CLOSE = 16, + WM_QUERYENDSESSION = 17, + WM_QUIT = 18, + WM_QUERYOPEN = 19, + WM_ERASEBKGND = 20, + WM_SYSCOLORCHANGE = 21, + WM_ENDSESSION = 22, + WM_SHOWWINDOW = 24, + WM_CTLCOLOR = 25, + WM_SETTINGCHANGE = 26, + WM_WININICHANGE = 26, + WM_DEVMODECHANGE = 27, + WM_ACTIVATEAPP = 28, + WM_FONTCHANGE = 29, + WM_TIMECHANGE = 30, + WM_CANCELMODE = 31, + WM_SETCURSOR = 32, + WM_TABLET_MAXOFFSET = 32, + WM_MOUSEACTIVATE = 33, + WM_CHILDACTIVATE = 34, + WM_QUEUESYNC = 35, + WM_GETMINMAXINFO = 36, + WM_PAINTICON = 38, + WM_ICONERASEBKGND = 39, + WM_NEXTDLGCTL = 40, + WM_SPOOLERSTATUS = 42, + WM_DRAWITEM = 43, + WM_MEASUREITEM = 44, + WM_DELETEITEM = 45, + WM_VKEYTOITEM = 46, + WM_CHARTOITEM = 47, + WM_SETFONT = 48, + WM_GETFONT = 49, + WM_SETHOTKEY = 50, + WM_GETHOTKEY = 51, + WM_QUERYDRAGICON = 55, + WM_COMPAREITEM = 57, + WM_GETOBJECT = 61, + WM_COMPACTING = 65, + WM_COMMNOTIFY = 68, + WM_WINDOWPOSCHANGING = 70, + WM_WINDOWPOSCHANGED = 71, + WM_POWER = 72, + WM_COPYDATA = 74, + WM_CANCELJOURNAL = 75, + WM_NOTIFY = 78, + WM_INPUTLANGCHANGEREQUEST = 80, + WM_INPUTLANGCHANGE = 81, + WM_TCARD = 82, + WM_HELP = 83, + WM_USERCHANGED = 84, + WM_NOTIFYFORMAT = 85, + WM_CONTEXTMENU = 123, + WM_STYLECHANGING = 124, + WM_STYLECHANGED = 125, + WM_DISPLAYCHANGE = 126, + WM_GETICON = 127, + WM_SETICON = 128, + WM_NCCREATE = 129, + WM_NCDESTROY = 130, + WM_NCCALCSIZE = 131, + WM_NCHITTEST = 132, + WM_NCPAINT = 133, + WM_NCACTIVATE = 134, + WM_GETDLGCODE = 135, + WM_SYNCPAINT = 136, + WM_MOUSEQUERY = 155, + WM_NCMOUSEMOVE = 160, + WM_NCLBUTTONDOWN = 161, + WM_NCLBUTTONUP = 162, + WM_NCLBUTTONDBLCLK = 163, + WM_NCRBUTTONDOWN = 164, + WM_NCRBUTTONUP = 165, + WM_NCRBUTTONDBLCLK = 166, + WM_NCMBUTTONDOWN = 167, + WM_NCMBUTTONUP = 168, + WM_NCMBUTTONDBLCLK = 169, + WM_NCXBUTTONDOWN = 171, + WM_NCXBUTTONUP = 172, + WM_NCXBUTTONDBLCLK = 173, + WM_INPUT = 255, + WM_KEYDOWN = 256, + WM_KEYFIRST = 256, + WM_KEYUP = 257, + WM_CHAR = 258, + WM_DEADCHAR = 259, + WM_SYSKEYDOWN = 260, + WM_SYSKEYUP = 261, + WM_SYSCHAR = 262, + WM_SYSDEADCHAR = 263, + WM_KEYLAST = 264, + WM_IME_STARTCOMPOSITION = 269, + WM_IME_ENDCOMPOSITION = 270, + WM_IME_COMPOSITION = 271, + WM_IME_KEYLAST = 271, + WM_INITDIALOG = 272, + WM_COMMAND = 273, + WM_SYSCOMMAND = 274, + WM_TIMER = 275, + WM_HSCROLL = 276, + WM_VSCROLL = 277, + WM_INITMENU = 278, + WM_INITMENUPOPUP = 279, + WM_MENUSELECT = 287, + WM_MENUCHAR = 288, + WM_ENTERIDLE = 289, + WM_UNINITMENUPOPUP = 293, + WM_CHANGEUISTATE = 295, + WM_UPDATEUISTATE = 296, + WM_QUERYUISTATE = 297, + WM_CTLCOLORMSGBOX = 306, + WM_CTLCOLOREDIT = 307, + WM_CTLCOLORLISTBOX = 308, + WM_CTLCOLORBTN = 309, + WM_CTLCOLORDLG = 310, + WM_CTLCOLORSCROLLBAR = 311, + WM_CTLCOLORSTATIC = 312, + WM_MOUSEFIRST = 512, + WM_MOUSEMOVE = 512, + WM_LBUTTONDOWN = 513, + WM_LBUTTONUP = 514, + WM_LBUTTONDBLCLK = 515, + WM_RBUTTONDOWN = 516, + WM_RBUTTONUP = 517, + WM_RBUTTONDBLCLK = 518, + WM_MBUTTONDOWN = 519, + WM_MBUTTONUP = 520, + WM_MBUTTONDBLCLK = 521, + WM_MOUSEWHEEL = 522, + WM_XBUTTONDOWN = 523, + WM_XBUTTONUP = 524, + WM_XBUTTONDBLCLK = 525, + WM_MOUSEHWHEEL = 526, + WM_MOUSELAST = 526, + WM_PARENTNOTIFY = 528, + WM_ENTERMENULOOP = 529, + WM_EXITMENULOOP = 530, + WM_NEXTMENU = 531, + WM_SIZING = 532, + WM_CAPTURECHANGED = 533, + WM_MOVING = 534, + WM_POWERBROADCAST = 536, + WM_DEVICECHANGE = 537, + WM_MDICREATE = 544, + WM_MDIDESTROY = 545, + WM_MDIACTIVATE = 546, + WM_MDIRESTORE = 547, + WM_MDINEXT = 548, + WM_MDIMAXIMIZE = 549, + WM_MDITILE = 550, + WM_MDICASCADE = 551, + WM_MDIICONARRANGE = 552, + WM_MDIGETACTIVE = 553, + WM_MDISETMENU = 560, + WM_ENTERSIZEMOVE = 561, + WM_EXITSIZEMOVE = 562, + WM_DROPFILES = 563, + WM_MDIREFRESHMENU = 564, + WM_IME_SETCONTEXT = 641, + WM_IME_NOTIFY = 642, + WM_IME_CONTROL = 643, + WM_IME_COMPOSITIONFULL = 644, + WM_IME_SELECT = 645, + WM_IME_CHAR = 646, + WM_IME_REQUEST = 648, + WM_IME_KEYDOWN = 656, + WM_IME_KEYUP = 657, + WM_MOUSEHOVER = 673, + WM_NCMOUSELEAVE = 674, + WM_MOUSELEAVE = 675, + WM_WTSSESSION_CHANGE = 689, + WM_TABLET_DEFBASE = 704, + WM_TABLET_ADDED = 712, + WM_TABLET_DELETED = 713, + WM_TABLET_FLICK = 715, + WM_TABLET_QUERYSYSTEMGESTURESTATUS = 716, + WM_CUT = 768, + WM_COPY = 769, + WM_PASTE = 770, + WM_CLEAR = 771, + WM_UNDO = 772, + WM_RENDERFORMAT = 773, + WM_RENDERALLFORMATS = 774, + WM_DESTROYCLIPBOARD = 775, + WM_DRAWCLIPBOARD = 776, + WM_PAINTCLIPBOARD = 777, + WM_VSCROLLCLIPBOARD = 778, + WM_SIZECLIPBOARD = 779, + WM_ASKCBFORMATNAME = 780, + WM_CHANGECBCHAIN = 781, + WM_HSCROLLCLIPBOARD = 782, + WM_QUERYNEWPALETTE = 783, + WM_PALETTEISCHANGING = 784, + WM_PALETTECHANGED = 785, + WM_HOTKEY = 786, + WM_PRINT = 791, + WM_PRINTCLIENT = 792, + WM_APPCOMMAND = 793, + WM_THEMECHANGED = 794, + WM_DWMCOMPOSITIONCHANGED = 798, + WM_DWMNCRENDERINGCHANGED = 799, + WM_DWMCOLORIZATIONCOLORCHANGED = 800, + WM_DWMWINDOWMAXIMIZEDCHANGE = 801, + WM_DWMSENDICONICTHUMBNAIL = 803, + WM_DWMSENDICONICLIVEPREVIEWBITMAP = 806, + WM_HANDHELDFIRST = 856, + WM_HANDHELDLAST = 863, + WM_AFXFIRST = 864, + WM_AFXLAST = 895, + WM_PENWINFIRST = 896, + WM_PENWINLAST = 911, + WM_USER = 1024, + WM_APP = 32768, + } + + public enum WindowSizingMessage + { + WMSZ_BOTTOM = 6, + WMSZ_BOTTOMLEFT = 7, + WMSZ_BOTTOMRIGHT = 8, + WMSZ_LEFT = 1, + WMSZ_RIGHT = 2, + WMSZ_TOP = 3, + WMSZ_TOPLEFT = 4, + WMSZ_TOPRIGHT = 5, + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/DefaultInterLayoutClient.cs b/Source/3rdparty/Dragablz/DefaultInterLayoutClient.cs new file mode 100644 index 0000000000..821fc20ef8 --- /dev/null +++ b/Source/3rdparty/Dragablz/DefaultInterLayoutClient.cs @@ -0,0 +1,48 @@ +using System; +using System.Runtime.ConstrainedExecution; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; + +namespace Dragablz +{ + /// + /// Provides a simple implementation of , but only really useful if + /// instances are specified in XAML. If you are binding via ItemsSource then + /// you most likely want to create your own implementation of . + /// + public class DefaultInterLayoutClient : IInterLayoutClient + { + public INewTabHost GetNewHost(object partition, TabablzControl source) + { + var tabablzControl = new TabablzControl { DataContext = source.DataContext }; + + Clone(source, tabablzControl); + + if (source.InterTabController == null) + throw new InvalidOperationException("Source tab does not have an InterTabCOntroller set. Ensure this is set on initial, and subsequently generated tab controls."); + + var newInterTabController = new InterTabController + { + Partition = source.InterTabController.Partition + }; + Clone(source.InterTabController, newInterTabController); + tabablzControl.SetCurrentValue(TabablzControl.InterTabControllerProperty, newInterTabController); + + return new NewTabHost(tabablzControl, tabablzControl); + } + + private static void Clone(DependencyObject from, DependencyObject to) + { + var localValueEnumerator = from.GetLocalValueEnumerator(); + while (localValueEnumerator.MoveNext()) + { + if (localValueEnumerator.Current.Property.ReadOnly || + localValueEnumerator.Current.Value is FrameworkElement) continue; + + if (!(localValueEnumerator.Current.Value is BindingExpressionBase)) + to.SetCurrentValue(localValueEnumerator.Current.Property, localValueEnumerator.Current.Value); + } + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/DefaultInterTabClient.cs b/Source/3rdparty/Dragablz/DefaultInterTabClient.cs new file mode 100644 index 0000000000..a9602a40d8 --- /dev/null +++ b/Source/3rdparty/Dragablz/DefaultInterTabClient.cs @@ -0,0 +1,34 @@ +using System; +using System.Linq; +using System.Windows; +using System.Windows.Threading; +using Dragablz.Core; + +namespace Dragablz +{ + public class DefaultInterTabClient : IInterTabClient + { + public virtual INewTabHost GetNewHost(IInterTabClient interTabClient, object partition, TabablzControl source) + { + if (source == null) throw new ArgumentNullException("source"); + var sourceWindow = Window.GetWindow(source); + if (sourceWindow == null) throw new ApplicationException("Unable to ascertain source window."); + var newWindow = (Window)Activator.CreateInstance(sourceWindow.GetType()); + + newWindow.Dispatcher.Invoke(new Action(() => { }), DispatcherPriority.DataBind); + + var newTabablzControl = newWindow.LogicalTreeDepthFirstTraversal().OfType().FirstOrDefault(); + if (newTabablzControl == null) throw new ApplicationException("Unable to ascertain tab control."); + + if (newTabablzControl.ItemsSource == null) + newTabablzControl.Items.Clear(); + + return new NewTabHost(newWindow, newTabablzControl); + } + + public virtual TabEmptiedResponse TabEmptiedHandler(TabablzControl tabControl, Window window) + { + return TabEmptiedResponse.CloseWindowOrLayoutBranch; + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Dockablz/Branch.cs b/Source/3rdparty/Dragablz/Dockablz/Branch.cs new file mode 100644 index 0000000000..68bb38c986 --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/Branch.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Markup; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace Dragablz.Dockablz +{ + [TemplatePart(Name = FirstContentPresenterPartName, Type = typeof(ContentPresenter))] + [TemplatePart(Name = SecondContentPresenterPartName, Type = typeof(ContentPresenter))] + public class Branch : Control + { + private const string FirstContentPresenterPartName = "PART_FirstContentPresenter"; + private const string SecondContentPresenterPartName = "PART_SecondContentPresenter"; + + static Branch() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(Branch), new FrameworkPropertyMetadata(typeof(Branch))); + } + + public static readonly DependencyProperty OrientationProperty = DependencyProperty.Register( + "Orientation", typeof(Orientation), typeof(Branch), new PropertyMetadata(default(Orientation))); + + public Orientation Orientation + { + get { return (Orientation)GetValue(OrientationProperty); } + set { SetValue(OrientationProperty, value); } + } + + public static readonly DependencyProperty FirstItemProperty = DependencyProperty.Register( + "FirstItem", typeof(object), typeof(Branch), new PropertyMetadata(default(object))); + + public object FirstItem + { + get { return GetValue(FirstItemProperty); } + set { SetValue(FirstItemProperty, value); } + } + + public static readonly DependencyProperty FirstItemLengthProperty = DependencyProperty.Register( + "FirstItemLength", typeof(GridLength), typeof(Branch), new FrameworkPropertyMetadata(new GridLength(0.49999, GridUnitType.Star), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + + public GridLength FirstItemLength + { + get { return (GridLength)GetValue(FirstItemLengthProperty); } + set { SetValue(FirstItemLengthProperty, value); } + } + + public static readonly DependencyProperty SecondItemProperty = DependencyProperty.Register( + "SecondItem", typeof(object), typeof(Branch), new PropertyMetadata(default(object))); + + public object SecondItem + { + get { return GetValue(SecondItemProperty); } + set { SetValue(SecondItemProperty, value); } + } + + public static readonly DependencyProperty SecondItemLengthProperty = DependencyProperty.Register( + "SecondItemLength", typeof(GridLength), typeof(Branch), new FrameworkPropertyMetadata(new GridLength(0.50001, GridUnitType.Star), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + + public GridLength SecondItemLength + { + get { return (GridLength)GetValue(SecondItemLengthProperty); } + set { SetValue(SecondItemLengthProperty, value); } + } + + /// + /// Gets the proportional size of the first item, between 0 and 1, where 1 would represent the entire size of the branch. + /// + /// + public double GetFirstProportion() + { + return (1 / (FirstItemLength.Value + SecondItemLength.Value)) * FirstItemLength.Value; + } + + public override void OnApplyTemplate() + { + base.OnApplyTemplate(); + + FirstContentPresenter = GetTemplateChild(FirstContentPresenterPartName) as ContentPresenter; + SecondContentPresenter = GetTemplateChild(SecondContentPresenterPartName) as ContentPresenter; + } + + internal ContentPresenter FirstContentPresenter { get; private set; } + internal ContentPresenter SecondContentPresenter { get; private set; } + } +} diff --git a/Source/3rdparty/Dragablz/Dockablz/BranchAccessor.cs b/Source/3rdparty/Dragablz/Dockablz/BranchAccessor.cs new file mode 100644 index 0000000000..a8c58c959b --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/BranchAccessor.cs @@ -0,0 +1,129 @@ +using System; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using Dragablz.Core; + +namespace Dragablz.Dockablz +{ + public class BranchAccessor + { + private readonly Branch _branch; + private readonly BranchAccessor _firstItemBranchAccessor; + private readonly BranchAccessor _secondItemBranchAccessor; + private readonly TabablzControl _firstItemTabablzControl; + private readonly TabablzControl _secondItemTabablzControl; + + public BranchAccessor(Branch branch) + { + if (branch == null) throw new ArgumentNullException("branch"); + + _branch = branch; + + var firstChildBranch = branch.FirstItem as Branch; + if (firstChildBranch != null) + _firstItemBranchAccessor = new BranchAccessor(firstChildBranch); + else + _firstItemTabablzControl = FindTabablzControl(branch.FirstItem, branch.FirstContentPresenter); + + var secondChildBranch = branch.SecondItem as Branch; + if (secondChildBranch != null) + _secondItemBranchAccessor = new BranchAccessor(secondChildBranch); + else + _secondItemTabablzControl = FindTabablzControl(branch.SecondItem, branch.SecondContentPresenter); + } + + private static TabablzControl FindTabablzControl(object item, DependencyObject contentPresenter) + { + var result = item as TabablzControl; + return result ?? contentPresenter.VisualTreeDepthFirstTraversal().OfType().FirstOrDefault(); + } + + public Branch Branch + { + get { return _branch; } + } + + public BranchAccessor FirstItemBranchAccessor + { + get { return _firstItemBranchAccessor; } + } + + public BranchAccessor SecondItemBranchAccessor + { + get { return _secondItemBranchAccessor; } + } + + public TabablzControl FirstItemTabablzControl + { + get { return _firstItemTabablzControl; } + } + + public TabablzControl SecondItemTabablzControl + { + get { return _secondItemTabablzControl; } + } + + /// + /// Visits the content of the first or second side of a branch, according to its content type. No more than one of the provided + /// callbacks will be called. + /// + /// + /// + /// + /// + /// + public BranchAccessor Visit(BranchItem childItem, + Action childBranchVisitor = null, + Action childTabablzControlVisitor = null, + Action childContentVisitor = null) + { + Func branchGetter; + Func tabGetter; + Func contentGetter; + + switch (childItem) + { + case BranchItem.First: + branchGetter = () => _firstItemBranchAccessor; + tabGetter = () => _firstItemTabablzControl; + contentGetter = () => _branch.FirstItem; + break; + case BranchItem.Second: + branchGetter = () => _secondItemBranchAccessor; + tabGetter = () => _secondItemTabablzControl; + contentGetter = () => _branch.SecondItem; + break; + default: + throw new ArgumentOutOfRangeException("childItem"); + } + + var branchDescription = branchGetter(); + if (branchDescription != null) + { + if (childBranchVisitor != null) + childBranchVisitor(branchDescription); + return this; + } + + var tabablzControl = tabGetter(); + if (tabablzControl != null) + { + if (childTabablzControlVisitor != null) + childTabablzControlVisitor(tabablzControl); + + return this; + } + + if (childContentVisitor == null) return this; + + var content = contentGetter(); + if (content != null) + childContentVisitor(content); + + return this; + } + } +} diff --git a/Source/3rdparty/Dragablz/Dockablz/BranchItem.cs b/Source/3rdparty/Dragablz/Dockablz/BranchItem.cs new file mode 100644 index 0000000000..946e75bd0f --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/BranchItem.cs @@ -0,0 +1,8 @@ +namespace Dragablz.Dockablz +{ + public enum BranchItem + { + First, + Second + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Dockablz/BranchResult.cs b/Source/3rdparty/Dragablz/Dockablz/BranchResult.cs new file mode 100644 index 0000000000..50a6242bed --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/BranchResult.cs @@ -0,0 +1,35 @@ +using System; + +namespace Dragablz.Dockablz +{ + public class BranchResult + { + private readonly Branch _branch; + private readonly TabablzControl _tabablzControl; + + public BranchResult(Branch branch, TabablzControl tabablzControl) + { + if (branch == null) throw new ArgumentNullException("branch"); + if (tabablzControl == null) throw new ArgumentNullException("tabablzControl"); + + _branch = branch; + _tabablzControl = tabablzControl; + } + + /// + /// The new branch. + /// + public Branch Branch + { + get { return _branch; } + } + + /// + /// The new tab control. + /// + public TabablzControl TabablzControl + { + get { return _tabablzControl; } + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Dockablz/CouldBeHeaderedStyleSelector.cs b/Source/3rdparty/Dragablz/Dockablz/CouldBeHeaderedStyleSelector.cs new file mode 100644 index 0000000000..5d70500584 --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/CouldBeHeaderedStyleSelector.cs @@ -0,0 +1,19 @@ +using System.Windows; +using System.Windows.Controls; + +namespace Dragablz.Dockablz +{ + public class CouldBeHeaderedStyleSelector : StyleSelector + { + public Style NonHeaderedStyle { get; set; } + + public Style HeaderedStyle { get; set; } + + public override Style SelectStyle(object item, DependencyObject container) + { + return container is HeaderedDragablzItem || container is HeaderedContentControl + ? HeaderedStyle + : NonHeaderedStyle; + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Dockablz/DropZone.cs b/Source/3rdparty/Dragablz/Dockablz/DropZone.cs new file mode 100644 index 0000000000..3ab20421b1 --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/DropZone.cs @@ -0,0 +1,37 @@ +using System.Windows; +using System.Windows.Controls; + +namespace Dragablz.Dockablz +{ + public class DropZone : Control + { + static DropZone() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(DropZone), new FrameworkPropertyMetadata(typeof(DropZone))); + } + + public static readonly DependencyProperty LocationProperty = DependencyProperty.Register( + "Location", typeof(DropZoneLocation), typeof(DropZone), new PropertyMetadata(default(DropZoneLocation))); + + public DropZoneLocation Location + { + get { return (DropZoneLocation)GetValue(LocationProperty); } + set { SetValue(LocationProperty, value); } + } + + private static readonly DependencyPropertyKey IsOfferedPropertyKey = + DependencyProperty.RegisterReadOnly( + "IsOffered", typeof(bool), typeof(DropZone), + new PropertyMetadata(default(bool))); + + public static readonly DependencyProperty IsOfferedProperty = + IsOfferedPropertyKey.DependencyProperty; + + public bool IsOffered + { + get { return (bool)GetValue(IsOfferedProperty); } + internal set { SetValue(IsOfferedPropertyKey, value); } + } + + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Dockablz/DropZoneLocation.cs b/Source/3rdparty/Dragablz/Dockablz/DropZoneLocation.cs new file mode 100644 index 0000000000..2c5c26c174 --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/DropZoneLocation.cs @@ -0,0 +1,11 @@ +namespace Dragablz.Dockablz +{ + public enum DropZoneLocation + { + Top, + Right, + Bottom, + Left, + Floating + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Dockablz/Extensions.cs b/Source/3rdparty/Dragablz/Dockablz/Extensions.cs new file mode 100644 index 0000000000..b7279856cb --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/Extensions.cs @@ -0,0 +1,86 @@ +using System; +using System.Runtime.Serialization; + +namespace Dragablz.Dockablz +{ + public static class Extensions + { + /// + /// Begin a query of layout content, returning an accessor for examining the children. + /// + /// + /// + public static LayoutAccessor Query(this Layout layout) + { + if (layout == null) throw new ArgumentNullException("layout"); + + return new LayoutAccessor(layout); + } + + /// + /// Helper method for which allows a context to be passed through. + /// + /// + /// + /// + /// + /// + /// + /// + public static LayoutAccessor Visit( + this LayoutAccessor layoutAccessor, + TContext context, + Action branchVisitor = null, + Action tabablzControlVisitor = null, + Action contentVisitor = null) + { + if (layoutAccessor == null) throw new ArgumentNullException("layoutAccessor"); + + layoutAccessor.Visit( + WrapVisitor(context, branchVisitor), + WrapVisitor(context, tabablzControlVisitor), + WrapVisitor(context, contentVisitor) + ); + + return layoutAccessor; + } + + /// + /// Helper method for which allows a context to be passed through. + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static BranchAccessor Visit( + this BranchAccessor branchAccessor, + TContext context, + BranchItem childItem, + Action branchVisitor = null, + Action tabablzControlVisitor = null, + Action contentVisitor = null) + { + if (branchAccessor == null) throw new ArgumentNullException("branchAccessor"); + + branchAccessor.Visit( + childItem, + WrapVisitor(context, branchVisitor), + WrapVisitor(context, tabablzControlVisitor), + WrapVisitor(context, contentVisitor) + ); + + return branchAccessor; + } + + private static Action WrapVisitor(TContext context, Action visitor) + { + if (visitor == null) return null; + + return a => visitor(context, a); + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Dockablz/Finder.cs b/Source/3rdparty/Dragablz/Dockablz/Finder.cs new file mode 100644 index 0000000000..c7d5056647 --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/Finder.cs @@ -0,0 +1,53 @@ +using System; + +namespace Dragablz.Dockablz +{ + internal static class Finder + { + internal static LocationReport Find(TabablzControl tabablzControl) + { + if (tabablzControl == null) throw new ArgumentNullException("tabablzControl"); + + var locationReportBuilder = new LocationReportBuilder(tabablzControl); + + foreach (var loadedInstance in Layout.GetLoadedInstances()) + { + locationReportBuilder.CurrentLayout = loadedInstance; + + loadedInstance.Query().Visit( + locationReportBuilder, + BranchVisitor, + TabablzControlVisitor + ); + + if (locationReportBuilder.IsFound) + break; + } + + if (!locationReportBuilder.IsFound) + throw new LocationReportException("Instance not within any layout."); + + return locationReportBuilder.ToLocationReport(); + } + + private static void BranchVisitor(LocationReportBuilder locationReportBuilder, BranchAccessor branchAccessor) + { + if (Equals(branchAccessor.FirstItemTabablzControl, locationReportBuilder.TargetTabablzControl)) + locationReportBuilder.MarkFound(branchAccessor.Branch, false); + else if (Equals(branchAccessor.SecondItemTabablzControl, locationReportBuilder.TargetTabablzControl)) + locationReportBuilder.MarkFound(branchAccessor.Branch, true); + else + { + branchAccessor.Visit(BranchItem.First, ba => BranchVisitor(locationReportBuilder, ba)); + if (locationReportBuilder.IsFound) return; + branchAccessor.Visit(BranchItem.Second, ba => BranchVisitor(locationReportBuilder, ba)); + } + } + + private static void TabablzControlVisitor(LocationReportBuilder locationReportBuilder, TabablzControl tabablzControl) + { + if (Equals(tabablzControl, locationReportBuilder.TargetTabablzControl)) + locationReportBuilder.MarkFound(); + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Dockablz/FloatRequestedEvent.cs b/Source/3rdparty/Dragablz/Dockablz/FloatRequestedEvent.cs new file mode 100644 index 0000000000..6e73a0be04 --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/FloatRequestedEvent.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; + +namespace Dragablz.Dockablz +{ + public delegate void FloatRequestedEventHandler(object sender, FloatRequestedEventArgs e); + + public class FloatRequestedEventArgs : DragablzItemEventArgs + { + public FloatRequestedEventArgs(RoutedEvent routedEvent, object source, DragablzItem dragablzItem) + : base(routedEvent, source, dragablzItem) + { } + + public FloatRequestedEventArgs(RoutedEvent routedEvent, DragablzItem dragablzItem) + : base(routedEvent, dragablzItem) + { } + } +} diff --git a/Source/3rdparty/Dragablz/Dockablz/FloatTransfer.cs b/Source/3rdparty/Dragablz/Dockablz/FloatTransfer.cs new file mode 100644 index 0000000000..a3a155b6e2 --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/FloatTransfer.cs @@ -0,0 +1,46 @@ +using System; + +namespace Dragablz.Dockablz +{ + internal class FloatTransfer + { + private readonly double _width; + private readonly double _height; + private readonly object _content; + + public FloatTransfer(double width, double height, object content) + { + if (content == null) throw new ArgumentNullException("content"); + + _width = width; + _height = height; + _content = content; + } + + public static FloatTransfer TakeSnapshot(DragablzItem dragablzItem, TabablzControl sourceTabControl) + { + if (dragablzItem == null) throw new ArgumentNullException("dragablzItem"); + + return new FloatTransfer(sourceTabControl.ActualWidth, sourceTabControl.ActualHeight, dragablzItem.UnderlyingContent ?? dragablzItem.Content ?? dragablzItem); + } + + [Obsolete] + //TODO width and height transfer obsolete + public double Width + { + get { return _width; } + } + + [Obsolete] + //TODO width and height transfer obsolete + public double Height + { + get { return _height; } + } + + public object Content + { + get { return _content; } + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Dockablz/FloatingItemSnapShot.cs b/Source/3rdparty/Dragablz/Dockablz/FloatingItemSnapShot.cs new file mode 100644 index 0000000000..1c2c7c19aa --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/FloatingItemSnapShot.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; + +namespace Dragablz.Dockablz +{ + /// + /// experimentational. might have to puish this back to mvvm only + /// + internal class FloatingItemSnapShot + { + private readonly object _content; + private readonly Rect _location; + private readonly int _zIndex; + private readonly WindowState _state; + + public FloatingItemSnapShot(object content, Rect location, int zIndex, WindowState state) + { + if (content == null) throw new ArgumentNullException("content"); + + _content = content; + _location = location; + _zIndex = zIndex; + _state = state; + } + + public static FloatingItemSnapShot Take(DragablzItem dragablzItem) + { + if (dragablzItem == null) throw new ArgumentNullException("dragablzItem"); + + return new FloatingItemSnapShot( + dragablzItem.Content, + new Rect(dragablzItem.X, dragablzItem.Y, dragablzItem.ActualWidth, dragablzItem.ActualHeight), + Panel.GetZIndex(dragablzItem), + Layout.GetFloatingItemState(dragablzItem)); + } + + public void Apply(DragablzItem dragablzItem) + { + if (dragablzItem == null) throw new ArgumentNullException("dragablzItem"); + + dragablzItem.SetCurrentValue(DragablzItem.XProperty, Location.Left); + dragablzItem.SetCurrentValue(DragablzItem.YProperty, Location.Top); + dragablzItem.SetCurrentValue(FrameworkElement.WidthProperty, Location.Width); + dragablzItem.SetCurrentValue(FrameworkElement.HeightProperty, Location.Height); + Layout.SetFloatingItemState(dragablzItem, State); + Panel.SetZIndex(dragablzItem, ZIndex); + } + + public object Content + { + get { return _content; } + } + + public Rect Location + { + get { return _location; } + } + + public int ZIndex + { + get { return _zIndex; } + } + + public WindowState State + { + get { return _state; } + } + } +} diff --git a/Source/3rdparty/Dragablz/Dockablz/Layout.cs b/Source/3rdparty/Dragablz/Dockablz/Layout.cs new file mode 100644 index 0000000000..41dc504fd5 --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/Layout.cs @@ -0,0 +1,999 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Data; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Threading; +using Dragablz.Core; + +namespace Dragablz.Dockablz +{ + public delegate void ClosingFloatingItemCallback(ItemActionCallbackArgs args); + + [TemplatePart(Name = TopDropZonePartName, Type = typeof(DropZone))] + [TemplatePart(Name = RightDropZonePartName, Type = typeof(DropZone))] + [TemplatePart(Name = BottomDropZonePartName, Type = typeof(DropZone))] + [TemplatePart(Name = LeftDropZonePartName, Type = typeof(DropZone))] + [TemplatePart(Name = FloatingDropZonePartName, Type = typeof(DropZone))] + [TemplatePart(Name = FloatingContentPresenterPartName, Type = typeof(ContentPresenter))] + public class Layout : ContentControl + { + private static readonly HashSet LoadedLayouts = new HashSet(); + private const string TopDropZonePartName = "PART_TopDropZone"; + private const string RightDropZonePartName = "PART_RightDropZone"; + private const string BottomDropZonePartName = "PART_BottomDropZone"; + private const string LeftDropZonePartName = "PART_LeftDropZone"; + private const string FloatingDropZonePartName = "PART_FloatDropZone"; + private const string FloatingContentPresenterPartName = "PART_FloatContentPresenter"; + + private readonly IDictionary _dropZones = new Dictionary(); + private static Tuple _currentlyOfferedDropZone; + + public static RoutedCommand UnfloatItemCommand = new RoutedCommand(); + public static RoutedCommand MaximiseFloatingItem = new RoutedCommand(); + public static RoutedCommand RestoreFloatingItem = new RoutedCommand(); + public static RoutedCommand CloseFloatingItem = new RoutedCommand(); + public static RoutedCommand TileFloatingItemsCommand = new RoutedCommand(); + public static RoutedCommand TileFloatingItemsVerticallyCommand = new RoutedCommand(); + public static RoutedCommand TileFloatingItemsHorizontallyCommand = new RoutedCommand(); + + private readonly DragablzItemsControl _floatingItems; + private static bool _isDragOpWireUpPending; + private FloatTransfer _floatTransfer; + + static Layout() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(Layout), new FrameworkPropertyMetadata(typeof(Layout))); + + EventManager.RegisterClassHandler(typeof(DragablzItem), DragablzItem.DragStarted, new DragablzDragStartedEventHandler(ItemDragStarted)); + EventManager.RegisterClassHandler(typeof(DragablzItem), DragablzItem.PreviewDragDelta, new DragablzDragDeltaEventHandler(PreviewItemDragDelta), true); + EventManager.RegisterClassHandler(typeof(DragablzItem), DragablzItem.DragCompleted, new DragablzDragCompletedEventHandler(ItemDragCompleted)); + } + + public Layout() + { + Loaded += (sender, args) => + { + LoadedLayouts.Add(this); + MarkTopLeftItem(this); + }; + Unloaded += (sender, args) => LoadedLayouts.Remove(this); + + CommandBindings.Add(new CommandBinding(UnfloatItemCommand, UnfloatExecuted, CanExecuteUnfloat)); + CommandBindings.Add(new CommandBinding(MaximiseFloatingItem, MaximiseFloatingItemExecuted, CanExecuteMaximiseFloatingItem)); + CommandBindings.Add(new CommandBinding(CloseFloatingItem, CloseFloatingItemExecuted, CanExecuteCloseFloatingItem)); + CommandBindings.Add(new CommandBinding(RestoreFloatingItem, RestoreFloatingItemExecuted, CanExecuteRestoreFloatingItem)); + CommandBindings.Add(new CommandBinding(TileFloatingItemsCommand, TileFloatingItemsExecuted)); + CommandBindings.Add(new CommandBinding(TileFloatingItemsCommand, TileFloatingItemsExecuted)); + CommandBindings.Add(new CommandBinding(TileFloatingItemsVerticallyCommand, TileFloatingItemsVerticallyExecuted)); + CommandBindings.Add(new CommandBinding(TileFloatingItemsHorizontallyCommand, TileFloatingItemsHorizontallyExecuted)); + + //TODO bad bad behaviour. Pick up this from the template. + _floatingItems = new DragablzItemsControl + { + ContainerCustomisations = new ContainerCustomisations( + GetFloatingContainerForItemOverride, + PrepareFloatingContainerForItemOverride, + ClearingFloatingContainerForItemOverride) + }; + + var floatingItemsSourceBinding = new Binding("FloatingItemsSource") { Source = this }; + _floatingItems.SetBinding(ItemsControl.ItemsSourceProperty, floatingItemsSourceBinding); + var floatingItemsControlStyleBinding = new Binding("FloatingItemsControlStyle") { Source = this }; + _floatingItems.SetBinding(StyleProperty, floatingItemsControlStyleBinding); + var floatingItemTemplateBinding = new Binding("FloatingItemTemplate") { Source = this }; + _floatingItems.SetBinding(ItemsControl.ItemTemplateProperty, floatingItemTemplateBinding); + var floatingItemTemplateSelectorBinding = new Binding("FloatingItemTemplateSelector") { Source = this }; + _floatingItems.SetBinding(ItemsControl.ItemTemplateSelectorProperty, floatingItemTemplateSelectorBinding); + var floatingItemContainerStyeBinding = new Binding("FloatingItemContainerStyle") { Source = this }; + _floatingItems.SetBinding(ItemsControl.ItemContainerStyleProperty, floatingItemContainerStyeBinding); + var floatingItemContainerStyleSelectorBinding = new Binding("FloatingItemContainerStyleSelector") { Source = this }; + _floatingItems.SetBinding(ItemsControl.ItemContainerStyleSelectorProperty, floatingItemContainerStyleSelectorBinding); + } + + /// + /// Helper method to get all the currently loaded layouts. + /// + /// + public static IEnumerable GetLoadedInstances() + { + return LoadedLayouts.ToList(); + } + + /// + /// Finds the location of a tab control withing a layout. + /// + /// + /// + public static LocationReport Find(TabablzControl tabablzControl) + { + if (tabablzControl == null) throw new ArgumentNullException("tabablzControl"); + + return Finder.Find(tabablzControl); + } + + /// + /// Creates a split in a layout, at the location of a specified . + /// + /// + /// Tab control to be split. + /// Direction of split. + /// Set to true to make the current tab control push into the right hand or bottom of the split. + /// The tab control to be split must be hosted in a layout control. + public static BranchResult Branch(TabablzControl tabablzControl, Orientation orientation, bool makeSecond) + { + return Branch(tabablzControl, orientation, makeSecond, .5); + } + + /// + /// Creates a split in a layout, at the location of a specified . + /// + /// + /// Tab control to be split. + /// Direction of split. + /// Set to true to make the current tab control push into the right hand or bottom of the split. + /// Sets the proportion of the first tab control, with 0.5 being 50% of available space. + /// The tab control to be split must be hosted in a layout control. should be set (typically via XAML). + public static BranchResult Branch(TabablzControl tabablzControl, Orientation orientation, bool makeSecond, double firstItemProportion) + { + return Branch(tabablzControl, null, orientation, makeSecond, firstItemProportion); + } + + /// + /// Creates a split in a layout, at the location of a specified . + /// + /// + /// Tab control to be split. + /// New sibling tab control (otherwise will be used). + /// Direction of split. + /// Set to true to make the current tab control push into the right hand or bottom of the split. + /// Sets the proportion of the first tab control, with 0.5 being 50% of available space. + /// The tab control to be split must be hosted in a layout control. + public static BranchResult Branch(TabablzControl tabablzControl, TabablzControl newSiblingTabablzControl, Orientation orientation, bool makeCurrentSecond, + double firstItemProportion) + { + if (firstItemProportion < 0.0 || firstItemProportion > 1.0) throw new ArgumentOutOfRangeException("firstItemProportion", "Must be >= 0.0 and <= 1.0"); + + var locationReport = Find(tabablzControl); + + Action applier; + object existingContent; + if (!locationReport.IsLeaf) + { + existingContent = locationReport.RootLayout.Content; + applier = branch => locationReport.RootLayout.Content = branch; + } + else if (!locationReport.IsSecondLeaf) + { + existingContent = locationReport.ParentBranch.FirstItem; + applier = branch => locationReport.ParentBranch.FirstItem = branch; + } + else + { + existingContent = locationReport.ParentBranch.SecondItem; + applier = branch => locationReport.ParentBranch.SecondItem = branch; + } + + var selectedItem = tabablzControl.SelectedItem; + var branchResult = Branch(orientation, firstItemProportion, makeCurrentSecond, locationReport.RootLayout.BranchTemplate, newSiblingTabablzControl, existingContent, applier); + tabablzControl.SelectedItem = selectedItem; + tabablzControl.Dispatcher.BeginInvoke(new Action(() => + { + tabablzControl.SetCurrentValue(Selector.SelectedItemProperty, selectedItem); + MarkTopLeftItem(locationReport.RootLayout); + }), + DispatcherPriority.Loaded); + + return branchResult; + } + + // Add parition as dependency property + public static readonly DependencyProperty PartitionProperty = DependencyProperty.Register( + "Partition", typeof(object), typeof(Layout), new PropertyMetadata(default(object))); + + /// + /// Use in conjuction with the on a + /// to isolate drag and drop spaces/control instances. + /// + public object Partition + { + get { return (object)GetValue(PartitionProperty); } + set { SetValue(PartitionProperty, value); } + } + + /// + /// Use in conjuction with the on a + /// to isolate drag and drop spaces/control instances. + /// + //public string Partition { get; set; } + + public static readonly DependencyProperty InterLayoutClientProperty = DependencyProperty.Register( + "InterLayoutClient", typeof(IInterLayoutClient), typeof(Layout), new PropertyMetadata(new DefaultInterLayoutClient())); + + public IInterLayoutClient InterLayoutClient + { + get { return (IInterLayoutClient)GetValue(InterLayoutClientProperty); } + set { SetValue(InterLayoutClientProperty, value); } + } + + internal static bool IsContainedWithinBranch(DependencyObject dependencyObject) + { + do + { + dependencyObject = VisualTreeHelper.GetParent(dependencyObject); + if (dependencyObject is Branch) + return true; + } while (dependencyObject != null); + return false; + } + + private static readonly DependencyPropertyKey IsParticipatingInDragPropertyKey = + DependencyProperty.RegisterReadOnly( + "IsParticipatingInDrag", typeof(bool), typeof(Layout), + new PropertyMetadata(default(bool))); + + public static readonly DependencyProperty IsParticipatingInDragProperty = + IsParticipatingInDragPropertyKey.DependencyProperty; + + public bool IsParticipatingInDrag + { + get { return (bool)GetValue(IsParticipatingInDragProperty); } + private set { SetValue(IsParticipatingInDragPropertyKey, value); } + } + + public static readonly DependencyProperty BranchTemplateProperty = DependencyProperty.Register( + "BranchTemplate", typeof(DataTemplate), typeof(Layout), new PropertyMetadata(default(DataTemplate))); + + public DataTemplate BranchTemplate + { + get { return (DataTemplate)GetValue(BranchTemplateProperty); } + set { SetValue(BranchTemplateProperty, value); } + } + + public static readonly DependencyProperty IsFloatDropZoneEnabledProperty = DependencyProperty.Register( + "IsFloatDropZoneEnabled", typeof(bool), typeof(Layout), new PropertyMetadata(default(bool))); + + public bool IsFloatDropZoneEnabled + { + get { return (bool)GetValue(IsFloatDropZoneEnabledProperty); } + set { SetValue(IsFloatDropZoneEnabledProperty, value); } + } + + /// + /// Defines a margin for the container which hosts all floating items. + /// + public static readonly DependencyProperty FloatingItemsContainerMarginProperty = DependencyProperty.Register( + "FloatingItemsContainerMargin", typeof(Thickness), typeof(Layout), new PropertyMetadata(default(Thickness))); + + /// + /// Defines a margin for the container which hosts all floating items. + /// + public Thickness FloatingItemsContainerMargin + { + get { return (Thickness)GetValue(FloatingItemsContainerMarginProperty); } + set { SetValue(FloatingItemsContainerMarginProperty, value); } + } + + /// + /// Floating items, such as tool/MDI windows, which will sit above the . + /// + public ItemCollection FloatingItems + { + get { return _floatingItems.Items; } + } + + public static readonly DependencyProperty FloatingItemsSourceProperty = DependencyProperty.Register( + "FloatingItemsSource", typeof(IEnumerable), typeof(Layout), new PropertyMetadata(default(IEnumerable))); + + /// + /// Floating items, such as tool/MDI windows, which will sit above the . + /// + public IEnumerable FloatingItemsSource + { + get { return (IEnumerable)GetValue(FloatingItemsSourceProperty); } + set { SetValue(FloatingItemsSourceProperty, value); } + } + + public static readonly DependencyProperty FloatingItemsControlStyleProperty = DependencyProperty.Register( + "FloatingItemsControlStyle", typeof(Style), typeof(Layout), new PropertyMetadata((Style)null)); + + /// + /// The style to be applied to the which is used to display floating items. + /// In most scenarios it should be OK to leave this to that applied by the default style. + /// + public Style FloatingItemsControlStyle + { + get { return (Style)GetValue(FloatingItemsControlStyleProperty); } + set { SetValue(FloatingItemsControlStyleProperty, value); } + } + + public static readonly DependencyProperty FloatingItemContainerStyleProperty = DependencyProperty.Register( + "FloatingItemContainerStyle", typeof(Style), typeof(Layout), new PropertyMetadata(default(Style))); + + public Style FloatingItemContainerStyle + { + get { return (Style)GetValue(FloatingItemContainerStyleProperty); } + set { SetValue(FloatingItemContainerStyleProperty, value); } + } + + public static readonly DependencyProperty FloatingItemContainerStyleSelectorProperty = DependencyProperty.Register( + "FloatingItemContainerStyleSelector", typeof(StyleSelector), typeof(Layout), new PropertyMetadata(new CouldBeHeaderedStyleSelector())); + + public StyleSelector FloatingItemContainerStyleSelector + { + get { return (StyleSelector)GetValue(FloatingItemContainerStyleSelectorProperty); } + set { SetValue(FloatingItemContainerStyleSelectorProperty, value); } + } + + public static readonly DependencyProperty FloatingItemTemplateProperty = DependencyProperty.Register( + "FloatingItemTemplate", typeof(DataTemplate), typeof(Layout), new PropertyMetadata(default(DataTemplate))); + + public DataTemplate FloatingItemTemplate + { + get { return (DataTemplate)GetValue(FloatingItemTemplateProperty); } + set { SetValue(FloatingItemTemplateProperty, value); } + } + + public static readonly DependencyProperty FloatingItemTemplateSelectorProperty = DependencyProperty.Register( + "FloatingItemTemplateSelector", typeof(DataTemplateSelector), typeof(Layout), new PropertyMetadata(default(DataTemplateSelector))); + + public DataTemplateSelector FloatingItemTemplateSelector + { + get { return (DataTemplateSelector)GetValue(FloatingItemTemplateSelectorProperty); } + set { SetValue(FloatingItemTemplateSelectorProperty, value); } + } + + public static readonly DependencyProperty FloatingItemHeaderMemberPathProperty = DependencyProperty.Register( + "FloatingItemHeaderMemberPath", typeof(string), typeof(Layout), new PropertyMetadata(default(string))); + + public string FloatingItemHeaderMemberPath + { + get { return (string)GetValue(FloatingItemHeaderMemberPathProperty); } + set { SetValue(FloatingItemHeaderMemberPathProperty, value); } + } + + public static readonly DependencyProperty FloatingItemDisplayMemberPathProperty = DependencyProperty.Register( + "FloatingItemDisplayMemberPath", typeof(string), typeof(Layout), new PropertyMetadata(default(string))); + + public string FloatingItemDisplayMemberPath + { + get { return (string)GetValue(FloatingItemDisplayMemberPathProperty); } + set { SetValue(FloatingItemDisplayMemberPathProperty, value); } + } + + public static readonly DependencyProperty ClosingFloatingItemCallbackProperty = DependencyProperty.Register( + "ClosingFloatingItemCallback", typeof(ClosingFloatingItemCallback), typeof(Layout), new PropertyMetadata(default(ClosingFloatingItemCallback))); + + public ClosingFloatingItemCallback ClosingFloatingItemCallback + { + get { return (ClosingFloatingItemCallback)GetValue(ClosingFloatingItemCallbackProperty); } + set { SetValue(ClosingFloatingItemCallbackProperty, value); } + } + + public static readonly DependencyPropertyKey KeyIsFloatingInLayoutPropertyKey = DependencyProperty.RegisterAttachedReadOnly( + "IsFloatingInLayout", typeof(bool), typeof(Layout), new PropertyMetadata(default(bool))); + + private static void SetIsFloatingInLayout(DependencyObject element, bool value) + { + element.SetValue(KeyIsFloatingInLayoutPropertyKey, value); + } + + public static bool GetIsFloatingInLayout(DependencyObject element) + { + return (bool)element.GetValue(KeyIsFloatingInLayoutPropertyKey.DependencyProperty); + } + + private static readonly DependencyPropertyKey IsTopLeftItemPropertyKey = + DependencyProperty.RegisterReadOnly( + "IsTopLeftItem", typeof(bool), typeof(Layout), + new PropertyMetadata(default(bool))); + + /// + /// Indicates if an item/tab control within a layout is contained at the top most and left most branch item. + /// + public static readonly DependencyProperty IsTopLeftItemProperty = IsTopLeftItemPropertyKey.DependencyProperty; + + /// + /// Indicates if an item/tab control within a layout is contained at the top most and left most branch item. + /// + private static void SetIsTopLeftItem(DependencyObject element, bool value) + { + element.SetValue(IsTopLeftItemPropertyKey, value); + } + + /// + /// Indicates if an item/tab control within a layout is contained at the top most and left most branch item. + /// + public static bool GetIsTopLeftItem(DependencyObject element) + { + return (bool)element.GetValue(IsTopLeftItemProperty); + } + + /// When overridden in a derived class, is invoked whenever application code or internal processes call . + public override void OnApplyTemplate() + { + base.OnApplyTemplate(); + + var floatingItemsContentPresenter = GetTemplateChild(FloatingContentPresenterPartName) as ContentPresenter; + if (floatingItemsContentPresenter != null) + floatingItemsContentPresenter.Content = _floatingItems; + + _dropZones[DropZoneLocation.Top] = GetTemplateChild(TopDropZonePartName) as DropZone; + _dropZones[DropZoneLocation.Right] = GetTemplateChild(RightDropZonePartName) as DropZone; + _dropZones[DropZoneLocation.Bottom] = GetTemplateChild(BottomDropZonePartName) as DropZone; + _dropZones[DropZoneLocation.Left] = GetTemplateChild(LeftDropZonePartName) as DropZone; + _dropZones[DropZoneLocation.Floating] = GetTemplateChild(FloatingDropZonePartName) as DropZone; + } + + internal IEnumerable FloatingDragablzItems() + { + return _floatingItems.DragablzItems(); + } + + internal static void RestoreFloatingItemSnapShots(DependencyObject ancestor, IEnumerable floatingItemSnapShots) + { + var layouts = ancestor.VisualTreeDepthFirstTraversal().OfType().ToList(); + foreach (var floatingDragablzItem in layouts.SelectMany(l => l.FloatingDragablzItems())) + { + var itemSnapShots = floatingItemSnapShots as FloatingItemSnapShot[] ?? floatingItemSnapShots.ToArray(); + var floatingItemSnapShot = itemSnapShots.FirstOrDefault( + ss => ss.Content == floatingDragablzItem.Content); + if (floatingItemSnapShot != null) + floatingItemSnapShot.Apply(floatingDragablzItem); + } + } + + private static void ItemDragStarted(object sender, DragablzDragStartedEventArgs e) + { + //we wait until drag is in full flow so we know the partition has been setup by the owning tab control + _isDragOpWireUpPending = true; + } + + private static void SetupParticipatingLayouts(DragablzItem dragablzItem) + { + var sourceOfDragItemsControl = ItemsControl.ItemsControlFromItemContainer(dragablzItem) as DragablzItemsControl; + if (sourceOfDragItemsControl == null || sourceOfDragItemsControl.Items.Count != 1) return; + + var draggingWindow = Window.GetWindow(dragablzItem); + if (draggingWindow == null) return; + + foreach (var loadedLayout in LoadedLayouts.Where(l => + l.Partition?.ToString() == dragablzItem.PartitionAtDragStart && + !Equals(Window.GetWindow(l), draggingWindow))) + + { + loadedLayout.IsParticipatingInDrag = true; + } + } + + private void MonitorDropZones(Point cursorPos) + { + var myWindow = Window.GetWindow(this); + if (myWindow == null) return; + + foreach (var dropZone in _dropZones.Values.Where(dz => dz != null)) + { + var pointFromScreen = myWindow.PointFromScreen(cursorPos); + var pointRelativeToDropZone = myWindow.TranslatePoint(pointFromScreen, dropZone); + var inputHitTest = dropZone.InputHitTest(pointRelativeToDropZone); + //TODO better halding when windows are layered over each other + if (inputHitTest != null) + { + if (_currentlyOfferedDropZone != null) + _currentlyOfferedDropZone.Item2.IsOffered = false; + dropZone.IsOffered = true; + _currentlyOfferedDropZone = new Tuple(this, dropZone); + } + else + { + dropZone.IsOffered = false; + if (_currentlyOfferedDropZone != null && _currentlyOfferedDropZone.Item2 == dropZone) + _currentlyOfferedDropZone = null; + } + } + } + + private static bool TryGetSourceTabControl(DragablzItem dragablzItem, out TabablzControl tabablzControl) + { + var sourceOfDragItemsControl = ItemsControl.ItemsControlFromItemContainer(dragablzItem) as DragablzItemsControl; + if (sourceOfDragItemsControl == null) throw new ApplicationException("Unable to determine source items control."); + + tabablzControl = TabablzControl.GetOwnerOfHeaderItems(sourceOfDragItemsControl); + + return tabablzControl != null; + } + + private void Branch(DropZoneLocation location, DragablzItem sourceDragablzItem) + { + if (InterLayoutClient == null) + throw new InvalidOperationException("InterLayoutClient is not set."); + + var sourceOfDragItemsControl = ItemsControl.ItemsControlFromItemContainer(sourceDragablzItem) as DragablzItemsControl; + if (sourceOfDragItemsControl == null) throw new ApplicationException("Unable to determin source items control."); + + var sourceTabControl = TabablzControl.GetOwnerOfHeaderItems(sourceOfDragItemsControl); + if (sourceTabControl == null) throw new ApplicationException("Unable to determin source tab control."); + + var floatingItemSnapShots = sourceTabControl.VisualTreeDepthFirstTraversal() + .OfType() + .SelectMany(l => l.FloatingDragablzItems().Select(FloatingItemSnapShot.Take)) + .ToList(); + + var sourceItem = sourceOfDragItemsControl.ItemContainerGenerator.ItemFromContainer(sourceDragablzItem); + sourceTabControl.RemoveItem(sourceDragablzItem); + + var branchItem = new Branch + { + Orientation = (location == DropZoneLocation.Right || location == DropZoneLocation.Left) ? Orientation.Horizontal : Orientation.Vertical + }; + + object newContent; + if (BranchTemplate == null) + { + var newTabHost = InterLayoutClient.GetNewHost(Partition, sourceTabControl); + if (newTabHost == null) + throw new ApplicationException("InterLayoutClient did not provide a new tab host."); + newTabHost.TabablzControl.AddToSource(sourceItem); + newTabHost.TabablzControl.SelectedItem = sourceItem; + newContent = newTabHost.Container; + + Dispatcher.BeginInvoke(new Action(() => RestoreFloatingItemSnapShots(newTabHost.TabablzControl, floatingItemSnapShots)), DispatcherPriority.Loaded); + } + else + { + newContent = new ContentControl + { + Content = new object(), + ContentTemplate = BranchTemplate, + }; + ((ContentControl)newContent).Dispatcher.BeginInvoke(new Action(() => + { + //TODO might need to improve this a bit, make it a bit more declarative for complex trees + var newTabControl = ((ContentControl)newContent).VisualTreeDepthFirstTraversal().OfType().FirstOrDefault(); + if (newTabControl == null) return; + + newTabControl.DataContext = sourceTabControl.DataContext; + newTabControl.AddToSource(sourceItem); + newTabControl.SelectedItem = sourceItem; + Dispatcher.BeginInvoke(new Action(() => RestoreFloatingItemSnapShots(newTabControl, floatingItemSnapShots)), DispatcherPriority.Loaded); + }), DispatcherPriority.Loaded); + } + + if (location == DropZoneLocation.Right || location == DropZoneLocation.Bottom) + { + branchItem.FirstItem = Content; + branchItem.SecondItem = newContent; + } + else + { + branchItem.FirstItem = newContent; + branchItem.SecondItem = Content; + } + + SetCurrentValue(ContentProperty, branchItem); + + Dispatcher.BeginInvoke(new Action(() => MarkTopLeftItem(this)), DispatcherPriority.Loaded); + } + + internal static bool ConsolidateBranch(DependencyObject redundantNode) + { + bool isSecondLineageWhenOwnerIsBranch; + var ownerBranch = FindLayoutOrBranchOwner(redundantNode, out isSecondLineageWhenOwnerIsBranch) as Branch; + if (ownerBranch == null) return false; + + var survivingItem = isSecondLineageWhenOwnerIsBranch ? ownerBranch.FirstItem : ownerBranch.SecondItem; + + var grandParent = FindLayoutOrBranchOwner(ownerBranch, out isSecondLineageWhenOwnerIsBranch); + if (grandParent == null) throw new ApplicationException("Unexpected structure, grandparent Layout or Branch not found"); + + var layout = grandParent as Layout; + if (layout != null) + { + layout.Content = survivingItem; + MarkTopLeftItem(layout); + return true; + } + + var branch = (Branch)grandParent; + if (isSecondLineageWhenOwnerIsBranch) + branch.SecondItem = survivingItem; + else + branch.FirstItem = survivingItem; + var rootLayout = branch.VisualTreeAncestory().OfType().FirstOrDefault(); + if (rootLayout != null) + MarkTopLeftItem(rootLayout); + + return true; + } + + private static object FindLayoutOrBranchOwner(DependencyObject node, out bool isSecondLineageWhenOwnerIsBranch) + { + isSecondLineageWhenOwnerIsBranch = false; + + var ancestoryStack = new Stack(); + do + { + ancestoryStack.Push(node); + node = VisualTreeHelper.GetParent(node); + if (node is Layout) + return node; + + var branch = node as Branch; + if (branch == null) continue; + + isSecondLineageWhenOwnerIsBranch = ancestoryStack.Contains(branch.SecondContentPresenter); + return branch; + + } while (node != null); + + return null; + } + + private static BranchResult Branch(Orientation orientation, double proportion, bool makeSecond, DataTemplate branchTemplate, TabablzControl newSibling, object existingContent, Action applier) + { + var branchItem = new Branch + { + Orientation = orientation + }; + + var newContent = new ContentControl + { + Content = newSibling ?? new object(), + ContentTemplate = branchTemplate, + }; + + if (!makeSecond) + { + branchItem.FirstItem = existingContent; + branchItem.SecondItem = newContent; + } + else + { + branchItem.FirstItem = newContent; + branchItem.SecondItem = existingContent; + } + + branchItem.SetCurrentValue(Dockablz.Branch.FirstItemLengthProperty, new GridLength(proportion, GridUnitType.Star)); + branchItem.SetCurrentValue(Dockablz.Branch.SecondItemLengthProperty, new GridLength(1 - proportion, GridUnitType.Star)); + + applier(branchItem); + + newContent.Dispatcher.Invoke(new Action(() => { }), DispatcherPriority.Loaded); + var newTabablzControl = newContent.VisualTreeDepthFirstTraversal().OfType().FirstOrDefault(); + if (newTabablzControl != null) return new BranchResult(branchItem, newTabablzControl); + + //let#s be kinf and give WPF an extra change to gen the controls + newContent.Dispatcher.Invoke(new Action(() => { }), DispatcherPriority.Background); + newTabablzControl = newContent.VisualTreeDepthFirstTraversal().OfType().FirstOrDefault(); + + if (newTabablzControl == null) + throw new ApplicationException("New TabablzControl was not generated inside branch."); + + return new BranchResult(branchItem, newTabablzControl); + } + + private static void ItemDragCompleted(object sender, DragablzDragCompletedEventArgs e) + { + _isDragOpWireUpPending = false; + + foreach (var loadedLayout in LoadedLayouts) + loadedLayout.IsParticipatingInDrag = false; + + if (_currentlyOfferedDropZone == null || e.DragablzItem.IsDropTargetFound) return; + + TabablzControl tabablzControl; + if (TryGetSourceTabControl(e.DragablzItem, out tabablzControl)) + { + if (tabablzControl.Items.Count > 1) return; + + if (_currentlyOfferedDropZone.Item2.Location == DropZoneLocation.Floating) + Float(_currentlyOfferedDropZone.Item1, e.DragablzItem); + else + _currentlyOfferedDropZone.Item1.Branch(_currentlyOfferedDropZone.Item2.Location, e.DragablzItem); + } + + _currentlyOfferedDropZone = null; + } + + private static void Float(Layout layout, DragablzItem dragablzItem) + { + //TODO we need eq of IManualInterTabClient here, so consumer can control this op'. + + //remove from source + var sourceOfDragItemsControl = ItemsControl.ItemsControlFromItemContainer(dragablzItem) as DragablzItemsControl; + if (sourceOfDragItemsControl == null) throw new ApplicationException("Unable to determin source items control."); + var sourceTabControl = TabablzControl.GetOwnerOfHeaderItems(sourceOfDragItemsControl); + layout._floatTransfer = FloatTransfer.TakeSnapshot(dragablzItem, sourceTabControl); + var floatingItemSnapShots = sourceTabControl.VisualTreeDepthFirstTraversal() + .OfType() + .SelectMany(l => l.FloatingDragablzItems().Select(FloatingItemSnapShot.Take)) + .ToList(); + if (sourceTabControl == null) throw new ApplicationException("Unable to determin source tab control."); + sourceTabControl.RemoveItem(dragablzItem); + + //add to float layer + CollectionTeaser collectionTeaser; + if (CollectionTeaser.TryCreate(layout.FloatingItemsSource, out collectionTeaser)) + collectionTeaser.Add(layout._floatTransfer.Content); + else + layout.FloatingItems.Add(layout._floatTransfer.Content); + + layout.Dispatcher.BeginInvoke(new Action(() => RestoreFloatingItemSnapShots(layout, floatingItemSnapShots)), DispatcherPriority.Loaded); + } + + private static void PreviewItemDragDelta(object sender, DragablzDragDeltaEventArgs e) + { + if (e.Cancel) return; + + if (_isDragOpWireUpPending) + { + SetupParticipatingLayouts(e.DragablzItem); + _isDragOpWireUpPending = false; + } + + foreach (var layout in LoadedLayouts.Where(l => l.IsParticipatingInDrag)) + { + var cursorPos = Native.GetCursorPos(); + layout.MonitorDropZones(cursorPos); + } + } + + private void PrepareFloatingContainerForItemOverride(DependencyObject dependencyObject, object o) + { + var headeredDragablzItem = dependencyObject as HeaderedDragablzItem; + if (headeredDragablzItem == null) return; + + SetIsFloatingInLayout(dependencyObject, true); + + var headerBinding = new Binding(FloatingItemHeaderMemberPath) { Source = o }; + headeredDragablzItem.SetBinding(HeaderedDragablzItem.HeaderContentProperty, headerBinding); + + if (!string.IsNullOrWhiteSpace(FloatingItemDisplayMemberPath)) + { + var contentBinding = new Binding(FloatingItemDisplayMemberPath) { Source = o }; + headeredDragablzItem.SetBinding(ContentProperty, contentBinding); + } + + if (_floatTransfer == null || (o != _floatTransfer.Content && dependencyObject != _floatTransfer.Content)) + return; + + var dragablzItem = (DragablzItem)dependencyObject; + + Dispatcher.BeginInvoke(new Action(() => + { + //TODO might be nice to allow user a bit of control over sizing...especially the .75 thing i have handily hard coded. shoot me. + dragablzItem.Measure(new Size(_floatingItems.ActualWidth, _floatingItems.ActualHeight)); + var newWidth = Math.Min(_floatingItems.ActualWidth * .75, dragablzItem.DesiredSize.Width); + var newHeight = Math.Min(_floatingItems.ActualHeight * .75, dragablzItem.DesiredSize.Height); + dragablzItem.SetCurrentValue(DragablzItem.XProperty, _floatingItems.ActualWidth / 2 - newWidth / 2); + dragablzItem.SetCurrentValue(DragablzItem.YProperty, _floatingItems.ActualHeight / 2 - newHeight / 2); + dragablzItem.SetCurrentValue(WidthProperty, newWidth); + dragablzItem.SetCurrentValue(HeightProperty, newHeight); + }), DispatcherPriority.Loaded); + + _floatTransfer = null; + } + + private DragablzItem GetFloatingContainerForItemOverride() + { + if (string.IsNullOrWhiteSpace(FloatingItemHeaderMemberPath)) + return new DragablzItem(); + + return new HeaderedDragablzItem(); + } + + private static void ClearingFloatingContainerForItemOverride(DependencyObject dependencyObject, object o) + { + SetIsFloatingInLayout(dependencyObject, false); + } + + private void TileFloatingItemsExecuted(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs) + { + var dragablzItems = _floatingItems.DragablzItems(); + Tiler.Tile(dragablzItems, new Size(_floatingItems.ActualWidth, _floatingItems.ActualHeight)); + } + + private void TileFloatingItemsHorizontallyExecuted(object sender, ExecutedRoutedEventArgs e) + { + var dragablzItems = _floatingItems.DragablzItems(); + Tiler.TileHorizontally(dragablzItems, new Size(_floatingItems.ActualWidth, _floatingItems.ActualHeight)); + } + + private void TileFloatingItemsVerticallyExecuted(object sender, ExecutedRoutedEventArgs e) + { + var dragablzItems = _floatingItems.DragablzItems(); + Tiler.TileVertically(dragablzItems, new Size(_floatingItems.ActualWidth, _floatingItems.ActualHeight)); + } + + public static readonly DependencyProperty FloatingItemStateProperty = DependencyProperty.RegisterAttached( + "FloatingItemState", typeof(WindowState), typeof(Layout), new PropertyMetadata(default(WindowState))); + + public static void SetFloatingItemState(DependencyObject element, WindowState value) + { + element.SetValue(FloatingItemStateProperty, value); + } + + public static WindowState GetFloatingItemState(DependencyObject element) + { + return (WindowState)element.GetValue(FloatingItemStateProperty); + } + + internal static readonly DependencyProperty LocationSnapShotProperty = DependencyProperty.RegisterAttached( + "LocationSnapShot", typeof(LocationSnapShot), typeof(Layout), new PropertyMetadata(default(LocationSnapShot))); + + internal static void SetLocationSnapShot(FrameworkElement element, LocationSnapShot value) + { + element.SetValue(LocationSnapShotProperty, value); + } + + internal static LocationSnapShot GetLocationSnapShot(FrameworkElement element) + { + return (LocationSnapShot)element.GetValue(LocationSnapShotProperty); + } + + private static void CanExecuteMaximiseFloatingItem(object sender, CanExecuteRoutedEventArgs canExecuteRoutedEventArgs) + { + canExecuteRoutedEventArgs.CanExecute = false; + canExecuteRoutedEventArgs.Handled = true; + + var dragablzItem = canExecuteRoutedEventArgs.Parameter as DragablzItem; + if (dragablzItem != null) + { + canExecuteRoutedEventArgs.CanExecute = new[] { WindowState.Normal, WindowState.Minimized }.Contains(GetFloatingItemState(dragablzItem)); + } + } + + private static void CanExecuteRestoreFloatingItem(object sender, CanExecuteRoutedEventArgs canExecuteRoutedEventArgs) + { + canExecuteRoutedEventArgs.CanExecute = false; + canExecuteRoutedEventArgs.Handled = true; + + var dragablzItem = canExecuteRoutedEventArgs.Parameter as DragablzItem; + if (dragablzItem != null) + { + canExecuteRoutedEventArgs.CanExecute = new[] { WindowState.Maximized, WindowState.Minimized }.Contains(GetFloatingItemState(dragablzItem)); + } + } + + private static void CanExecuteCloseFloatingItem(object sender, CanExecuteRoutedEventArgs canExecuteRoutedEventArgs) + { + canExecuteRoutedEventArgs.CanExecute = true; + canExecuteRoutedEventArgs.Handled = true; + } + + private void CloseFloatingItemExecuted(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs) + { + var dragablzItem = executedRoutedEventArgs.Parameter as DragablzItem; + if (dragablzItem == null) throw new ApplicationException("Parameter must be a DragablzItem"); + + var cancel = false; + if (ClosingFloatingItemCallback != null) + { + var callbackArgs = new ItemActionCallbackArgs(Window.GetWindow(this), this, dragablzItem); + ClosingFloatingItemCallback(callbackArgs); + cancel = callbackArgs.IsCancelled; + } + + if (cancel) return; + + //TODO ...need a similar tp manual inter tab controlller here for the extra hook + + var item = _floatingItems.ItemContainerGenerator.ItemFromContainer(dragablzItem); + + CollectionTeaser collectionTeaser; + if (CollectionTeaser.TryCreate(_floatingItems.ItemsSource, out collectionTeaser)) + collectionTeaser.Remove(item); + else + _floatingItems.Items.Remove(item); + } + + private static void MaximiseFloatingItemExecuted(object sender, ExecutedRoutedEventArgs e) + { + var dragablzItem = e.Parameter as DragablzItem; + if (dragablzItem == null) return; + + SetLocationSnapShot(dragablzItem, LocationSnapShot.Take(dragablzItem)); + SetFloatingItemState(dragablzItem, WindowState.Maximized); + } + + private static void RestoreFloatingItemExecuted(object sender, ExecutedRoutedEventArgs e) + { + var dragablzItem = e.Parameter as DragablzItem; + if (dragablzItem == null) return; + + SetFloatingItemState(dragablzItem, WindowState.Normal); + var locationSnapShot = GetLocationSnapShot(dragablzItem); + if (locationSnapShot != null) + locationSnapShot.Apply(dragablzItem); + } + + private bool IsHostingTab() + { + return this.VisualTreeDepthFirstTraversal().OfType() + .FirstOrDefault(t => t.InterTabController != null && t.InterTabController.Partition == Partition) + != null; + } + + private static void MarkTopLeftItem(Layout layout) + { + var layoutAccessor = layout.Query(); + if (layoutAccessor.TabablzControl != null) + { + SetIsTopLeftItem(layoutAccessor.TabablzControl, true); + return; + } + var branchAccessor = layoutAccessor.BranchAccessor; + while (branchAccessor != null && branchAccessor.FirstItemTabablzControl == null) + { + branchAccessor = branchAccessor.FirstItemBranchAccessor; + } + + foreach (var tabablzControl in layoutAccessor.TabablzControls()) + { + SetIsTopLeftItem(tabablzControl, branchAccessor != null && Equals(tabablzControl, branchAccessor.FirstItemTabablzControl)); + } + } + + private void CanExecuteUnfloat(object sender, CanExecuteRoutedEventArgs canExecuteRoutedEventArgs) + { + canExecuteRoutedEventArgs.CanExecute = IsHostingTab(); + canExecuteRoutedEventArgs.ContinueRouting = false; + canExecuteRoutedEventArgs.Handled = true; + } + + private void UnfloatExecuted(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs) + { + var dragablzItem = executedRoutedEventArgs.Parameter as DragablzItem; + if (dragablzItem == null) return; + + var exemplarTabControl = this.VisualTreeDepthFirstTraversal().OfType() + .FirstOrDefault(t => t.InterTabController != null && t.InterTabController.Partition == Partition); + + if (exemplarTabControl == null) return; + + //TODO passing the exemplar tab in here isnt ideal, as strictly speaking there isnt one. + var newTabHost = exemplarTabControl.InterTabController.InterTabClient.GetNewHost(exemplarTabControl.InterTabController.InterTabClient, + exemplarTabControl.InterTabController.Partition, exemplarTabControl); + if (newTabHost == null || newTabHost.TabablzControl == null || newTabHost.Container == null) + throw new ApplicationException("New tab host was not correctly provided"); + + var floatingItemSnapShots = dragablzItem.VisualTreeDepthFirstTraversal() + .OfType() + .SelectMany(l => l.FloatingDragablzItems().Select(FloatingItemSnapShot.Take)) + .ToList(); + + var content = dragablzItem.Content ?? dragablzItem; + + //remove from source + CollectionTeaser collectionTeaser; + if (CollectionTeaser.TryCreate(FloatingItemsSource, out collectionTeaser)) + collectionTeaser.Remove(content); + else + FloatingItems.Remove(content); + + var myWindow = Window.GetWindow(this); + if (myWindow == null) throw new ApplicationException("Unable to find owning window."); + newTabHost.Container.Width = myWindow.RestoreBounds.Width; + newTabHost.Container.Height = myWindow.RestoreBounds.Height; + + newTabHost.Container.Left = myWindow.Left + 20; + newTabHost.Container.Top = myWindow.Top + 20; + + Dispatcher.BeginInvoke(new Action(() => + { + newTabHost.TabablzControl.AddToSource(content); + newTabHost.TabablzControl.SelectedItem = content; + newTabHost.Container.Show(); + newTabHost.Container.Activate(); + + Dispatcher.BeginInvoke( + new Action(() => RestoreFloatingItemSnapShots(newTabHost.TabablzControl, floatingItemSnapShots))); + }), DispatcherPriority.DataBind); + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Dockablz/LayoutAccessor.cs b/Source/3rdparty/Dragablz/Dockablz/LayoutAccessor.cs new file mode 100644 index 0000000000..d770015b96 --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/LayoutAccessor.cs @@ -0,0 +1,110 @@ +using System; +using System.Collections.Generic; + +namespace Dragablz.Dockablz +{ + /// + /// Provides information about the instance. + /// + public class LayoutAccessor + { + private readonly Layout _layout; + private readonly BranchAccessor _branchAccessor; + private readonly TabablzControl _tabablzControl; + + public LayoutAccessor(Layout layout) + { + if (layout == null) throw new ArgumentNullException("layout"); + + _layout = layout; + + var branch = Layout.Content as Branch; + if (branch != null) + _branchAccessor = new BranchAccessor(branch); + else + _tabablzControl = Layout.Content as TabablzControl; + } + + public Layout Layout + { + get { return _layout; } + } + + public IEnumerable FloatingItems + { + get { return _layout.FloatingDragablzItems(); } + } + + /// + /// and are mutually exclusive, according to whether the layout has been split, or just contains a tab control. + /// + public BranchAccessor BranchAccessor + { + get { return _branchAccessor; } + } + + /// + /// and are mutually exclusive, according to whether the layout has been split, or just contains a tab control. + /// + public TabablzControl TabablzControl + { + get { return _tabablzControl; } + } + + /// + /// Visits the content of the layout, according to its content type. No more than one of the provided + /// callbacks will be called. + /// + public LayoutAccessor Visit( + Action branchVisitor = null, + Action tabablzControlVisitor = null, + Action contentVisitor = null) + { + if (_branchAccessor != null) + { + if (branchVisitor != null) + { + branchVisitor(_branchAccessor); + } + + return this; + } + + if (_tabablzControl != null) + { + if (tabablzControlVisitor != null) + tabablzControlVisitor(_tabablzControl); + + return this; + } + + if (_layout.Content != null && contentVisitor != null) + contentVisitor(_layout.Content); + + return this; + } + + /// + /// Gets all the Tabablz controls in a Layout, regardless of location. + /// + /// + public IEnumerable TabablzControls() + { + var tabablzControls = new List(); + this.Visit(tabablzControls, BranchAccessorVisitor, TabablzControlVisitor); + return tabablzControls; + } + + private static void TabablzControlVisitor(IList resultSet, TabablzControl tabablzControl) + { + resultSet.Add(tabablzControl); + } + + private static void BranchAccessorVisitor(IList resultSet, BranchAccessor branchAccessor) + { + branchAccessor + .Visit(resultSet, BranchItem.First, BranchAccessorVisitor, TabablzControlVisitor) + .Visit(resultSet, BranchItem.Second, BranchAccessorVisitor, TabablzControlVisitor); + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Dockablz/LocationReport.cs b/Source/3rdparty/Dragablz/Dockablz/LocationReport.cs new file mode 100644 index 0000000000..9b1ef14738 --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/LocationReport.cs @@ -0,0 +1,65 @@ +using System; + +namespace Dragablz.Dockablz +{ + /// + /// Provides information about where a tab control is withing a layout structure. + /// + public class LocationReport + { + private readonly TabablzControl _tabablzControl; + private readonly Layout _rootLayout; + private readonly Branch _parentBranch; + private readonly bool _isLeaf; + private readonly bool _isSecondLeaf; + + //TODO I've internalised constructor for now, so I can come back and add Window without breaking. + + internal LocationReport(TabablzControl tabablzControl, Layout rootLayout) + : this(tabablzControl, rootLayout, null, false) + { } + + internal LocationReport(TabablzControl tabablzControl, Layout rootLayout, Branch parentBranch, bool isSecondLeaf) + { + if (tabablzControl == null) throw new ArgumentNullException("tabablzControl"); + if (rootLayout == null) throw new ArgumentNullException("rootLayout"); + + _tabablzControl = tabablzControl; + _rootLayout = rootLayout; + _parentBranch = parentBranch; + _isLeaf = _parentBranch != null; + _isSecondLeaf = isSecondLeaf; + } + + public TabablzControl TabablzControl + { + get { return _tabablzControl; } + } + + public Layout RootLayout + { + get { return _rootLayout; } + } + + /// + /// Gets the parent branch if this is a leaf. If the is directly under the will be null. + /// + public Branch ParentBranch + { + get { return _parentBranch; } + } + + /// + /// Idicates if this is a leaf in a branch. True if is not null. + /// + public bool IsLeaf + { + get { return _isLeaf; } + } + + public bool IsSecondLeaf + { + get { return _isSecondLeaf; } + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Dockablz/LocationReportBuilder.cs b/Source/3rdparty/Dragablz/Dockablz/LocationReportBuilder.cs new file mode 100644 index 0000000000..3f1a878061 --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/LocationReportBuilder.cs @@ -0,0 +1,54 @@ +using System; + +namespace Dragablz.Dockablz +{ + internal class LocationReportBuilder + { + private readonly TabablzControl _targetTabablzControl; + private Branch _branch; + private bool _isSecondLeaf; + private Layout _layout; + + public LocationReportBuilder(TabablzControl targetTabablzControl) + { + _targetTabablzControl = targetTabablzControl; + } + + public TabablzControl TargetTabablzControl + { + get { return _targetTabablzControl; } + } + + public bool IsFound { get; private set; } + + public void MarkFound() + { + if (IsFound) + throw new InvalidOperationException("Already found."); + + IsFound = true; + + _layout = CurrentLayout; + } + + public void MarkFound(Branch branch, bool isSecondLeaf) + { + if (branch == null) throw new ArgumentNullException("branch"); + if (IsFound) + throw new InvalidOperationException("Already found."); + + IsFound = true; + + _layout = CurrentLayout; + _branch = branch; + _isSecondLeaf = isSecondLeaf; + } + + public Layout CurrentLayout { get; set; } + + public LocationReport ToLocationReport() + { + return new LocationReport(_targetTabablzControl, _layout, _branch, _isSecondLeaf); + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Dockablz/LocationReportException.cs b/Source/3rdparty/Dragablz/Dockablz/LocationReportException.cs new file mode 100644 index 0000000000..de955c9bf0 --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/LocationReportException.cs @@ -0,0 +1,22 @@ +using System; + +namespace Dragablz.Dockablz +{ + /// + /// + /// + public class LocationReportException : Exception + { + public LocationReportException() + { + } + + public LocationReportException(string message) : base(message) + { + } + + public LocationReportException(string message, Exception innerException) : base(message, innerException) + { + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Dockablz/LocationSnapShot.cs b/Source/3rdparty/Dragablz/Dockablz/LocationSnapShot.cs new file mode 100644 index 0000000000..6523ee3e7d --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/LocationSnapShot.cs @@ -0,0 +1,38 @@ +using System; +using System.Windows; +using System.Windows.Navigation; + +namespace Dragablz.Dockablz +{ + /// + /// Initially needed to restore MDI dragablz items styles after a max then restore, + /// as the trigger which binds the item width to the canvas width sets the Width back to the default + /// (e.g double.NaN) when the trigger is unset. so we need to re-apply sizes manually + /// + internal class LocationSnapShot + { + private readonly double _width; + private readonly double _height; + + public static LocationSnapShot Take(FrameworkElement frameworkElement) + { + if (frameworkElement == null) throw new ArgumentNullException("frameworkElement"); + + return new LocationSnapShot(frameworkElement.Width, frameworkElement.Height); + } + + private LocationSnapShot(double width, double height) + { + _width = width; + _height = height; + } + + public void Apply(FrameworkElement frameworkElement) + { + if (frameworkElement == null) throw new ArgumentNullException("frameworkElement"); + + frameworkElement.SetCurrentValue(FrameworkElement.WidthProperty, _width); + frameworkElement.SetCurrentValue(FrameworkElement.HeightProperty, _height); + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Dockablz/Tiler.cs b/Source/3rdparty/Dragablz/Dockablz/Tiler.cs new file mode 100644 index 0000000000..811dad90c5 --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/Tiler.cs @@ -0,0 +1,83 @@ +using System; +using System.CodeDom; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; + +namespace Dragablz.Dockablz +{ + internal class Tiler + { + public static void Tile(IEnumerable dragablzItems, Size bounds) + { + if (dragablzItems == null) throw new ArgumentNullException("dragablzItems"); + + var items = new Queue(dragablzItems.OrderBy(Panel.GetZIndex)); + + var cellCountPerColumn = TilerCalculator.GetCellCountPerColumn(items.Count()); + var x = 0d; + var cellWidth = bounds.Width / cellCountPerColumn.Length; + foreach (var cellCount in cellCountPerColumn) + { + var y = 0d; + var cellHeight = bounds.Height / cellCount; + for (var cell = 0; cell < cellCount; cell++) + { + var item = items.Dequeue(); + Layout.SetFloatingItemState(item, WindowState.Normal); + item.SetCurrentValue(DragablzItem.XProperty, x); + item.SetCurrentValue(DragablzItem.YProperty, y); + item.SetCurrentValue(FrameworkElement.WidthProperty, cellWidth); + item.SetCurrentValue(FrameworkElement.HeightProperty, cellHeight); + + y += cellHeight; + } + + x += cellWidth; + } + } + + public static void TileHorizontally(IEnumerable dragablzItems, Size bounds) + { + if (dragablzItems == null) throw new ArgumentNullException("dragablzItems"); + + var items = dragablzItems.ToList(); + + var x = 0.0; + var width = bounds.Width / items.Count; + foreach (var dragablzItem in items) + { + Layout.SetFloatingItemState(dragablzItem, WindowState.Normal); + dragablzItem.SetCurrentValue(DragablzItem.XProperty, x); + dragablzItem.SetCurrentValue(DragablzItem.YProperty, 0d); + x += width; + dragablzItem.SetCurrentValue(FrameworkElement.WidthProperty, width); + dragablzItem.SetCurrentValue(FrameworkElement.HeightProperty, bounds.Height); + } + } + + public static void TileVertically(IEnumerable dragablzItems, Size bounds) + { + if (dragablzItems == null) throw new ArgumentNullException("dragablzItems"); + + var items = dragablzItems.ToList(); + + var y = 0.0; + var height = bounds.Height / items.Count; + foreach (var dragablzItem in items) + { + Layout.SetFloatingItemState(dragablzItem, WindowState.Normal); + dragablzItem.SetCurrentValue(DragablzItem.YProperty, y); + dragablzItem.SetCurrentValue(DragablzItem.XProperty, 0d); + y += height; + dragablzItem.SetCurrentValue(FrameworkElement.HeightProperty, height); + dragablzItem.SetCurrentValue(FrameworkElement.WidthProperty, bounds.Width); + } + } + + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Dockablz/TilerCalculator.cs b/Source/3rdparty/Dragablz/Dockablz/TilerCalculator.cs new file mode 100644 index 0000000000..d99d02fd86 --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/TilerCalculator.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Dragablz.Dockablz +{ + internal static class TilerCalculator + { + public static int[] GetCellCountPerColumn(int totalCells) + { + if (totalCells == 2) + return new[] { 1, 1 }; + + var sqrt = Math.Sqrt(totalCells); + + if (unchecked(sqrt == (int)sqrt)) + return Enumerable.Repeat((int)sqrt, (int)sqrt).ToArray(); + + var columns = (int)Math.Round(sqrt, MidpointRounding.AwayFromZero); + var minimumCellsPerColumns = (int)Math.Floor(sqrt); + var result = Enumerable.Repeat(minimumCellsPerColumns, columns).ToArray(); + + for (var i = columns - 1; result.Aggregate((current, next) => current + next) < totalCells; i--) + result[i] += 1; + + return result; + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Dragablz.csproj b/Source/3rdparty/Dragablz/Dragablz.csproj new file mode 100644 index 0000000000..9fafb9fa3b --- /dev/null +++ b/Source/3rdparty/Dragablz/Dragablz.csproj @@ -0,0 +1,10 @@ + + + + + net10.0-windows + true + false + + + diff --git a/Source/3rdparty/Dragablz/DragablzColors.cs b/Source/3rdparty/Dragablz/DragablzColors.cs new file mode 100644 index 0000000000..12eb0ad3b4 --- /dev/null +++ b/Source/3rdparty/Dragablz/DragablzColors.cs @@ -0,0 +1,74 @@ +using System; +using System.Windows; +using System.Windows.Media; +using Dragablz.Core; + +namespace Dragablz +{ + /// + /// + /// + /// + /// In supporting .Net 4.0 we don't have access to SystemParameters.WindowGlassBrush, and even then + /// the opacity is not provided, so this class wraps up a few issues around here. + /// + public static class DragablzColors + { + //TODO listen to changes from the OS to provide updates + public static Color WindowBaseColor = Color.FromRgb(217, 217, 217); + public static Brush WindowGlassBrush = GetWindowGlassBrush(); + public static Brush WindowGlassBalancedBrush = GetBalancedWindowGlassBrush(); + public static Brush WindowInactiveBrush = GetWindowInactiveBrush(); + + private static Brush GetWindowGlassBrush() + { + var colorizationParams = new Native.DWMCOLORIZATIONPARAMS(); + Native.DwmGetColorizationParameters(ref colorizationParams); + var frameColor = ToColor(colorizationParams.ColorizationColor); + + return new SolidColorBrush(frameColor); + } + + + private static Brush GetBalancedWindowGlassBrush() + { + var colorizationParams = new Native.DWMCOLORIZATIONPARAMS(); + Native.DwmGetColorizationParameters(ref colorizationParams); + var frameColor = ToColor(colorizationParams.ColorizationColor); + var blendedColor = BlendColor(frameColor, WindowBaseColor, 100f - colorizationParams.ColorizationColorBalance); + + return new SolidColorBrush(blendedColor); + } + + private static Brush GetWindowInactiveBrush() + { + return new SolidColorBrush(SystemColors.MenuBarColor); + } + + private static Color ToColor(UInt32 value) + { + return Color.FromArgb(255, + (byte)(value >> 16), + (byte)(value >> 8), + (byte)value + ); + } + + private static Color BlendColor(Color color1, Color color2, double percentage) + { + percentage = Math.Min(100, Math.Max(0, percentage)); + + return Color.FromRgb( + BlendColorChannel(color1.R, color2.R, percentage), + BlendColorChannel(color1.G, color2.G, percentage), + BlendColorChannel(color1.B, color2.B, percentage)); + } + + private static byte BlendColorChannel(double channel1, double channel2, double channel2Percentage) + { + var buff = channel1 + (channel2 - channel1) * channel2Percentage / 100D; + return Math.Min((byte)Math.Round(buff), (byte)255); + } + + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/DragablzDragCompletedEventArgs.cs b/Source/3rdparty/Dragablz/DragablzDragCompletedEventArgs.cs new file mode 100644 index 0000000000..b4bf35ab49 --- /dev/null +++ b/Source/3rdparty/Dragablz/DragablzDragCompletedEventArgs.cs @@ -0,0 +1,54 @@ +using System; +using System.Windows; +using System.Windows.Controls.Primitives; + +namespace Dragablz +{ + public delegate void DragablzDragCompletedEventHandler(object sender, DragablzDragCompletedEventArgs e); + + public class DragablzDragCompletedEventArgs : RoutedEventArgs + { + private readonly DragablzItem _dragablzItem; + private readonly bool _isDropTargetFound; + private readonly DragCompletedEventArgs _dragCompletedEventArgs; + + public DragablzDragCompletedEventArgs(DragablzItem dragablzItem, DragCompletedEventArgs dragCompletedEventArgs) + { + if (dragablzItem == null) throw new ArgumentNullException("dragablzItem"); + if (dragCompletedEventArgs == null) throw new ArgumentNullException("dragCompletedEventArgs"); + + _dragablzItem = dragablzItem; + _dragCompletedEventArgs = dragCompletedEventArgs; + } + + public DragablzDragCompletedEventArgs(RoutedEvent routedEvent, DragablzItem dragablzItem, DragCompletedEventArgs dragCompletedEventArgs) + : base(routedEvent) + { + if (dragablzItem == null) throw new ArgumentNullException("dragablzItem"); + if (dragCompletedEventArgs == null) throw new ArgumentNullException("dragCompletedEventArgs"); + + _dragablzItem = dragablzItem; + _dragCompletedEventArgs = dragCompletedEventArgs; + } + + public DragablzDragCompletedEventArgs(RoutedEvent routedEvent, object source, DragablzItem dragablzItem, DragCompletedEventArgs dragCompletedEventArgs) + : base(routedEvent, source) + { + if (dragablzItem == null) throw new ArgumentNullException("dragablzItem"); + if (dragCompletedEventArgs == null) throw new ArgumentNullException("dragCompletedEventArgs"); + + _dragablzItem = dragablzItem; + _dragCompletedEventArgs = dragCompletedEventArgs; + } + + public DragablzItem DragablzItem + { + get { return _dragablzItem; } + } + + public DragCompletedEventArgs DragCompletedEventArgs + { + get { return _dragCompletedEventArgs; } + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/DragablzDragDeltaEventArgs.cs b/Source/3rdparty/Dragablz/DragablzDragDeltaEventArgs.cs new file mode 100644 index 0000000000..3e4ad36b8e --- /dev/null +++ b/Source/3rdparty/Dragablz/DragablzDragDeltaEventArgs.cs @@ -0,0 +1,44 @@ +using System; +using System.Windows; +using System.Windows.Controls.Primitives; + +namespace Dragablz +{ + public delegate void DragablzDragDeltaEventHandler(object sender, DragablzDragDeltaEventArgs e); + + public class DragablzDragDeltaEventArgs : DragablzItemEventArgs + { + private readonly DragDeltaEventArgs _dragDeltaEventArgs; + + public DragablzDragDeltaEventArgs(DragablzItem dragablzItem, DragDeltaEventArgs dragDeltaEventArgs) + : base(dragablzItem) + { + if (dragDeltaEventArgs == null) throw new ArgumentNullException("dragDeltaEventArgs"); + + _dragDeltaEventArgs = dragDeltaEventArgs; + } + + public DragablzDragDeltaEventArgs(RoutedEvent routedEvent, DragablzItem dragablzItem, DragDeltaEventArgs dragDeltaEventArgs) + : base(routedEvent, dragablzItem) + { + if (dragDeltaEventArgs == null) throw new ArgumentNullException("dragDeltaEventArgs"); + + _dragDeltaEventArgs = dragDeltaEventArgs; + } + + public DragablzDragDeltaEventArgs(RoutedEvent routedEvent, object source, DragablzItem dragablzItem, DragDeltaEventArgs dragDeltaEventArgs) + : base(routedEvent, source, dragablzItem) + { + if (dragDeltaEventArgs == null) throw new ArgumentNullException("dragDeltaEventArgs"); + + _dragDeltaEventArgs = dragDeltaEventArgs; + } + + public DragDeltaEventArgs DragDeltaEventArgs + { + get { return _dragDeltaEventArgs; } + } + + public bool Cancel { get; set; } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/DragablzDragStartedEventArgs.cs b/Source/3rdparty/Dragablz/DragablzDragStartedEventArgs.cs new file mode 100644 index 0000000000..dfa6196a27 --- /dev/null +++ b/Source/3rdparty/Dragablz/DragablzDragStartedEventArgs.cs @@ -0,0 +1,38 @@ +using System; +using System.Windows; +using System.Windows.Controls.Primitives; + +namespace Dragablz +{ + public delegate void DragablzDragStartedEventHandler(object sender, DragablzDragStartedEventArgs e); + + public class DragablzDragStartedEventArgs : DragablzItemEventArgs + { + private readonly DragStartedEventArgs _dragStartedEventArgs; + + public DragablzDragStartedEventArgs(DragablzItem dragablzItem, DragStartedEventArgs dragStartedEventArgs) + : base(dragablzItem) + { + if (dragStartedEventArgs == null) throw new ArgumentNullException("dragStartedEventArgs"); + + _dragStartedEventArgs = dragStartedEventArgs; + } + + public DragablzDragStartedEventArgs(RoutedEvent routedEvent, DragablzItem dragablzItem, DragStartedEventArgs dragStartedEventArgs) + : base(routedEvent, dragablzItem) + { + _dragStartedEventArgs = dragStartedEventArgs; + } + + public DragablzDragStartedEventArgs(RoutedEvent routedEvent, object source, DragablzItem dragablzItem, DragStartedEventArgs dragStartedEventArgs) + : base(routedEvent, source, dragablzItem) + { + _dragStartedEventArgs = dragStartedEventArgs; + } + + public DragStartedEventArgs DragStartedEventArgs + { + get { return _dragStartedEventArgs; } + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/DragablzIcon.cs b/Source/3rdparty/Dragablz/DragablzIcon.cs new file mode 100644 index 0000000000..2594760f1d --- /dev/null +++ b/Source/3rdparty/Dragablz/DragablzIcon.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; + +namespace Dragablz +{ + public class DragablzIcon : Control + { + static DragablzIcon() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(DragablzIcon), new FrameworkPropertyMetadata(typeof(DragablzIcon))); + } + } +} diff --git a/Source/3rdparty/Dragablz/DragablzItem.cs b/Source/3rdparty/Dragablz/DragablzItem.cs new file mode 100644 index 0000000000..95ec0a08d9 --- /dev/null +++ b/Source/3rdparty/Dragablz/DragablzItem.cs @@ -0,0 +1,639 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Threading; +using Dragablz.Core; +using Dragablz.Referenceless; + +namespace Dragablz +{ + public enum SizeGrip + { + NotApplicable, + Left, + TopLeft, + Top, + TopRight, + Right, + BottomRight, + Bottom, + BottomLeft + } + + [TemplatePart(Name = ThumbPartName, Type = typeof(Thumb))] + public class DragablzItem : ContentControl + { + public const string ThumbPartName = "PART_Thumb"; + + private readonly SerialDisposable _templateSubscriptions = new SerialDisposable(); + private readonly SerialDisposable _rightMouseUpCleanUpDisposable = new SerialDisposable(); + + private Thumb _customThumb; + private Thumb _thumb; + private bool _seizeDragWithTemplate; + private Action _dragSeizedContinuation; + + static DragablzItem() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(DragablzItem), new FrameworkPropertyMetadata(typeof(DragablzItem))); + } + + public DragablzItem() + { + AddHandler(MouseDownEvent, new RoutedEventHandler(MouseDownHandler), true); + } + + public static readonly DependencyProperty XProperty = DependencyProperty.Register( + "X", typeof(double), typeof(DragablzItem), new PropertyMetadata(default(double), OnXChanged)); + + public double X + { + get { return (double)GetValue(XProperty); } + set { SetValue(XProperty, value); } + } + + public static readonly RoutedEvent XChangedEvent = + EventManager.RegisterRoutedEvent( + "XChanged", + RoutingStrategy.Bubble, + typeof(RoutedPropertyChangedEventHandler), + typeof(DragablzItem)); + + public event RoutedPropertyChangedEventHandler XChanged + { + add { AddHandler(XChangedEvent, value); } + remove { RemoveHandler(IsDraggingChangedEvent, value); } + } + + private static void OnXChanged( + DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var instance = (DragablzItem)d; + var args = new RoutedPropertyChangedEventArgs( + (double)e.OldValue, + (double)e.NewValue) + { + RoutedEvent = XChangedEvent + }; + instance.RaiseEvent(args); + } + + public static readonly DependencyProperty YProperty = DependencyProperty.Register( + "Y", typeof(double), typeof(DragablzItem), new PropertyMetadata(default(double), OnYChanged)); + + public double Y + { + get { return (double)GetValue(YProperty); } + set { SetValue(YProperty, value); } + } + + public static readonly RoutedEvent YChangedEvent = + EventManager.RegisterRoutedEvent( + "YChanged", + RoutingStrategy.Bubble, + typeof(RoutedPropertyChangedEventHandler), + typeof(DragablzItem)); + + public event RoutedPropertyChangedEventHandler YChanged + { + add { AddHandler(YChangedEvent, value); } + remove { RemoveHandler(IsDraggingChangedEvent, value); } + } + + private static void OnYChanged( + DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var instance = (DragablzItem)d; + var args = new RoutedPropertyChangedEventArgs( + (double)e.OldValue, + (double)e.NewValue) + { + RoutedEvent = YChangedEvent + }; + instance.RaiseEvent(args); + } + + private static readonly DependencyPropertyKey LogicalIndexPropertyKey = + DependencyProperty.RegisterReadOnly( + "LogicalIndex", typeof(int), typeof(DragablzItem), + new PropertyMetadata(default(int), OnLogicalIndexChanged)); + + public static readonly DependencyProperty LogicalIndexProperty = + LogicalIndexPropertyKey.DependencyProperty; + + public int LogicalIndex + { + get { return (int)GetValue(LogicalIndexProperty); } + internal set { SetValue(LogicalIndexPropertyKey, value); } + } + + public static readonly RoutedEvent LogicalIndexChangedEvent = + EventManager.RegisterRoutedEvent( + "LogicalIndexChanged", + RoutingStrategy.Bubble, + typeof(RoutedPropertyChangedEventHandler), + typeof(DragablzItem)); + + public event RoutedPropertyChangedEventHandler LogicalIndexChanged + { + add { AddHandler(LogicalIndexChangedEvent, value); } + remove { RemoveHandler(LogicalIndexChangedEvent, value); } + } + + private static void OnLogicalIndexChanged( + DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var instance = (DragablzItem)d; + var args = new RoutedPropertyChangedEventArgs( + (int)e.OldValue, + (int)e.NewValue) + { + RoutedEvent = DragablzItem.LogicalIndexChangedEvent + }; + instance.RaiseEvent(args); + } + + public static readonly DependencyProperty SizeGripProperty = DependencyProperty.RegisterAttached( + "SizeGrip", typeof(SizeGrip), typeof(DragablzItem), new PropertyMetadata(default(SizeGrip), SizeGripPropertyChangedCallback)); + + private static void SizeGripPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) + { + var thumb = (dependencyObject as Thumb); + if (thumb == null) return; + thumb.DragDelta += SizeThumbOnDragDelta; + } + + private static void SizeThumbOnDragDelta(object sender, DragDeltaEventArgs dragDeltaEventArgs) + { + var thumb = ((Thumb)sender); + var dragablzItem = thumb.VisualTreeAncestory().OfType().FirstOrDefault(); + if (dragablzItem == null) return; + + var sizeGrip = (SizeGrip)thumb.GetValue(SizeGripProperty); + var width = dragablzItem.ActualWidth; + var height = dragablzItem.ActualHeight; + var x = dragablzItem.X; + var y = dragablzItem.Y; + switch (sizeGrip) + { + case SizeGrip.NotApplicable: + break; + case SizeGrip.Left: + width += -dragDeltaEventArgs.HorizontalChange; + x += dragDeltaEventArgs.HorizontalChange; + break; + case SizeGrip.TopLeft: + width += -dragDeltaEventArgs.HorizontalChange; + height += -dragDeltaEventArgs.VerticalChange; + x += dragDeltaEventArgs.HorizontalChange; + y += dragDeltaEventArgs.VerticalChange; + break; + case SizeGrip.Top: + height += -dragDeltaEventArgs.VerticalChange; + y += dragDeltaEventArgs.VerticalChange; + break; + case SizeGrip.TopRight: + height += -dragDeltaEventArgs.VerticalChange; + width += dragDeltaEventArgs.HorizontalChange; + y += dragDeltaEventArgs.VerticalChange; + break; + case SizeGrip.Right: + width += dragDeltaEventArgs.HorizontalChange; + break; + case SizeGrip.BottomRight: + width += dragDeltaEventArgs.HorizontalChange; + height += dragDeltaEventArgs.VerticalChange; + break; + case SizeGrip.Bottom: + height += dragDeltaEventArgs.VerticalChange; + break; + case SizeGrip.BottomLeft: + height += dragDeltaEventArgs.VerticalChange; + width += -dragDeltaEventArgs.HorizontalChange; + x += dragDeltaEventArgs.HorizontalChange; + break; + default: + throw new ArgumentOutOfRangeException(); + } + dragablzItem.SetCurrentValue(XProperty, x); + dragablzItem.SetCurrentValue(YProperty, y); + dragablzItem.SetCurrentValue(WidthProperty, Math.Max(width, thumb.DesiredSize.Width)); + dragablzItem.SetCurrentValue(HeightProperty, Math.Max(height, thumb.DesiredSize.Height)); + } + + public static void SetSizeGrip(DependencyObject element, SizeGrip value) + { + element.SetValue(SizeGripProperty, value); + } + + public static SizeGrip GetSizeGrip(DependencyObject element) + { + return (SizeGrip)element.GetValue(SizeGripProperty); + } + + /// + /// Allows item content to be rotated (in suppported templates), typically for use in a vertical/side tab. + /// + public static readonly DependencyProperty ContentRotateTransformAngleProperty = DependencyProperty.RegisterAttached( + "ContentRotateTransformAngle", typeof(double), typeof(DragablzItem), new FrameworkPropertyMetadata(default(double), FrameworkPropertyMetadataOptions.Inherits)); + + /// + /// Allows item content to be rotated (in suppported templates), typically for use in a vertical/side tab. + /// + /// + /// + public static void SetContentRotateTransformAngle(DependencyObject element, double value) + { + element.SetValue(ContentRotateTransformAngleProperty, value); + } + + /// + /// Allows item content to be rotated (in suppported templates), typically for use in a vertical/side tab. + /// + /// + /// + public static double GetContentRotateTransformAngle(DependencyObject element) + { + return (double)element.GetValue(ContentRotateTransformAngleProperty); + } + + public static readonly DependencyProperty IsSelectedProperty = DependencyProperty.Register( + "IsSelected", typeof(bool), typeof(DragablzItem), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.AffectsParentMeasure)); + + public bool IsSelected + { + get { return (bool)GetValue(IsSelectedProperty); } + set { SetValue(IsSelectedProperty, value); } + } + + private static readonly DependencyPropertyKey IsDraggingPropertyKey = + DependencyProperty.RegisterReadOnly( + "IsDragging", typeof(bool), typeof(DragablzItem), + new PropertyMetadata(default(bool), OnIsDraggingChanged)); + + public static readonly DependencyProperty IsDraggingProperty = + IsDraggingPropertyKey.DependencyProperty; + + public bool IsDragging + { + get { return (bool)GetValue(IsDraggingProperty); } + internal set { SetValue(IsDraggingPropertyKey, value); } + } + + public static readonly RoutedEvent IsDraggingChangedEvent = + EventManager.RegisterRoutedEvent( + "IsDraggingChanged", + RoutingStrategy.Bubble, + typeof(RoutedPropertyChangedEventHandler), + typeof(DragablzItem)); + + public event RoutedPropertyChangedEventHandler IsDraggingChanged + { + add { AddHandler(IsDraggingChangedEvent, value); } + remove { RemoveHandler(IsDraggingChangedEvent, value); } + } + + internal object UnderlyingContent { get; set; } + + private static void OnIsDraggingChanged( + DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var instance = (DragablzItem)d; + var args = new RoutedPropertyChangedEventArgs( + (bool)e.OldValue, + (bool)e.NewValue) + { RoutedEvent = IsDraggingChangedEvent }; + instance.RaiseEvent(args); + } + + public static readonly RoutedEvent MouseDownWithinEvent = + EventManager.RegisterRoutedEvent( + "MouseDownWithin", + RoutingStrategy.Bubble, + typeof(DragablzItemEventHandler), + typeof(DragablzItem)); + + private static void OnMouseDownWithin(DependencyObject d) + { + var instance = (DragablzItem)d; + instance.RaiseEvent(new DragablzItemEventArgs(MouseDownWithinEvent, instance)); + } + + private static readonly DependencyPropertyKey IsSiblingDraggingPropertyKey = + DependencyProperty.RegisterReadOnly( + "IsSiblingDragging", typeof(bool), typeof(DragablzItem), + new PropertyMetadata(default(bool), OnIsSiblingDraggingChanged)); + + public static readonly DependencyProperty IsSiblingDraggingProperty = + IsSiblingDraggingPropertyKey.DependencyProperty; + + public bool IsSiblingDragging + { + get { return (bool)GetValue(IsSiblingDraggingProperty); } + internal set { SetValue(IsSiblingDraggingPropertyKey, value); } + } + + public static readonly RoutedEvent IsSiblingDraggingChangedEvent = + EventManager.RegisterRoutedEvent( + "IsSiblingDraggingChanged", + RoutingStrategy.Bubble, + typeof(RoutedPropertyChangedEventHandler), + typeof(DragablzItem)); + + public event RoutedPropertyChangedEventHandler IsSiblingDraggingChanged + { + add { AddHandler(IsSiblingDraggingChangedEvent, value); } + remove { RemoveHandler(IsSiblingDraggingChangedEvent, value); } + } + + private static void OnIsSiblingDraggingChanged( + DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var instance = (DragablzItem)d; + var args = new RoutedPropertyChangedEventArgs( + (bool)e.OldValue, + (bool)e.NewValue) + { + RoutedEvent = IsSiblingDraggingChangedEvent + }; + instance.RaiseEvent(args); + } + + public static readonly RoutedEvent DragStarted = + EventManager.RegisterRoutedEvent( + "DragStarted", + RoutingStrategy.Bubble, + typeof(DragablzDragStartedEventHandler), + typeof(DragablzItem)); + + protected void OnDragStarted(DragablzDragStartedEventArgs e) + { + RaiseEvent(e); + } + + public static readonly RoutedEvent DragDelta = + EventManager.RegisterRoutedEvent( + "DragDelta", + RoutingStrategy.Bubble, + typeof(DragablzDragDeltaEventHandler), + typeof(DragablzItem)); + + protected void OnDragDelta(DragablzDragDeltaEventArgs e) + { + RaiseEvent(e); + } + + public static readonly RoutedEvent PreviewDragDelta = + EventManager.RegisterRoutedEvent( + "PreviewDragDelta", + RoutingStrategy.Tunnel, + typeof(DragablzDragDeltaEventHandler), + typeof(DragablzItem)); + + protected void OnPreviewDragDelta(DragablzDragDeltaEventArgs e) + { + RaiseEvent(e); + } + + public static readonly RoutedEvent DragCompleted = + EventManager.RegisterRoutedEvent( + "DragCompleted", + RoutingStrategy.Bubble, + typeof(DragablzDragCompletedEventHandler), + typeof(DragablzItem)); + + protected void OnDragCompleted(DragCompletedEventArgs e) + { + var args = new DragablzDragCompletedEventArgs(DragCompleted, this, e); + RaiseEvent(args); + + //OK, this is a cheeky bit. A completed drag may have occured after a tab as been pushed + //intom a new window, which means we may have reverted to the template thumb. So, let's + //refresh the thumb in case the user has a custom one + _customThumb = FindCustomThumb(); + _templateSubscriptions.Disposable = SelectAndSubscribeToThumb().Item2; + } + + /// + /// templates contain a thumb, which is used to drag the item around. + /// For most scenarios this is fine, but by setting this flag to true you can define + /// a custom thumb in your content, without having to override the template. This can be useful if you + /// have extra content; such as a custom button that you want the user to be able to interact with (as usually + /// the default thumb will handle mouse interaction). + /// + public static readonly DependencyProperty IsCustomThumbProperty = DependencyProperty.RegisterAttached( + "IsCustomThumb", typeof(bool), typeof(DragablzItem), new PropertyMetadata(default(bool), IsCustomThumbPropertyChangedCallback)); + + private static void IsCustomThumbPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) + { + var thumb = dependencyObject as Thumb; + if (thumb == null) throw new ApplicationException("IsCustomThumb can only be applied to a thumb"); + + if (thumb.IsLoaded) + ApplyCustomThumbSetting(thumb); + else + thumb.Loaded += CustomThumbOnLoaded; + } + + /// + /// templates contain a thumb, which is used to drag the item around. + /// For most scenarios this is fine, but by setting this flag to true you can define + /// a custom thumb in your content, without having to override the template. This can be useful if you + /// have extra content; such as a custom button that you want the user to be able to interact with (as usually + /// the default thumb will handle mouse interaction). + /// + public static void SetIsCustomThumb(Thumb element, bool value) + { + element.SetValue(IsCustomThumbProperty, value); + } + + public static bool GetIsCustomThumb(Thumb element) + { + return (bool)element.GetValue(IsCustomThumbProperty); + } + + private bool _isTemplateThumbWithMouseAfterSeize = false; + public override void OnApplyTemplate() + { + base.OnApplyTemplate(); + + var thumbAndSubscription = SelectAndSubscribeToThumb(); + _templateSubscriptions.Disposable = thumbAndSubscription.Item2; + + if (_seizeDragWithTemplate && thumbAndSubscription.Item1 != null) + { + _isTemplateThumbWithMouseAfterSeize = true; + Mouse.AddLostMouseCaptureHandler(this, LostMouseAfterSeizeHandler); + if (_dragSeizedContinuation != null) + _dragSeizedContinuation(this); + _dragSeizedContinuation = null; + + Dispatcher.BeginInvoke(new Action(() => thumbAndSubscription.Item1.RaiseEvent(new MouseButtonEventArgs(InputManager.Current.PrimaryMouseDevice, + 0, + MouseButton.Left) + { RoutedEvent = MouseLeftButtonDownEvent }))); + } + _seizeDragWithTemplate = false; + } + + protected override async void OnPreviewMouseRightButtonDown(MouseButtonEventArgs e) + { + if (_thumb != null) + { + var currentThumbIsHitTestVisible = _thumb.IsHitTestVisible; + _thumb.SetCurrentValue(IsHitTestVisibleProperty, false); + + while (Mouse.RightButton == MouseButtonState.Pressed) + { + await Task.Delay(25); + } + ; + + _thumb.SetCurrentValue(IsHitTestVisibleProperty, currentThumbIsHitTestVisible); + } + + base.OnPreviewMouseRightButtonDown(e); + } + + protected override void OnPreviewMouseRightButtonUp(MouseButtonEventArgs e) + { + _rightMouseUpCleanUpDisposable.Disposable = Disposable.Empty; + base.OnPreviewMouseRightButtonUp(e); + } + + private void LostMouseAfterSeizeHandler(object sender, MouseEventArgs mouseEventArgs) + { + _isTemplateThumbWithMouseAfterSeize = false; + Mouse.RemoveLostMouseCaptureHandler(this, LostMouseAfterSeizeHandler); + } + + internal void InstigateDrag(Action continuation) + { + _dragSeizedContinuation = continuation; + var thumb = GetTemplateChild(ThumbPartName) as Thumb; + if (thumb != null) + { + thumb.CaptureMouse(); + } + else + _seizeDragWithTemplate = true; + } + + internal Point MouseAtDragStart { get; set; } + + private bool _onTheMove; + + internal string PartitionAtDragStart { get; set; } + + internal bool IsDropTargetFound { get; set; } + + private void ThumbOnDragCompleted(object sender, DragCompletedEventArgs dragCompletedEventArgs) + { + OnDragCompleted(dragCompletedEventArgs); + MouseAtDragStart = new Point(); + _onTheMove = false; + } + + private void ThumbOnDragDelta(object sender, DragDeltaEventArgs dragDeltaEventArgs) + { + var thumb = (Thumb)sender; + + var previewEventArgs = new DragablzDragDeltaEventArgs(PreviewDragDelta, this, dragDeltaEventArgs); + + OnPreviewDragDelta(previewEventArgs); + + if (!_onTheMove) + { + var delta = MouseAtDragStart - Mouse.GetPosition(this); + if ( + (Math.Abs(delta.X) < SystemParameters.MinimumHorizontalDragDistance) && + (Math.Abs(delta.Y) < SystemParameters.MinimumVerticalDragDistance)) + { + previewEventArgs.Handled = true; + + return; + } + else + _onTheMove = true; + } + + if (previewEventArgs.Cancel) + thumb.CancelDrag(); + if (!previewEventArgs.Handled) + { + var eventArgs = new DragablzDragDeltaEventArgs(DragDelta, this, dragDeltaEventArgs); + OnDragDelta(eventArgs); + if (eventArgs.Cancel) + thumb.CancelDrag(); + } + } + + private void ThumbOnDragStarted(object sender, DragStartedEventArgs dragStartedEventArgs) + { + MouseAtDragStart = Mouse.GetPosition(this); + OnDragStarted(new DragablzDragStartedEventArgs(DragStarted, this, dragStartedEventArgs)); + } + + private void MouseDownHandler(object sender, RoutedEventArgs routedEventArgs) + { + OnMouseDownWithin(this); + } + + private static void CustomThumbOnLoaded(object sender, RoutedEventArgs routedEventArgs) + { + var thumb = (Thumb)sender; + thumb.Loaded -= CustomThumbOnLoaded; + ApplyCustomThumbSetting(thumb); + } + + private Thumb FindCustomThumb() + { + return this.VisualTreeDepthFirstTraversal().OfType().FirstOrDefault(GetIsCustomThumb); + } + + private static void ApplyCustomThumbSetting(Thumb thumb) + { + var dragablzItem = thumb.VisualTreeAncestory().OfType().FirstOrDefault(); + if (dragablzItem == null) throw new ApplicationException("Cannot find parent DragablzItem for custom thumb"); + + var enableCustomThumb = (bool)thumb.GetValue(IsCustomThumbProperty); + dragablzItem._customThumb = enableCustomThumb ? thumb : null; + dragablzItem._templateSubscriptions.Disposable = dragablzItem.SelectAndSubscribeToThumb().Item2; + + if (dragablzItem._customThumb != null && dragablzItem._isTemplateThumbWithMouseAfterSeize) + dragablzItem.Dispatcher.BeginInvoke(new Action(() => dragablzItem._customThumb.RaiseEvent(new MouseButtonEventArgs(InputManager.Current.PrimaryMouseDevice, + 0, + MouseButton.Left) + { RoutedEvent = MouseLeftButtonDownEvent }))); + } + + private Tuple SelectAndSubscribeToThumb() + { + var templateThumb = GetTemplateChild(ThumbPartName) as Thumb; + templateThumb?.SetCurrentValue(IsHitTestVisibleProperty, _customThumb == null); + + _thumb = _customThumb ?? templateThumb; + if (_thumb != null) + { + _thumb.DragStarted += ThumbOnDragStarted; + _thumb.DragDelta += ThumbOnDragDelta; + _thumb.DragCompleted += ThumbOnDragCompleted; + } + + var tidyUpThumb = _thumb; + var disposable = Disposable.Create(() => + { + if (tidyUpThumb == null) return; + tidyUpThumb.DragStarted -= ThumbOnDragStarted; + tidyUpThumb.DragDelta -= ThumbOnDragDelta; + tidyUpThumb.DragCompleted -= ThumbOnDragCompleted; + }); + + return new Tuple(_thumb, disposable); + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/DragablzItemEventArgs.cs b/Source/3rdparty/Dragablz/DragablzItemEventArgs.cs new file mode 100644 index 0000000000..88b256e18a --- /dev/null +++ b/Source/3rdparty/Dragablz/DragablzItemEventArgs.cs @@ -0,0 +1,37 @@ +using System; +using System.Windows; +using System.Windows.Controls.Primitives; + +namespace Dragablz +{ + public delegate void DragablzItemEventHandler(object sender, DragablzItemEventArgs e); + + public class DragablzItemEventArgs : RoutedEventArgs + { + private readonly DragablzItem _dragablzItem; + + public DragablzItemEventArgs(DragablzItem dragablzItem) + { + if (dragablzItem == null) throw new ArgumentNullException("dragablzItem"); + + _dragablzItem = dragablzItem; + } + + public DragablzItemEventArgs(RoutedEvent routedEvent, DragablzItem dragablzItem) + : base(routedEvent) + { + _dragablzItem = dragablzItem; + } + + public DragablzItemEventArgs(RoutedEvent routedEvent, object source, DragablzItem dragablzItem) + : base(routedEvent, source) + { + _dragablzItem = dragablzItem; + } + + public DragablzItem DragablzItem + { + get { return _dragablzItem; } + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/DragablzItemsControl.cs b/Source/3rdparty/Dragablz/DragablzItemsControl.cs new file mode 100644 index 0000000000..6c14cf1ce9 --- /dev/null +++ b/Source/3rdparty/Dragablz/DragablzItemsControl.cs @@ -0,0 +1,401 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Data; +using System.Windows.Threading; +using Dragablz.Core; + +namespace Dragablz +{ + /// + /// Items control which typically uses a canvas and + /// + public class DragablzItemsControl : ItemsControl + { + private object[] _previousSortQueryResult; + + static DragablzItemsControl() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(DragablzItemsControl), new FrameworkPropertyMetadata(typeof(DragablzItemsControl))); + } + + public DragablzItemsControl() + { + ItemContainerGenerator.StatusChanged += ItemContainerGeneratorOnStatusChanged; + ItemContainerGenerator.ItemsChanged += ItemContainerGeneratorOnItemsChanged; + AddHandler(DragablzItem.XChangedEvent, new RoutedPropertyChangedEventHandler(ItemXChanged)); + AddHandler(DragablzItem.YChangedEvent, new RoutedPropertyChangedEventHandler(ItemYChanged)); + AddHandler(DragablzItem.DragDelta, new DragablzDragDeltaEventHandler(ItemDragDelta)); + AddHandler(DragablzItem.DragCompleted, new DragablzDragCompletedEventHandler(ItemDragCompleted)); + AddHandler(DragablzItem.DragStarted, new DragablzDragStartedEventHandler(ItemDragStarted)); + AddHandler(DragablzItem.MouseDownWithinEvent, new DragablzItemEventHandler(ItemMouseDownWithinHandlerTarget)); + } + + public static readonly DependencyProperty FixedItemCountProperty = DependencyProperty.Register( + "FixedItemCount", typeof(int), typeof(DragablzItemsControl), new PropertyMetadata(default(int))); + + public int FixedItemCount + { + get { return (int)GetValue(FixedItemCountProperty); } + set { SetValue(FixedItemCountProperty, value); } + } + + private void ItemContainerGeneratorOnItemsChanged(object sender, ItemsChangedEventArgs itemsChangedEventArgs) + { + //throw new NotImplementedException(); + } + + protected override void ClearContainerForItemOverride(DependencyObject element, object item) + { + if (ContainerCustomisations != null && ContainerCustomisations.ClearingContainerForItemOverride != null) + ContainerCustomisations.ClearingContainerForItemOverride(element, item); + + base.ClearContainerForItemOverride(element, item); + + ((DragablzItem)element).SizeChanged -= ItemSizeChangedEventHandler; + + Dispatcher.BeginInvoke(new Action(() => + { + var dragablzItems = DragablzItems().ToList(); + if (ItemsOrganiser == null) return; + ItemsOrganiser.Organise(this, new Size(ItemsPresenterWidth, ItemsPresenterHeight), dragablzItems); + var measure = ItemsOrganiser.Measure(this, new Size(ActualWidth, ActualHeight), dragablzItems); + ItemsPresenterWidth = measure.Width; + ItemsPresenterHeight = measure.Height; + }), DispatcherPriority.Input); + } + + public static readonly DependencyProperty ItemsOrganiserProperty = DependencyProperty.Register( + "ItemsOrganiser", typeof(IItemsOrganiser), typeof(DragablzItemsControl), new PropertyMetadata(default(IItemsOrganiser))); + + public IItemsOrganiser ItemsOrganiser + { + get { return (IItemsOrganiser)GetValue(ItemsOrganiserProperty); } + set { SetValue(ItemsOrganiserProperty, value); } + } + + public static readonly DependencyProperty PositionMonitorProperty = DependencyProperty.Register( + "PositionMonitor", typeof(PositionMonitor), typeof(DragablzItemsControl), new PropertyMetadata(default(PositionMonitor))); + + public PositionMonitor PositionMonitor + { + get { return (PositionMonitor)GetValue(PositionMonitorProperty); } + set { SetValue(PositionMonitorProperty, value); } + } + + private static readonly DependencyPropertyKey ItemsPresenterWidthPropertyKey = + DependencyProperty.RegisterReadOnly( + "ItemsPresenterWidth", typeof(double), typeof(DragablzItemsControl), + new PropertyMetadata(default(double))); + + public static readonly DependencyProperty ItemsPresenterWidthProperty = + ItemsPresenterWidthPropertyKey.DependencyProperty; + + public double ItemsPresenterWidth + { + get { return (double)GetValue(ItemsPresenterWidthProperty); } + private set { SetValue(ItemsPresenterWidthPropertyKey, value); } + } + + private static readonly DependencyPropertyKey ItemsPresenterHeightPropertyKey = + DependencyProperty.RegisterReadOnly( + "ItemsPresenterHeight", typeof(double), typeof(DragablzItemsControl), + new PropertyMetadata(default(double))); + + public static readonly DependencyProperty ItemsPresenterHeightProperty = + ItemsPresenterHeightPropertyKey.DependencyProperty; + + public double ItemsPresenterHeight + { + get { return (double)GetValue(ItemsPresenterHeightProperty); } + private set { SetValue(ItemsPresenterHeightPropertyKey, value); } + } + + /// + /// Adds an item to the underlying source, displaying in a specific position in rendered control. + /// + /// + /// + public void AddToSource(object item, AddLocationHint addLocationHint) + { + AddToSource(item, null, addLocationHint); + } + + /// + /// Adds an item to the underlying source, displaying in a specific position in rendered control. + /// + /// + /// + /// + public void AddToSource(object item, object nearItem, AddLocationHint addLocationHint) + { + CollectionTeaser collectionTeaser; + if (CollectionTeaser.TryCreate(ItemsSource, out collectionTeaser)) + collectionTeaser.Add(item); + else + Items.Add(item); + MoveItem(new MoveItemRequest(item, nearItem, addLocationHint)); + } + + internal ContainerCustomisations ContainerCustomisations { get; set; } + + private void ItemContainerGeneratorOnStatusChanged(object sender, EventArgs eventArgs) + { + if (ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated) return; + + InvalidateMeasure(); + //extra kick + Dispatcher.BeginInvoke(new Action(InvalidateMeasure), DispatcherPriority.Loaded); + } + + protected override bool IsItemItsOwnContainerOverride(object item) + { + var dragablzItem = item as DragablzItem; + if (dragablzItem == null) return false; + + return true; + } + + protected override DependencyObject GetContainerForItemOverride() + { + var result = ContainerCustomisations != null && ContainerCustomisations.GetContainerForItemOverride != null + ? ContainerCustomisations.GetContainerForItemOverride() + : new DragablzItem(); + + result.SizeChanged += ItemSizeChangedEventHandler; + + return result; + } + + protected override void PrepareContainerForItemOverride(DependencyObject element, object item) + { + if (ContainerCustomisations != null && ContainerCustomisations.PrepareContainerForItemOverride != null) + ContainerCustomisations.PrepareContainerForItemOverride(element, item); + + base.PrepareContainerForItemOverride(element, item); + } + + protected override Size MeasureOverride(Size constraint) + { + if (ItemsOrganiser == null) return base.MeasureOverride(constraint); + + if (LockedMeasure.HasValue) + { + ItemsPresenterWidth = LockedMeasure.Value.Width; + ItemsPresenterHeight = LockedMeasure.Value.Height; + return LockedMeasure.Value; + } + + var dragablzItems = DragablzItems().ToList(); + var maxConstraint = new Size(double.PositiveInfinity, double.PositiveInfinity); + + ItemsOrganiser.Organise(this, maxConstraint, dragablzItems); + var measure = ItemsOrganiser.Measure(this, new Size(ActualWidth, ActualHeight), dragablzItems); + + ItemsPresenterWidth = measure.Width; + ItemsPresenterHeight = measure.Height; + + var width = double.IsInfinity(constraint.Width) ? measure.Width : constraint.Width; + var height = double.IsInfinity(constraint.Height) ? measure.Height : constraint.Height; + + return new Size(width, height); + } + + internal void InstigateDrag(object item, Action continuation) + { + var dragablzItem = (DragablzItem)ItemContainerGenerator.ContainerFromItem(item); + dragablzItem.InstigateDrag(continuation); + } + + /// + /// Move an item in the rendered layout. + /// + /// + public void MoveItem(MoveItemRequest moveItemRequest) + { + if (moveItemRequest == null) throw new ArgumentNullException("moveItemRequest"); + + if (ItemsOrganiser == null) return; + + var dragablzItem = moveItemRequest.Item as DragablzItem ?? + ItemContainerGenerator.ContainerFromItem( + moveItemRequest.Item) as DragablzItem; + var contextDragablzItem = moveItemRequest.Context as DragablzItem ?? + ItemContainerGenerator.ContainerFromItem( + moveItemRequest.Context) as DragablzItem; + + if (dragablzItem == null) return; + + var sortedItems = DragablzItems().OrderBy(di => di.LogicalIndex).ToList(); + sortedItems.Remove(dragablzItem); + + switch (moveItemRequest.AddLocationHint) + { + case AddLocationHint.First: + sortedItems.Insert(0, dragablzItem); + break; + case AddLocationHint.Last: + sortedItems.Add(dragablzItem); + break; + case AddLocationHint.Prior: + case AddLocationHint.After: + if (contextDragablzItem == null) + return; + + var contextIndex = sortedItems.IndexOf(contextDragablzItem); + sortedItems.Insert(moveItemRequest.AddLocationHint == AddLocationHint.Prior ? contextIndex : contextIndex + 1, dragablzItem); + + break; + default: + throw new ArgumentOutOfRangeException(); + } + + //TODO might not be too great for perf on larger lists + var orderedEnumerable = sortedItems.OrderBy(di => sortedItems.IndexOf(di)); + + ItemsOrganiser.Organise(this, new Size(ItemsPresenterWidth, ItemsPresenterHeight), orderedEnumerable); + } + + internal IEnumerable DragablzItems() + { + return this.Containers().ToList(); + } + + internal Size? LockedMeasure { get; set; } + + private void ItemDragStarted(object sender, DragablzDragStartedEventArgs eventArgs) + { + if (ItemsOrganiser != null) + { + var bounds = new Size(ActualWidth, ActualHeight); + ItemsOrganiser.OrganiseOnDragStarted(this, bounds, + DragablzItems().Except(new[] { eventArgs.DragablzItem }).ToList(), + eventArgs.DragablzItem); + } + + eventArgs.Handled = true; + + Dispatcher.BeginInvoke(new Action(InvalidateMeasure), DispatcherPriority.Loaded); + } + + private void ItemDragCompleted(object sender, DragablzDragCompletedEventArgs eventArgs) + { + var dragablzItems = DragablzItems() + .Select(i => + { + i.IsDragging = false; + i.IsSiblingDragging = false; + return i; + }) + .ToList(); + + if (ItemsOrganiser != null) + { + var bounds = new Size(ActualWidth, ActualHeight); + ItemsOrganiser.OrganiseOnDragCompleted(this, bounds, + dragablzItems.Except(eventArgs.DragablzItem), + eventArgs.DragablzItem); + } + + eventArgs.Handled = true; + + //wowsers + Dispatcher.BeginInvoke(new Action(InvalidateMeasure)); + Dispatcher.BeginInvoke(new Action(InvalidateMeasure), DispatcherPriority.Loaded); + } + + private void ItemDragDelta(object sender, DragablzDragDeltaEventArgs eventArgs) + { + var bounds = new Size(ItemsPresenterWidth, ItemsPresenterHeight); + var desiredLocation = new Point( + eventArgs.DragablzItem.X + eventArgs.DragDeltaEventArgs.HorizontalChange, + eventArgs.DragablzItem.Y + eventArgs.DragDeltaEventArgs.VerticalChange + ); + if (ItemsOrganiser != null) + { + if (FixedItemCount > 0 && + ItemsOrganiser.Sort(DragablzItems()).Take(FixedItemCount).Contains(eventArgs.DragablzItem)) + { + eventArgs.Handled = true; + return; + } + + desiredLocation = ItemsOrganiser.ConstrainLocation(this, bounds, + new Point(eventArgs.DragablzItem.X, eventArgs.DragablzItem.Y), + new Size(eventArgs.DragablzItem.ActualWidth, eventArgs.DragablzItem.ActualHeight), + desiredLocation, eventArgs.DragablzItem.DesiredSize); + } + + foreach (var dragableItem in DragablzItems() + .Except(new[] { eventArgs.DragablzItem })) // how about Linq.Where() ? + { + dragableItem.IsSiblingDragging = true; + } + eventArgs.DragablzItem.IsDragging = true; + + eventArgs.DragablzItem.X = desiredLocation.X; + eventArgs.DragablzItem.Y = desiredLocation.Y; + + if (ItemsOrganiser != null) + ItemsOrganiser.OrganiseOnDrag( + this, + bounds, + DragablzItems().Except(new[] { eventArgs.DragablzItem }), eventArgs.DragablzItem); + + eventArgs.DragablzItem.BringIntoView(); + + eventArgs.Handled = true; + } + + private void ItemXChanged(object sender, RoutedPropertyChangedEventArgs routedPropertyChangedEventArgs) + { + UpdateMonitor(routedPropertyChangedEventArgs); + } + + private void ItemYChanged(object sender, RoutedPropertyChangedEventArgs routedPropertyChangedEventArgs) + { + UpdateMonitor(routedPropertyChangedEventArgs); + } + + private void UpdateMonitor(RoutedEventArgs routedPropertyChangedEventArgs) + { + if (PositionMonitor == null) return; + + var dragablzItem = (DragablzItem)routedPropertyChangedEventArgs.OriginalSource; + + if (!Equals(ItemsControlFromItemContainer(dragablzItem), this)) return; + + PositionMonitor.OnLocationChanged(new LocationChangedEventArgs(dragablzItem.Content, new Point(dragablzItem.X, dragablzItem.Y))); + + var linearPositionMonitor = PositionMonitor as StackPositionMonitor; + if (linearPositionMonitor == null) return; + + var sortedItems = linearPositionMonitor.Sort(this.Containers()).Select(di => di.Content).ToArray(); + if (_previousSortQueryResult == null || !_previousSortQueryResult.SequenceEqual(sortedItems)) + linearPositionMonitor.OnOrderChanged(new OrderChangedEventArgs(_previousSortQueryResult, sortedItems)); + + _previousSortQueryResult = sortedItems; + } + + private void ItemMouseDownWithinHandlerTarget(object sender, DragablzItemEventArgs e) + { + if (ItemsOrganiser == null) return; + + var bounds = new Size(ActualWidth, ActualHeight); + ItemsOrganiser.OrganiseOnMouseDownWithin(this, bounds, + DragablzItems().Except(e.DragablzItem).ToList(), + e.DragablzItem); + } + + private void ItemSizeChangedEventHandler(object sender, SizeChangedEventArgs e) + { + InvalidateMeasure(); + //extra kick + Dispatcher.BeginInvoke(new Action(InvalidateMeasure), DispatcherPriority.Loaded); + } + } +} diff --git a/Source/3rdparty/Dragablz/DragablzWindow.cs b/Source/3rdparty/Dragablz/DragablzWindow.cs new file mode 100644 index 0000000000..9263b571ad --- /dev/null +++ b/Source/3rdparty/Dragablz/DragablzWindow.cs @@ -0,0 +1,367 @@ +using System; +using System.Linq; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Interop; +using System.Windows.Media; +using System.Windows.Threading; +using Dragablz.Core; +using Dragablz.Dockablz; +using Dragablz.Referenceless; + +namespace Dragablz +{ + /// + /// It is not necessary to use a to gain tab dragging features. + /// What this Window does is allow a quick way to remove the Window border, and support transparency whilst + /// dragging. + /// + [TemplatePart(Name = WindowSurfaceGridPartName, Type = typeof(Grid))] + [TemplatePart(Name = WindowRestoreThumbPartName, Type = typeof(Thumb))] + [TemplatePart(Name = WindowResizeThumbPartName, Type = typeof(Thumb))] + public class DragablzWindow : Window + { + public const string WindowSurfaceGridPartName = "PART_WindowSurface"; + public const string WindowRestoreThumbPartName = "PART_WindowRestoreThumb"; + public const string WindowResizeThumbPartName = "PART_WindowResizeThumb"; + private readonly SerialDisposable _templateSubscription = new SerialDisposable(); + + public static RoutedCommand CloseWindowCommand = new RoutedCommand(); + public static RoutedCommand RestoreWindowCommand = new RoutedCommand(); + public static RoutedCommand MaximizeWindowCommand = new RoutedCommand(); + public static RoutedCommand MinimizeWindowCommand = new RoutedCommand(); + + private const int ResizeMargin = 4; + private Size _sizeWhenResizeBegan; + private Point _screenMousePointWhenResizeBegan; + private Point _windowLocationPointWhenResizeBegan; + private SizeGrip _resizeType; + + private static SizeGrip[] _leftMode = new[] { SizeGrip.TopLeft, SizeGrip.Left, SizeGrip.BottomLeft }; + private static SizeGrip[] _rightMode = new[] { SizeGrip.TopRight, SizeGrip.Right, SizeGrip.BottomRight }; + private static SizeGrip[] _topMode = new[] { SizeGrip.TopLeft, SizeGrip.Top, SizeGrip.TopRight }; + private static SizeGrip[] _bottomMode = new[] { SizeGrip.BottomLeft, SizeGrip.Bottom, SizeGrip.BottomRight }; + + private static double _xScale = 1; + private static double _yScale = 1; + private static bool _dpiInitialized = false; + + static DragablzWindow() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(DragablzWindow), new FrameworkPropertyMetadata(typeof(DragablzWindow))); + } + + public DragablzWindow() + { + AddHandler(DragablzItem.DragStarted, new DragablzDragStartedEventHandler(ItemDragStarted), true); + AddHandler(DragablzItem.DragCompleted, new DragablzDragCompletedEventHandler(ItemDragCompleted), true); + CommandBindings.Add(new CommandBinding(CloseWindowCommand, CloseWindowExecuted)); + CommandBindings.Add(new CommandBinding(MaximizeWindowCommand, MaximizeWindowExecuted)); + CommandBindings.Add(new CommandBinding(MinimizeWindowCommand, MinimizeWindowExecuted)); + CommandBindings.Add(new CommandBinding(RestoreWindowCommand, RestoreWindowExecuted)); + } + + private static readonly DependencyPropertyKey IsWindowBeingDraggedByTabPropertyKey = + DependencyProperty.RegisterReadOnly( + "IsBeingDraggedByTab", typeof(bool), typeof(DragablzWindow), + new PropertyMetadata(default(bool))); + + public static readonly DependencyProperty IsBeingDraggedByTabProperty = + IsWindowBeingDraggedByTabPropertyKey.DependencyProperty; + + public bool IsBeingDraggedByTab + { + get { return (bool)GetValue(IsBeingDraggedByTabProperty); } + private set { SetValue(IsWindowBeingDraggedByTabPropertyKey, value); } + } + + private void ItemDragCompleted(object sender, DragablzDragCompletedEventArgs e) + { + IsBeingDraggedByTab = false; + } + + private void ItemDragStarted(object sender, DragablzDragStartedEventArgs e) + { + var sourceOfDragItemsControl = ItemsControl.ItemsControlFromItemContainer(e.DragablzItem) as DragablzItemsControl; + if (sourceOfDragItemsControl == null) return; + + var sourceTab = TabablzControl.GetOwnerOfHeaderItems(sourceOfDragItemsControl); + if (sourceTab == null) return; + + if (sourceOfDragItemsControl.Items.Count != 1 + || (sourceTab.InterTabController != null && !sourceTab.InterTabController.MoveWindowWithSolitaryTabs) + || Layout.IsContainedWithinBranch(sourceOfDragItemsControl)) + return; + + IsBeingDraggedByTab = true; + } + + public override void OnApplyTemplate() + { + var windowSurfaceGrid = GetTemplateChild(WindowSurfaceGridPartName) as Grid; + var windowRestoreThumb = GetTemplateChild(WindowRestoreThumbPartName) as Thumb; + var windowResizeThumb = GetTemplateChild(WindowResizeThumbPartName) as Thumb; + + _templateSubscription.Disposable = Disposable.Create(() => + { + if (windowSurfaceGrid != null) + { + windowSurfaceGrid.MouseLeftButtonDown -= WindowSurfaceGridOnMouseLeftButtonDown; + } + + if (windowRestoreThumb != null) + { + windowRestoreThumb.DragDelta -= WindowMoveThumbOnDragDelta; + windowRestoreThumb.MouseDoubleClick -= WindowRestoreThumbOnMouseDoubleClick; + } + + if (windowResizeThumb == null) return; + + windowResizeThumb.MouseMove -= WindowResizeThumbOnMouseMove; + windowResizeThumb.DragStarted -= WindowResizeThumbOnDragStarted; + windowResizeThumb.DragDelta -= WindowResizeThumbOnDragDelta; + windowResizeThumb.DragCompleted -= WindowResizeThumbOnDragCompleted; + }); + + base.OnApplyTemplate(); + + if (windowSurfaceGrid != null) + { + windowSurfaceGrid.MouseLeftButtonDown += WindowSurfaceGridOnMouseLeftButtonDown; + } + + if (windowRestoreThumb != null) + { + windowRestoreThumb.DragDelta += WindowMoveThumbOnDragDelta; + windowRestoreThumb.MouseDoubleClick += WindowRestoreThumbOnMouseDoubleClick; + } + + if (windowResizeThumb == null) return; + + windowResizeThumb.MouseMove += WindowResizeThumbOnMouseMove; + windowResizeThumb.DragStarted += WindowResizeThumbOnDragStarted; + windowResizeThumb.DragDelta += WindowResizeThumbOnDragDelta; + windowResizeThumb.DragCompleted += WindowResizeThumbOnDragCompleted; + } + + protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) + { + var resizeThumb = GetTemplateChild(WindowResizeThumbPartName) as Thumb; + if (resizeThumb != null) + { + var outerRectangleGeometry = new RectangleGeometry(new Rect(sizeInfo.NewSize)); + var innerRectangleGeometry = + new RectangleGeometry(new Rect(ResizeMargin, ResizeMargin, sizeInfo.NewSize.Width - ResizeMargin * 2, sizeInfo.NewSize.Height - ResizeMargin * 2)); + resizeThumb.Clip = new CombinedGeometry(GeometryCombineMode.Exclude, outerRectangleGeometry, + innerRectangleGeometry); + } + + base.OnRenderSizeChanged(sizeInfo); + } + + protected IntPtr CriticalHandle + { + get + { + return new WindowInteropHelper(this).Handle; + } + } + + private void WindowSurfaceGridOnMouseLeftButtonDown(object sender, MouseButtonEventArgs mouseButtonEventArgs) + { + if (mouseButtonEventArgs.ChangedButton != MouseButton.Left) return; + if (mouseButtonEventArgs.ClickCount == 1) + DragMove(); + if (mouseButtonEventArgs.ClickCount == 2) + WindowState = WindowState.Maximized; + } + + private static void WindowResizeThumbOnMouseMove(object sender, MouseEventArgs mouseEventArgs) + { + var thumb = (Thumb)sender; + var mousePositionInThumb = Mouse.GetPosition(thumb); + thumb.Cursor = SelectCursor(SelectSizingMode(mousePositionInThumb, thumb.RenderSize)); + } + + private void WindowRestoreThumbOnMouseDoubleClick(object sender, MouseButtonEventArgs mouseButtonEventArgs) + { + WindowState = WindowState.Normal; + } + + private void WindowResizeThumbOnDragCompleted(object sender, DragCompletedEventArgs dragCompletedEventArgs) + { + Cursor = Cursors.Arrow; + } + + private void WindowResizeThumbOnDragDelta(object sender, DragDeltaEventArgs dragDeltaEventArgs) + { + var mousePositionInWindow = Mouse.GetPosition(this); + var currentScreenMousePoint = PointToScreen(mousePositionInWindow); + + var width = _sizeWhenResizeBegan.Width; + var height = _sizeWhenResizeBegan.Height; + var left = _windowLocationPointWhenResizeBegan.X; + var top = _windowLocationPointWhenResizeBegan.Y; + + if (_leftMode.Contains(_resizeType)) + { + var diff = currentScreenMousePoint.X - _screenMousePointWhenResizeBegan.X; + diff /= _xScale; + var suggestedWidth = width + -diff; + left += diff; + width = suggestedWidth; + } + if (_rightMode.Contains(_resizeType)) + { + var diff = currentScreenMousePoint.X - _screenMousePointWhenResizeBegan.X; + diff /= _xScale; + width += diff; + } + if (_topMode.Contains(_resizeType)) + { + var diff = currentScreenMousePoint.Y - _screenMousePointWhenResizeBegan.Y; + diff /= _yScale; + height += -diff; + top += diff; + } + if (_bottomMode.Contains(_resizeType)) + { + var diff = currentScreenMousePoint.Y - _screenMousePointWhenResizeBegan.Y; + diff /= _yScale; + height += diff; + } + + width = Math.Max(MinWidth, width); + height = Math.Max(MinHeight, height); + //TODO must try harder. + left = Math.Min(left, _windowLocationPointWhenResizeBegan.X + _sizeWhenResizeBegan.Width - ResizeMargin * 4); + //TODO must try harder. + top = Math.Min(top, _windowLocationPointWhenResizeBegan.Y + _sizeWhenResizeBegan.Height - ResizeMargin * 4); + SetCurrentValue(WidthProperty, width); + SetCurrentValue(HeightProperty, height); + SetCurrentValue(LeftProperty, left); + SetCurrentValue(TopProperty, top); + } + + private void GetDPI() + { + if (_dpiInitialized) + { + return; + } + + Matrix m = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice; + _xScale = m.M11; + _yScale = m.M22; + _dpiInitialized = true; + } + + private void WindowResizeThumbOnDragStarted(object sender, DragStartedEventArgs dragStartedEventArgs) + { + _sizeWhenResizeBegan = new Size(ActualWidth, ActualHeight); + _windowLocationPointWhenResizeBegan = new Point(Left, Top); + var mousePositionInWindow = Mouse.GetPosition(this); + _screenMousePointWhenResizeBegan = PointToScreen(mousePositionInWindow); + + var thumb = (Thumb)sender; + var mousePositionInThumb = Mouse.GetPosition(thumb); + _resizeType = SelectSizingMode(mousePositionInThumb, thumb.RenderSize); + + GetDPI(); + } + + private static SizeGrip SelectSizingMode(Point mousePositionInThumb, Size thumbSize) + { + if (mousePositionInThumb.X <= ResizeMargin) + { + if (mousePositionInThumb.Y <= ResizeMargin) + return SizeGrip.TopLeft; + if (mousePositionInThumb.Y >= thumbSize.Height - ResizeMargin) + return SizeGrip.BottomLeft; + return SizeGrip.Left; + } + + if (mousePositionInThumb.X >= thumbSize.Width - ResizeMargin) + { + if (mousePositionInThumb.Y <= ResizeMargin) + return SizeGrip.TopRight; + if (mousePositionInThumb.Y >= thumbSize.Height - ResizeMargin) + return SizeGrip.BottomRight; + return SizeGrip.Right; + } + + if (mousePositionInThumb.Y <= ResizeMargin) + return SizeGrip.Top; + + return SizeGrip.Bottom; + } + + private static Cursor SelectCursor(SizeGrip sizeGrip) + { + switch (sizeGrip) + { + case SizeGrip.Left: + return Cursors.SizeWE; + case SizeGrip.TopLeft: + return Cursors.SizeNWSE; + case SizeGrip.Top: + return Cursors.SizeNS; + case SizeGrip.TopRight: + return Cursors.SizeNESW; + case SizeGrip.Right: + return Cursors.SizeWE; + case SizeGrip.BottomRight: + return Cursors.SizeNWSE; + case SizeGrip.Bottom: + return Cursors.SizeNS; + case SizeGrip.BottomLeft: + return Cursors.SizeNESW; + default: + return Cursors.Arrow; + } + } + + private void WindowMoveThumbOnDragDelta(object sender, DragDeltaEventArgs dragDeltaEventArgs) + { + if (WindowState != WindowState.Maximized || + (!(Math.Abs(dragDeltaEventArgs.HorizontalChange) > 2) && + !(Math.Abs(dragDeltaEventArgs.VerticalChange) > 2))) return; + + var cursorPos = Native.GetRawCursorPos(); + WindowState = WindowState.Normal; + + GetDPI(); + + Top = cursorPos.Y / _yScale - 2; + Left = cursorPos.X / _xScale - RestoreBounds.Width / 2; + + var lParam = (int)(uint)cursorPos.X | (cursorPos.Y << 16); + Native.SendMessage(CriticalHandle, WindowMessage.WM_LBUTTONUP, (IntPtr)HitTest.HT_CAPTION, + (IntPtr)lParam); + Native.SendMessage(CriticalHandle, WindowMessage.WM_SYSCOMMAND, (IntPtr)SystemCommand.SC_MOUSEMOVE, + IntPtr.Zero); + } + + private void RestoreWindowExecuted(object sender, ExecutedRoutedEventArgs e) + { + Native.PostMessage(new WindowInteropHelper(this).Handle, WindowMessage.WM_SYSCOMMAND, (IntPtr)SystemCommand.SC_RESTORE, IntPtr.Zero); + } + + private void MinimizeWindowExecuted(object sender, ExecutedRoutedEventArgs e) + { + Native.PostMessage(new WindowInteropHelper(this).Handle, WindowMessage.WM_SYSCOMMAND, (IntPtr)SystemCommand.SC_MINIMIZE, IntPtr.Zero); + } + + private void MaximizeWindowExecuted(object sender, ExecutedRoutedEventArgs e) + { + Native.PostMessage(new WindowInteropHelper(this).Handle, WindowMessage.WM_SYSCOMMAND, (IntPtr)SystemCommand.SC_MAXIMIZE, IntPtr.Zero); + } + + private void CloseWindowExecuted(object sender, ExecutedRoutedEventArgs executedRoutedEventArgs) + { + Native.PostMessage(new WindowInteropHelper(this).Handle, WindowMessage.WM_CLOSE, IntPtr.Zero, IntPtr.Zero); + } + } +} diff --git a/Source/3rdparty/Dragablz/EmptyHeaderSizingHint.cs b/Source/3rdparty/Dragablz/EmptyHeaderSizingHint.cs new file mode 100644 index 0000000000..cbaee08f7b --- /dev/null +++ b/Source/3rdparty/Dragablz/EmptyHeaderSizingHint.cs @@ -0,0 +1,22 @@ +namespace Dragablz +{ + /// + /// Provide a hint for how the header should size itself if there are no tabs left (and a Window is still open). + /// + public enum EmptyHeaderSizingHint + { + /// + /// The header size collapses to zero along the correct axis. + /// + Collapse, + /// + /// The header size remains that of the last tab prior to the tab header becoming empty. + /// + PreviousTab, + //TODO implement EmptyHeaderSizingHint.Stretch + /// + /// The header stretches along the according axis. + /// + //Stretch + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/HeaderedDragablzItem.cs b/Source/3rdparty/Dragablz/HeaderedDragablzItem.cs new file mode 100644 index 0000000000..ddb540f407 --- /dev/null +++ b/Source/3rdparty/Dragablz/HeaderedDragablzItem.cs @@ -0,0 +1,49 @@ +using System.Windows; +using System.Windows.Controls; + +namespace Dragablz +{ + public class HeaderedDragablzItem : DragablzItem + { + static HeaderedDragablzItem() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(HeaderedDragablzItem), new FrameworkPropertyMetadata(typeof(HeaderedDragablzItem))); + } + + public static readonly DependencyProperty HeaderContentProperty = DependencyProperty.Register( + "HeaderContent", typeof(object), typeof(HeaderedDragablzItem), new PropertyMetadata(default(object))); + + public object HeaderContent + { + get { return (object)GetValue(HeaderContentProperty); } + set { SetValue(HeaderContentProperty, value); } + } + + public static readonly DependencyProperty HeaderContentStringFormatProperty = DependencyProperty.Register( + "HeaderContentStringFormat", typeof(string), typeof(HeaderedDragablzItem), new PropertyMetadata(default(string))); + + public string HeaderContentStringFormat + { + get { return (string)GetValue(HeaderContentStringFormatProperty); } + set { SetValue(HeaderContentStringFormatProperty, value); } + } + + public static readonly DependencyProperty HeaderContentTemplateProperty = DependencyProperty.Register( + "HeaderContentTemplate", typeof(DataTemplate), typeof(HeaderedDragablzItem), new PropertyMetadata(default(DataTemplate))); + + public DataTemplate HeaderContentTemplate + { + get { return (DataTemplate)GetValue(HeaderContentTemplateProperty); } + set { SetValue(HeaderContentTemplateProperty, value); } + } + + public static readonly DependencyProperty HeaderContentTemplateSelectorProperty = DependencyProperty.Register( + "HeaderContentTemplateSelector", typeof(DataTemplateSelector), typeof(HeaderedDragablzItem), new PropertyMetadata(default(DataTemplateSelector))); + + public DataTemplateSelector HeaderContentTemplateSelector + { + get { return (DataTemplateSelector)GetValue(HeaderContentTemplateSelectorProperty); } + set { SetValue(HeaderContentTemplateSelectorProperty, value); } + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/HeaderedItemViewModel.cs b/Source/3rdparty/Dragablz/HeaderedItemViewModel.cs new file mode 100644 index 0000000000..87089fede0 --- /dev/null +++ b/Source/3rdparty/Dragablz/HeaderedItemViewModel.cs @@ -0,0 +1,83 @@ +using System.ComponentModel; +using System.Runtime.CompilerServices; + +namespace Dragablz +{ + /// + /// Helper class to create view models, particularly for tool/MDI windows. + /// + public class HeaderedItemViewModel : INotifyPropertyChanged + { + private bool _isSelected; + private object _header; + private object _content; + + public HeaderedItemViewModel() + { + } + + public HeaderedItemViewModel(object header, object content, bool isSelected = false) + { + _header = header; + _content = content; + _isSelected = isSelected; + } + + public object Header + { + get { return _header; } + set + { + if (_header == value) return; + _header = value; +#if NET40 + OnPropertyChanged("Header"); +#else + OnPropertyChanged(); +#endif + } + } + + public object Content + { + get { return _content; } + set + { + if (_content == value) return; + _content = value; +#if NET40 + OnPropertyChanged("Content"); +#else + OnPropertyChanged(); +#endif + } + } + + public bool IsSelected + { + get { return _isSelected; } + set + { + if (_isSelected == value) return; + _isSelected = value; +#if NET40 + OnPropertyChanged("IsSelected"); +#else + OnPropertyChanged(); +#endif + } + } + + public event PropertyChangedEventHandler PropertyChanged; + +#if NET40 + protected virtual void OnPropertyChanged(string propertyName) +#else + protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) +#endif + { + var handler = PropertyChanged; + if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); + } + } +} diff --git a/Source/3rdparty/Dragablz/HorizontalOrganiser.cs b/Source/3rdparty/Dragablz/HorizontalOrganiser.cs new file mode 100644 index 0000000000..60a8a29577 --- /dev/null +++ b/Source/3rdparty/Dragablz/HorizontalOrganiser.cs @@ -0,0 +1,16 @@ +using System; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media.Animation; + +namespace Dragablz +{ + public class HorizontalOrganiser : StackOrganiser + { + public HorizontalOrganiser() : base(Orientation.Horizontal) + { } + + public HorizontalOrganiser(double itemOffset) : base(Orientation.Horizontal, itemOffset) + { } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/HorizontalPositionMonitor.cs b/Source/3rdparty/Dragablz/HorizontalPositionMonitor.cs new file mode 100644 index 0000000000..9ea694a04b --- /dev/null +++ b/Source/3rdparty/Dragablz/HorizontalPositionMonitor.cs @@ -0,0 +1,11 @@ +using System.Windows.Controls; + +namespace Dragablz +{ + public class HorizontalPositionMonitor : StackPositionMonitor + { + public HorizontalPositionMonitor() : base(Orientation.Horizontal) + { + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/IInterLayoutClient.cs b/Source/3rdparty/Dragablz/IInterLayoutClient.cs new file mode 100644 index 0000000000..c241d3a608 --- /dev/null +++ b/Source/3rdparty/Dragablz/IInterLayoutClient.cs @@ -0,0 +1,19 @@ +using System.Windows; + +namespace Dragablz +{ + /// + /// Implementors should provide a mechanism to provide a new host control which contains a new . + /// + public interface IInterLayoutClient + { + /// + /// Provide a new host control and tab into which will be placed into a newly created layout branch. + /// + /// Provides the partition where the drag operation was initiated. + /// The source control where a dragging operation was initiated. + /// + INewTabHost GetNewHost(object partition, TabablzControl source); + + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/IInterTabClient.cs b/Source/3rdparty/Dragablz/IInterTabClient.cs new file mode 100644 index 0000000000..41283ca2e6 --- /dev/null +++ b/Source/3rdparty/Dragablz/IInterTabClient.cs @@ -0,0 +1,27 @@ +using System.Threading; +using System.Windows; + +namespace Dragablz +{ + /// + /// Implementors should provide mechanisms for providing new windows and closing old windows. + /// + public interface IInterTabClient + { + /// + /// Provide a new host window so a tab can be teared from an existing window into a new window. + /// + /// + /// Provides the partition where the drag operation was initiated. + /// The source control where a dragging operation was initiated. + /// + INewTabHost GetNewHost(IInterTabClient interTabClient, object partition, TabablzControl source); + /// + /// Called when a tab has been emptied, and thus typically a window needs closing. + /// + /// + /// + /// + TabEmptiedResponse TabEmptiedHandler(TabablzControl tabControl, Window window); + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/IItemsOrganiser.cs b/Source/3rdparty/Dragablz/IItemsOrganiser.cs new file mode 100644 index 0000000000..8ac4a14dc6 --- /dev/null +++ b/Source/3rdparty/Dragablz/IItemsOrganiser.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Windows; + +namespace Dragablz +{ + public interface IItemsOrganiser + { + void Organise(DragablzItemsControl requestor, Size measureBounds, IEnumerable items); + void Organise(DragablzItemsControl requestor, Size measureBounds, IOrderedEnumerable items); + void OrganiseOnMouseDownWithin(DragablzItemsControl requestor, Size measureBounds, List siblingItems, DragablzItem dragablzItem); + void OrganiseOnDragStarted(DragablzItemsControl requestor, Size measureBounds, IEnumerable siblingItems, DragablzItem dragItem); + void OrganiseOnDrag(DragablzItemsControl requestor, Size measureBounds, IEnumerable siblingItems, DragablzItem dragItem); + void OrganiseOnDragCompleted(DragablzItemsControl requestor, Size measureBounds, IEnumerable siblingItems, DragablzItem dragItem); + Point ConstrainLocation(DragablzItemsControl requestor, Size measureBounds, Point itemCurrentLocation, Size itemCurrentSize, Point itemDesiredLocation, Size itemDesiredSize); + Size Measure(DragablzItemsControl requestor, Size availableSize, IEnumerable items); + IEnumerable Sort(IEnumerable items); + } +} diff --git a/Source/3rdparty/Dragablz/IManualInterTabClient.cs b/Source/3rdparty/Dragablz/IManualInterTabClient.cs new file mode 100644 index 0000000000..5d3f70a35b --- /dev/null +++ b/Source/3rdparty/Dragablz/IManualInterTabClient.cs @@ -0,0 +1,8 @@ +namespace Dragablz +{ + public interface IManualInterTabClient : IInterTabClient + { + void Add(object item); + void Remove(object item); + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/INewTabHost.cs b/Source/3rdparty/Dragablz/INewTabHost.cs new file mode 100644 index 0000000000..74a98674d8 --- /dev/null +++ b/Source/3rdparty/Dragablz/INewTabHost.cs @@ -0,0 +1,10 @@ +using System.Windows; + +namespace Dragablz +{ + public interface INewTabHost where TElement : UIElement + { + TElement Container { get; } + TabablzControl TabablzControl { get; } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/InterTabController.cs b/Source/3rdparty/Dragablz/InterTabController.cs new file mode 100644 index 0000000000..f4e8923a3e --- /dev/null +++ b/Source/3rdparty/Dragablz/InterTabController.cs @@ -0,0 +1,72 @@ +using System.Windows; + +namespace Dragablz +{ + public class InterTabController : FrameworkElement + { + public InterTabController() + { + HorizontalPopoutGrace = 8; + VerticalPopoutGrace = 8; + MoveWindowWithSolitaryTabs = true; + } + + public static readonly DependencyProperty HorizontalPopoutGraceProperty = DependencyProperty.Register( + "HorizontalPopoutGrace", typeof(double), typeof(InterTabController), new PropertyMetadata(8.0)); + + public double HorizontalPopoutGrace + { + get { return (double)GetValue(HorizontalPopoutGraceProperty); } + set { SetValue(HorizontalPopoutGraceProperty, value); } + } + + public static readonly DependencyProperty VerticalPopoutGraceProperty = DependencyProperty.Register( + "VerticalPopoutGrace", typeof(double), typeof(InterTabController), new PropertyMetadata(8.0)); + + public double VerticalPopoutGrace + { + get { return (double)GetValue(VerticalPopoutGraceProperty); } + set { SetValue(VerticalPopoutGraceProperty, value); } + } + + public static readonly DependencyProperty MoveWindowWithSolitaryTabsProperty = DependencyProperty.Register( + "MoveWindowWithSolitaryTabs", typeof(bool), typeof(InterTabController), new PropertyMetadata(true)); + + public bool MoveWindowWithSolitaryTabs + { + get { return (bool)GetValue(MoveWindowWithSolitaryTabsProperty); } + set { SetValue(MoveWindowWithSolitaryTabsProperty, value); } + } + + public static readonly DependencyProperty InterTabClientProperty = DependencyProperty.Register( + "InterTabClient", typeof(IInterTabClient), typeof(InterTabController), + new PropertyMetadata(new DefaultInterTabClient())); + + public IInterTabClient InterTabClient + { + get { return (IInterTabClient)GetValue(InterTabClientProperty); } + set { SetValue(InterTabClientProperty, value); } + } + + public static readonly DependencyProperty PartitionProperty = DependencyProperty.Register( + "Partition", typeof(object), typeof(InterTabController), new PropertyMetadata(default(object))); + + /// + /// The partition allows on or more tab environments in a single application. Only tabs which have a tab controller + /// with a common partition will be allowed to have tabs dragged between them. null is a valid partition (i.e global). + /// + public object Partition + { + get { return (object)GetValue(PartitionProperty); } + set { SetValue(PartitionProperty, value); } + } + + /* + /// + /// The partition allows on or more tab environments in a single application. Only tabs which have a tab controller + /// with a common partition will be allowed to have tabs dragged between them. null is a valid partition (i.e global). + /// + public string Partition { get; set; } + */ + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/ItemActionCallbackArgs.cs b/Source/3rdparty/Dragablz/ItemActionCallbackArgs.cs new file mode 100644 index 0000000000..3a471ce404 --- /dev/null +++ b/Source/3rdparty/Dragablz/ItemActionCallbackArgs.cs @@ -0,0 +1,47 @@ +using System; +using System.Windows; + +namespace Dragablz +{ + public delegate void ItemActionCallback(ItemActionCallbackArgs args); + + public class ItemActionCallbackArgs where TOwner : FrameworkElement + { + private readonly Window _window; + private readonly TOwner _owner; + private readonly DragablzItem _dragablzItem; + + public ItemActionCallbackArgs(Window window, TOwner owner, DragablzItem dragablzItem) + { + if (window == null) throw new ArgumentNullException("window"); + if (owner == null) throw new ArgumentNullException("owner"); + if (dragablzItem == null) throw new ArgumentNullException("dragablzItem"); + + _window = window; + _owner = owner; + _dragablzItem = dragablzItem; + } + + public Window Window + { + get { return _window; } + } + + public TOwner Owner + { + get { return _owner; } + } + + public DragablzItem DragablzItem + { + get { return _dragablzItem; } + } + + public bool IsCancelled { get; private set; } + + public void Cancel() + { + IsCancelled = true; + } + } +} diff --git a/Source/3rdparty/Dragablz/LICENSE b/Source/3rdparty/Dragablz/LICENSE new file mode 100644 index 0000000000..320040e619 --- /dev/null +++ b/Source/3rdparty/Dragablz/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) James Willock, Mulholland Software and Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/LocationChangedEventArgs.cs b/Source/3rdparty/Dragablz/LocationChangedEventArgs.cs new file mode 100644 index 0000000000..ea920b0b8d --- /dev/null +++ b/Source/3rdparty/Dragablz/LocationChangedEventArgs.cs @@ -0,0 +1,29 @@ +using System; +using System.Windows; + +namespace Dragablz +{ + public class LocationChangedEventArgs : EventArgs + { + private readonly object _item; + private readonly Point _location; + + public LocationChangedEventArgs(object item, Point location) + { + if (item == null) throw new ArgumentNullException("item"); + + _item = item; + _location = location; + } + + public object Item + { + get { return _item; } + } + + public Point Location + { + get { return _location; } + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/LocationHint.cs b/Source/3rdparty/Dragablz/LocationHint.cs new file mode 100644 index 0000000000..7efeb77eb8 --- /dev/null +++ b/Source/3rdparty/Dragablz/LocationHint.cs @@ -0,0 +1,26 @@ +namespace Dragablz +{ + /// + /// Specifies where an item should appear when added to tab control, as the headers order do not + /// specifically correlate to the order of the the source items. + /// + public enum AddLocationHint + { + /// + /// Display item in the first position. + /// + First, + /// + /// Display item in the first position. + /// + Last, + /// + /// Display an item prior to the selected, or specified item. + /// + Prior, + /// + /// Display an item after the selected, or specified item. + /// + After + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/MergeTargetArea.cs b/Source/3rdparty/Dragablz/MergeTargetArea.cs new file mode 100644 index 0000000000..f87e239e9f --- /dev/null +++ b/Source/3rdparty/Dragablz/MergeTargetArea.cs @@ -0,0 +1,18 @@ +namespace Dragablz +{ + /// + /// Defines which part of a accepts a tab which is dragged (as a window) over it. + /// + public enum MergeTargetArea + { + /// + /// Only the area occupied by the header items (the default). + /// + HeaderItems, + + /// + /// The whole header panel (), including the empty area behind the last tab. + /// + HeaderPanel + } +} diff --git a/Source/3rdparty/Dragablz/MergeTargetCalculator.cs b/Source/3rdparty/Dragablz/MergeTargetCalculator.cs new file mode 100644 index 0000000000..ed2f264445 --- /dev/null +++ b/Source/3rdparty/Dragablz/MergeTargetCalculator.cs @@ -0,0 +1,66 @@ +using System; +using System.Windows; +using System.Windows.Controls; + +namespace Dragablz +{ + /// + /// Pure geometry used to decide where a dragged tab can be merged into a . + /// + internal static class MergeTargetCalculator + { + /// + /// Calculates the rectangle which accepts a dragged tab. + /// + /// Bounds of the header items control. + /// Bounds of the header panel, only used for . + /// Requested area. + /// Horizontal for top/bottom tab strips, vertical for left/right ones. + /// + /// End of the last fixed item along the main axis, relative to the start of the items control (0 if there is none). + /// + public static Rect GetBounds(Rect itemsBounds, Rect? panelBounds, MergeTargetArea area, Orientation orientation, + double fixedItemsEnd) + { + var bounds = area == MergeTargetArea.HeaderPanel && panelBounds.HasValue + ? panelBounds.Value + : itemsBounds; + + if (fixedItemsEnd <= 0) return bounds; + + if (orientation == Orientation.Horizontal) + { + var left = Math.Max(bounds.Left, itemsBounds.Left + fixedItemsEnd); + return new Rect(left, bounds.Top, Math.Max(0, bounds.Right - left), bounds.Height); + } + + var top = Math.Max(bounds.Top, itemsBounds.Top + fixedItemsEnd); + return new Rect(bounds.Left, top, bounds.Width, Math.Max(0, bounds.Bottom - top)); + } + + /// + /// Grows a rectangle on all sides, e.g. to detect a cursor which is near a merge target. + /// + public static Rect Inflate(Rect bounds, double amount) + { + if (bounds.IsEmpty) return bounds; + amount = Math.Max(0, amount); + return new Rect(bounds.Left - amount, bounds.Top - amount, bounds.Width + 2 * amount, + bounds.Height + 2 * amount); + } + + /// + /// Keeps the position of an inserted tab between the end of the fixed items and the end of the last item, + /// so a tab dropped on the empty part of the header ends up behind the last tab. + /// + /// Position along the main axis, relative to the items control. + /// End of the last fixed item (0 if there is none). + /// End of the last item (0 if there are no items). + public static double ClampInsertPosition(double desiredPosition, double fixedItemsEnd, double lastItemEnd) + { + var min = Math.Max(0, fixedItemsEnd); + var max = Math.Max(min, lastItemEnd); + return Math.Min(Math.Max(desiredPosition, min), max); + } + } +} diff --git a/Source/3rdparty/Dragablz/MoveItemRequest.cs b/Source/3rdparty/Dragablz/MoveItemRequest.cs new file mode 100644 index 0000000000..fd1c87be46 --- /dev/null +++ b/Source/3rdparty/Dragablz/MoveItemRequest.cs @@ -0,0 +1,31 @@ +namespace Dragablz +{ + public class MoveItemRequest + { + private readonly object _item; + private readonly object _context; + private readonly AddLocationHint _addLocationHint; + + public MoveItemRequest(object item, object context, AddLocationHint addLocationHint) + { + _item = item; + _context = context; + _addLocationHint = addLocationHint; + } + + public object Item + { + get { return _item; } + } + + public object Context + { + get { return _context; } + } + + public AddLocationHint AddLocationHint + { + get { return _addLocationHint; } + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/NewTabHost.cs b/Source/3rdparty/Dragablz/NewTabHost.cs new file mode 100644 index 0000000000..c9e37c4d70 --- /dev/null +++ b/Source/3rdparty/Dragablz/NewTabHost.cs @@ -0,0 +1,30 @@ +using System; +using System.Windows; + +namespace Dragablz +{ + public class NewTabHost : INewTabHost where TElement : UIElement + { + private readonly TElement _container; + private readonly TabablzControl _tabablzControl; + + public NewTabHost(TElement container, TabablzControl tabablzControl) + { + if (container == null) throw new ArgumentNullException("container"); + if (tabablzControl == null) throw new ArgumentNullException("tabablzControl"); + + _container = container; + _tabablzControl = tabablzControl; + } + + public TElement Container + { + get { return _container; } + } + + public TabablzControl TabablzControl + { + get { return _tabablzControl; } + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/OrderChangedEventArgs.cs b/Source/3rdparty/Dragablz/OrderChangedEventArgs.cs new file mode 100644 index 0000000000..0ad749f665 --- /dev/null +++ b/Source/3rdparty/Dragablz/OrderChangedEventArgs.cs @@ -0,0 +1,28 @@ +using System; + +namespace Dragablz +{ + public class OrderChangedEventArgs : EventArgs + { + private readonly object[] _previousOrder; + private readonly object[] _newOrder; + + public OrderChangedEventArgs(object[] previousOrder, object[] newOrder) + { + if (newOrder == null) throw new ArgumentNullException("newOrder"); + + _previousOrder = previousOrder; + _newOrder = newOrder; + } + + public object[] PreviousOrder + { + get { return _previousOrder; } + } + + public object[] NewOrder + { + get { return _newOrder; } + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/PositionMonitor.cs b/Source/3rdparty/Dragablz/PositionMonitor.cs new file mode 100644 index 0000000000..dfaf896284 --- /dev/null +++ b/Source/3rdparty/Dragablz/PositionMonitor.cs @@ -0,0 +1,31 @@ +using System; +using System.Text; +using System.Threading.Tasks; + +namespace Dragablz +{ + /// + /// Consumers can provide a position monitor to receive updates regarding the location of an item. + /// + /// + /// A can be used to listen to changes + /// instead of routed events, which can be easier in a MVVM scenario. + /// + public class PositionMonitor + { + /// + /// Raised when the X,Y coordinate of a changes. + /// + public event EventHandler LocationChanged; + + internal virtual void OnLocationChanged(LocationChangedEventArgs e) + { + if (e == null) throw new ArgumentNullException("e"); + + var handler = LocationChanged; + handler?.Invoke(this, e); + } + + internal virtual void ItemsChanged() { } + } +} diff --git a/Source/3rdparty/Dragablz/Properties/AssemblyInfo.cs b/Source/3rdparty/Dragablz/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000..b29af62aa2 --- /dev/null +++ b/Source/3rdparty/Dragablz/Properties/AssemblyInfo.cs @@ -0,0 +1,63 @@ +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Windows; +using System.Windows.Markup; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Dragablz")] +[assembly: AssemblyDescription("Dragable tabable")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Mulholland Software Ltd/James Willock")] +[assembly: AssemblyProduct("Dragablz")] +[assembly: AssemblyCopyright("Copyright © 2019")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] +[assembly: XmlnsPrefix("http://dragablz.net/winfx/xaml/dragablz", "dragablz")] +[assembly: XmlnsDefinition("http://dragablz.net/winfx/xaml/dragablz", + "Dragablz")] +[assembly: XmlnsPrefix("http://dragablz.net/winfx/xaml/dockablz", "dockablz")] +[assembly: XmlnsDefinition("http://dragablz.net/winfx/xaml/dockablz", + "Dragablz.Dockablz")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +//In order to begin building localizable applications, set +//CultureYouAreCodingWith in your .csproj file +//inside a . For example, if you are using US english +//in your source files, set the to en-US. Then uncomment +//the NeutralResourceLanguage attribute below. Update the "en-US" in +//the line below to match the UICulture setting in the project file. + +//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] + + +[assembly: ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] + + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("0.0.4.0")] +[assembly: AssemblyFileVersion("0.0.4.0")] + diff --git a/Source/3rdparty/Dragablz/Properties/Resources.Designer.cs b/Source/3rdparty/Dragablz/Properties/Resources.Designer.cs new file mode 100644 index 0000000000..eb1fe1499e --- /dev/null +++ b/Source/3rdparty/Dragablz/Properties/Resources.Designer.cs @@ -0,0 +1,63 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.34014 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Dragablz.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Dragablz.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/Source/3rdparty/Dragablz/Properties/Resources.resx b/Source/3rdparty/Dragablz/Properties/Resources.resx new file mode 100644 index 0000000000..af7dbebbac --- /dev/null +++ b/Source/3rdparty/Dragablz/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Properties/Settings.Designer.cs b/Source/3rdparty/Dragablz/Properties/Settings.Designer.cs new file mode 100644 index 0000000000..af46672de2 --- /dev/null +++ b/Source/3rdparty/Dragablz/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.34014 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Dragablz.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/Source/3rdparty/Dragablz/Properties/Settings.settings b/Source/3rdparty/Dragablz/Properties/Settings.settings new file mode 100644 index 0000000000..033d7a5e9e --- /dev/null +++ b/Source/3rdparty/Dragablz/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/README.md b/Source/3rdparty/Dragablz/README.md new file mode 100644 index 0000000000..40efe3d5db --- /dev/null +++ b/Source/3rdparty/Dragablz/README.md @@ -0,0 +1,27 @@ +# Dragablz + +Tearable tab control for WPF (tabs, drag out to a new window, merge, split layouts), used for the tabs of the +NETworkManager tools. + +| | | +|---|---| +| Original | [ButchersBoy/Dragablz](https://github.com/ButchersBoy/Dragablz) by James Willock, last upstream commit `e493913` (2022-09-09) | +| Fork | [BornToBeRoot/Dragablz](https://github.com/BornToBeRoot/Dragablz), commit `5415e71` (2026-11-14) - was the git submodule `Source/3rdparty/Dragablz` until it was copied here | +| License | MIT, see [LICENSE](LICENSE) - keep this file and the copyright notice with the code | +| Changes | See [CHANGELOG.md](CHANGELOG.md) (all changes compared to the original) | + +Only the library is included (no demos, tests or NuGet package) and it's stripped to what NETworkManager uses. +The project, assembly and namespaces are still called `Dragablz` / `Dragablz.Dockablz`, so the `xmlns` and pack URIs +(`pack://application:,,,/Dragablz;component/Themes/MahApps.xaml`) in the application stay unchanged. + +## Maintenance + +- This folder is the source of truth now; the fork is kept for history only. +- Change the code only when a feature or fix of NETworkManager needs it, keep the changes small and add an entry to + [CHANGELOG.md](CHANGELOG.md). +- Don't reformat or restyle the code (`Source/.editorconfig` marks it as generated code, so analyzers and formatting + rules ignore it). +- The file version in `Properties/AssemblyInfo.cs` is set to the NETworkManager version by AppVeyor (`appveyor.yml`), + otherwise the MSI doesn't replace `Dragablz.dll` on an upgrade - keep the `AssemblyFileVersion` attribute. +- The license is also shipped with the application (`Source/NETworkManager.Documentation/Licenses/Dragablz.txt`, shown + in the about / license view via `LibraryManager`). diff --git a/Source/3rdparty/Dragablz/Referenceless/AnonymousDisposable.cs b/Source/3rdparty/Dragablz/Referenceless/AnonymousDisposable.cs new file mode 100644 index 0000000000..44a96dda4d --- /dev/null +++ b/Source/3rdparty/Dragablz/Referenceless/AnonymousDisposable.cs @@ -0,0 +1,31 @@ +using System; +using System.Threading; + +namespace Dragablz.Referenceless +{ + internal sealed class AnonymousDisposable : ICancelable, IDisposable + { + private volatile Action _dispose; + + public bool IsDisposed + { + get + { + return this._dispose == null; + } + } + + public AnonymousDisposable(Action dispose) + { + this._dispose = dispose; + } + + public void Dispose() + { + var action = Interlocked.Exchange(ref _dispose, (Action)null); + if (action == null) + return; + action(); + } + } +} diff --git a/Source/3rdparty/Dragablz/Referenceless/DefaultDisposable.cs b/Source/3rdparty/Dragablz/Referenceless/DefaultDisposable.cs new file mode 100644 index 0000000000..9cb570300c --- /dev/null +++ b/Source/3rdparty/Dragablz/Referenceless/DefaultDisposable.cs @@ -0,0 +1,21 @@ +using System; + +namespace Dragablz.Referenceless +{ + internal sealed class DefaultDisposable : IDisposable + { + public static readonly DefaultDisposable Instance = new DefaultDisposable(); + + static DefaultDisposable() + { + } + + private DefaultDisposable() + { + } + + public void Dispose() + { + } + } +} diff --git a/Source/3rdparty/Dragablz/Referenceless/Disposable.cs b/Source/3rdparty/Dragablz/Referenceless/Disposable.cs new file mode 100644 index 0000000000..75752b96ca --- /dev/null +++ b/Source/3rdparty/Dragablz/Referenceless/Disposable.cs @@ -0,0 +1,23 @@ +using System; + +namespace Dragablz.Referenceless +{ + internal static class Disposable + { + public static IDisposable Empty + { + get + { + return (IDisposable)DefaultDisposable.Instance; + } + } + + public static IDisposable Create(Action dispose) + { + if (dispose == null) + throw new ArgumentNullException("dispose"); + else + return (IDisposable)new AnonymousDisposable(dispose); + } + } +} diff --git a/Source/3rdparty/Dragablz/Referenceless/ICancelable.cs b/Source/3rdparty/Dragablz/Referenceless/ICancelable.cs new file mode 100644 index 0000000000..350b1baa0c --- /dev/null +++ b/Source/3rdparty/Dragablz/Referenceless/ICancelable.cs @@ -0,0 +1,9 @@ +using System; + +namespace Dragablz.Referenceless +{ + internal interface ICancelable : IDisposable + { + bool IsDisposed { get; } + } +} diff --git a/Source/3rdparty/Dragablz/Referenceless/SerialDisposable.cs b/Source/3rdparty/Dragablz/Referenceless/SerialDisposable.cs new file mode 100644 index 0000000000..be94b4dec3 --- /dev/null +++ b/Source/3rdparty/Dragablz/Referenceless/SerialDisposable.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Dragablz.Referenceless +{ + internal sealed class SerialDisposable : ICancelable, IDisposable + { + private readonly object _gate = new object(); + private IDisposable _current; + private bool _disposed; + + /// + /// Gets a value that indicates whether the object is disposed. + /// + /// + public bool IsDisposed + { + get + { + lock (this._gate) + return this._disposed; + } + } + + /// + /// Gets or sets the underlying disposable. + /// + /// + /// + /// + /// If the SerialDisposable has already been disposed, assignment to this property causes immediate disposal of the given disposable object. Assigning this property disposes the previous disposable object. + /// + public IDisposable Disposable + { + get + { + return this._current; + } + set + { + bool flag = false; + IDisposable disposable = (IDisposable)null; + lock (this._gate) + { + flag = this._disposed; + if (!flag) + { + disposable = this._current; + this._current = value; + } + } + if (disposable != null) + disposable.Dispose(); + if (!flag || value == null) + return; + value.Dispose(); + } + } + + /// + /// Disposes the underlying disposable as well as all future replacements. + /// + /// + public void Dispose() + { + IDisposable disposable = (IDisposable)null; + lock (this._gate) + { + if (!this._disposed) + { + this._disposed = true; + disposable = this._current; + this._current = (IDisposable)null; + } + } + if (disposable == null) + return; + disposable.Dispose(); + } + } +} diff --git a/Source/3rdparty/Dragablz/StackOrganiser.cs b/Source/3rdparty/Dragablz/StackOrganiser.cs new file mode 100644 index 0000000000..e891927685 --- /dev/null +++ b/Source/3rdparty/Dragablz/StackOrganiser.cs @@ -0,0 +1,309 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media.Animation; +using Dragablz.Core; + +namespace Dragablz +{ + public abstract class StackOrganiser : IItemsOrganiser + { + private readonly Orientation _orientation; + private readonly double _itemOffset; + private readonly Func _getDesiredSize; + private readonly Func _getLocation; + private readonly DependencyProperty _canvasDependencyProperty; + private readonly Action _setLocation; + + private readonly Dictionary _activeStoryboardTargetLocations = + new Dictionary(); + + protected StackOrganiser(Orientation orientation, double itemOffset = 0) + { + _orientation = orientation; + _itemOffset = itemOffset; + + switch (orientation) + { + case Orientation.Horizontal: + _getDesiredSize = item => item.DesiredSize.Width; + _getLocation = item => item.X; + _setLocation = (item, coord) => item.SetCurrentValue(DragablzItem.XProperty, coord); + _canvasDependencyProperty = Canvas.LeftProperty; + break; + case Orientation.Vertical: + _getDesiredSize = item => item.DesiredSize.Height; + _getLocation = item => item.Y; + _setLocation = (item, coord) => item.SetCurrentValue(DragablzItem.YProperty, coord); + _canvasDependencyProperty = Canvas.TopProperty; + break; + default: + throw new ArgumentOutOfRangeException("orientation"); + } + } + + #region LocationInfo + + private class LocationInfo + { + private readonly DragablzItem _item; + private readonly double _start; + private readonly double _mid; + private readonly double _end; + + public LocationInfo(DragablzItem item, double start, double mid, double end) + { + _item = item; + _start = start; + _mid = mid; + _end = end; + } + + public double Start + { + get { return _start; } + } + + public double Mid + { + get { return _mid; } + } + + public double End + { + get { return _end; } + } + + public DragablzItem Item + { + get { return _item; } + } + } + + #endregion + + public virtual Orientation Orientation + { + get { return _orientation; } + } + + public virtual void Organise(DragablzItemsControl requestor, Size measureBounds, IEnumerable items) + { + if (items == null) throw new ArgumentNullException("items"); + + OrganiseInternal( + requestor, + measureBounds, + items.Select((di, idx) => new Tuple(idx, di)) + .OrderBy(tuple => tuple, + MultiComparer>.Ascending(tuple => _getLocation(tuple.Item2)) + .ThenAscending(tuple => tuple.Item1)) + .Select(tuple => tuple.Item2)); + } + + public virtual void Organise(DragablzItemsControl requestor, Size measureBounds, IOrderedEnumerable items) + { + if (items == null) throw new ArgumentNullException("items"); + + OrganiseInternal( + requestor, + measureBounds, + items); + } + + private void OrganiseInternal(DragablzItemsControl requestor, Size measureBounds, + IEnumerable items) + { + var currentCoord = 0.0; + var z = int.MaxValue; + var logicalIndex = 0; + foreach (var newItem in items) + { + Panel.SetZIndex(newItem, newItem.IsSelected ? int.MaxValue : --z); + SetLocation(newItem, currentCoord); + newItem.LogicalIndex = logicalIndex++; + newItem.Measure(measureBounds); + var desiredSize = _getDesiredSize(newItem); + if (desiredSize == 0.0) desiredSize = 1.0; //no measure? create something to help sorting + currentCoord += desiredSize + _itemOffset; + } + } + + + public virtual void OrganiseOnMouseDownWithin(DragablzItemsControl requestor, Size measureBounds, + List siblingItems, DragablzItem dragablzItem) + { + + } + + private IDictionary _siblingItemLocationOnDragStart; + + public virtual void OrganiseOnDragStarted(DragablzItemsControl requestor, Size measureBounds, + IEnumerable siblingItems, DragablzItem dragItem) + { + if (siblingItems == null) throw new ArgumentNullException("siblingItems"); + if (dragItem == null) throw new ArgumentNullException("dragItem"); + + _siblingItemLocationOnDragStart = siblingItems.Select(GetLocationInfo).ToDictionary(loc => loc.Item); + } + + public virtual void OrganiseOnDrag(DragablzItemsControl requestor, Size measureBounds, + IEnumerable siblingItems, DragablzItem dragItem) + { + if (siblingItems == null) throw new ArgumentNullException("siblingItems"); + if (dragItem == null) throw new ArgumentNullException("dragItem"); + + var currentLocations = siblingItems + .Select(GetLocationInfo) + .Union(new[] { GetLocationInfo(dragItem) }) + .OrderBy(loc => loc.Item == dragItem ? loc.Start : _siblingItemLocationOnDragStart[loc.Item].Start); + + var currentCoord = 0.0; + var zIndex = int.MaxValue; + foreach (var location in currentLocations) + { + if (!Equals(location.Item, dragItem)) + { + SendToLocation(location.Item, currentCoord); + Panel.SetZIndex(location.Item, --zIndex); + } + currentCoord += _getDesiredSize(location.Item) + _itemOffset; + } + Panel.SetZIndex(dragItem, int.MaxValue); + } + + public virtual void OrganiseOnDragCompleted(DragablzItemsControl requestor, Size measureBounds, + IEnumerable siblingItems, DragablzItem dragItem) + { + if (siblingItems == null) throw new ArgumentNullException("siblingItems"); + var currentLocations = siblingItems + .Select(GetLocationInfo) + .Union(new[] { GetLocationInfo(dragItem) }) + .OrderBy(loc => loc.Item == dragItem ? loc.Start : _siblingItemLocationOnDragStart[loc.Item].Start); + + var currentCoord = 0.0; + var z = int.MaxValue; + var logicalIndex = 0; + foreach (var location in currentLocations) + { + SetLocation(location.Item, currentCoord); + currentCoord += _getDesiredSize(location.Item) + _itemOffset; + Panel.SetZIndex(location.Item, --z); + location.Item.LogicalIndex = logicalIndex++; + } + Panel.SetZIndex(dragItem, int.MaxValue); + } + + public virtual Point ConstrainLocation(DragablzItemsControl requestor, Size measureBounds, Point itemCurrentLocation, + Size itemCurrentSize, Point itemDesiredLocation, Size itemDesiredSize) + { + var fixedItems = requestor.FixedItemCount; + var lowerBound = fixedItems == 0 + ? -1d + : GetLocationInfo(requestor.DragablzItems() + .Take(fixedItems) + .Last()).End + _itemOffset - 1; + + return new Point( + _orientation == Orientation.Vertical + ? 0 + : Math.Min(Math.Max(lowerBound, itemDesiredLocation.X), (measureBounds.Width) + 1), + _orientation == Orientation.Horizontal + ? 0 + : Math.Min(Math.Max(lowerBound, itemDesiredLocation.Y), (measureBounds.Height) + 1) + ); + } + + public virtual Size Measure(DragablzItemsControl requestor, Size availableSize, IEnumerable items) + { + if (items == null) throw new ArgumentNullException("items"); + + var size = new Size(double.PositiveInfinity, double.PositiveInfinity); + + double width = 0, height = 0; + var isFirst = true; + foreach (var dragablzItem in items) + { + dragablzItem.Measure(size); + if (_orientation == Orientation.Horizontal) + { + width += !dragablzItem.IsLoaded ? dragablzItem.DesiredSize.Width : dragablzItem.ActualWidth; + if (!isFirst) + width += _itemOffset; + height = Math.Max(height, + !dragablzItem.IsLoaded ? dragablzItem.DesiredSize.Height : dragablzItem.ActualHeight); + } + else + { + width = Math.Max(width, + !dragablzItem.IsLoaded ? dragablzItem.DesiredSize.Width : dragablzItem.ActualWidth); + height += !dragablzItem.IsLoaded ? dragablzItem.DesiredSize.Height : dragablzItem.ActualHeight; + if (!isFirst) + height += _itemOffset; + } + + isFirst = false; + } + + return new Size(Math.Max(width, 0), Math.Max(height, 0)); + } + + public virtual IEnumerable Sort(IEnumerable items) + { + if (items == null) throw new ArgumentNullException("items"); + + return items.OrderBy(i => GetLocationInfo(i).Start); + } + + private void SetLocation(DragablzItem dragablzItem, double location) + { + _setLocation(dragablzItem, location); + } + + private void SendToLocation(DragablzItem dragablzItem, double location) + { + double activeTarget; + if (Math.Abs(_getLocation(dragablzItem) - location) < 1.0 + || + _activeStoryboardTargetLocations.TryGetValue(dragablzItem, out activeTarget) + && Math.Abs(activeTarget - location) < 1.0) + { + return; + } + + _activeStoryboardTargetLocations[dragablzItem] = location; + + var storyboard = new Storyboard { FillBehavior = FillBehavior.Stop }; + storyboard.WhenComplete(sb => + { + _setLocation(dragablzItem, location); + sb.Remove(dragablzItem); + _activeStoryboardTargetLocations.Remove(dragablzItem); + }); + + var timeline = new DoubleAnimationUsingKeyFrames(); + timeline.SetValue(Storyboard.TargetPropertyProperty, new PropertyPath(_canvasDependencyProperty)); + timeline.KeyFrames.Add( + new EasingDoubleKeyFrame(location, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(200))) + { + EasingFunction = new CubicEase() { EasingMode = EasingMode.EaseOut } + }); + storyboard.Children.Add(timeline); + storyboard.Begin(dragablzItem, true); + } + + private LocationInfo GetLocationInfo(DragablzItem item) + { + var size = _getDesiredSize(item); + double startLocation; + if (!_activeStoryboardTargetLocations.TryGetValue(item, out startLocation)) + startLocation = _getLocation(item); + var midLocation = startLocation + size / 2; + var endLocation = startLocation + size; + + return new LocationInfo(item, startLocation, midLocation, endLocation); + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/StackPositionMonitor.cs b/Source/3rdparty/Dragablz/StackPositionMonitor.cs new file mode 100644 index 0000000000..fbd6c4c5a6 --- /dev/null +++ b/Source/3rdparty/Dragablz/StackPositionMonitor.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Windows.Controls; + +namespace Dragablz +{ + /// + /// A linear position monitor simplifies the montoring of the order of items, where they are laid out + /// horizontally or vertically (typically via a . + /// + public abstract class StackPositionMonitor : PositionMonitor + { + private readonly Func _getLocation; + + protected StackPositionMonitor(Orientation orientation) + { + switch (orientation) + { + case Orientation.Horizontal: + _getLocation = item => item.X; + break; + case Orientation.Vertical: + _getLocation = item => item.Y; + break; + default: + throw new ArgumentOutOfRangeException("orientation"); + } + } + + public event EventHandler OrderChanged; + + internal virtual void OnOrderChanged(OrderChangedEventArgs e) + { + var handler = OrderChanged; + if (handler != null) handler(this, e); + } + + internal IEnumerable Sort(IEnumerable items) + { + if (items == null) throw new ArgumentNullException("items"); + + return items.OrderBy(i => _getLocation(i)); + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/StoryboardCompletionListener.cs b/Source/3rdparty/Dragablz/StoryboardCompletionListener.cs new file mode 100644 index 0000000000..2929d69087 --- /dev/null +++ b/Source/3rdparty/Dragablz/StoryboardCompletionListener.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Windows.Media.Animation; + +namespace Dragablz +{ + internal class StoryboardCompletionListener + { + private readonly Storyboard _storyboard; + private readonly Action _continuation; + + public StoryboardCompletionListener(Storyboard storyboard, Action continuation) + { + if (storyboard == null) throw new ArgumentNullException("storyboard"); + if (continuation == null) throw new ArgumentNullException("continuation"); + + _storyboard = storyboard; + _continuation = continuation; + + _storyboard.Completed += StoryboardOnCompleted; + } + + private void StoryboardOnCompleted(object sender, EventArgs eventArgs) + { + _storyboard.Completed -= StoryboardOnCompleted; + _continuation(_storyboard); + } + } + + internal static class StoryboardCompletionListenerExtension + { + private static readonly IDictionary> ContinuationIndex = new Dictionary>(); + + public static void WhenComplete(this Storyboard storyboard, Action continuation) + { + // ReSharper disable once ObjectCreationAsStatement + new StoryboardCompletionListener(storyboard, continuation); + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/TabEmptiedResponse.cs b/Source/3rdparty/Dragablz/TabEmptiedResponse.cs new file mode 100644 index 0000000000..42e7a850c0 --- /dev/null +++ b/Source/3rdparty/Dragablz/TabEmptiedResponse.cs @@ -0,0 +1,20 @@ +namespace Dragablz +{ + public enum TabEmptiedResponse + { + /// + /// Allow the Window and Layout branch to be closed automatically. + /// + CloseWindowOrLayoutBranch, + + /// + /// Allow the Layout branch to be closed automatically, but not the window. + /// + CloseLayoutBranch, + + /// + /// The window will not be closed by the , probably meaning the implementor will close the window manually + /// + DoNothing + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/TabablzControl.cs b/Source/3rdparty/Dragablz/TabablzControl.cs new file mode 100644 index 0000000000..5450b55feb --- /dev/null +++ b/Source/3rdparty/Dragablz/TabablzControl.cs @@ -0,0 +1,1821 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Linq; +using System.Windows; +using System.Windows.Automation.Peers; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Data; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Threading; +using Dragablz.Core; +using Dragablz.Dockablz; +using Dragablz.Referenceless; + +namespace Dragablz +{ + //original code specific to keeping visual tree "alive" sourced from http://stackoverflow.com/questions/12432062/binding-to-itemssource-of-tabcontrol-in-wpf + + /// + /// Extended tab control which supports tab repositioning, and drag and drop. Also + /// uses the common WPF technique for pesisting the visual tree across tabs. + /// + [TemplatePart(Name = HeaderItemsControlPartName, Type = typeof(DragablzItemsControl))] + [TemplatePart(Name = ItemsHolderPartName, Type = typeof(Panel))] + [TemplatePart(Name = HeaderPanelPartName, Type = typeof(FrameworkElement))] + public class TabablzControl : TabControl + { + /// + /// Template part. + /// + public const string HeaderItemsControlPartName = "PART_HeaderItemsControl"; + /// + /// Template part. + /// + public const string ItemsHolderPartName = "PART_ItemsHolder"; + /// + /// Optional template part. The whole header (tab bar), used for . + /// + public const string HeaderPanelPartName = "PART_HeaderPanel"; + + /// + /// Routed command which can be used to close a tab. + /// + public static RoutedCommand CloseItemCommand = new RoutedUICommand("Close", "Close", typeof(TabablzControl)); + + /// + /// Routed command which can be used to add a new tab. See . + /// + public static RoutedCommand AddItemCommand = new RoutedUICommand("Add", "Add", typeof(TabablzControl)); + + private static readonly HashSet LoadedInstances = new HashSet(); + private static readonly HashSet VisibleInstances = new HashSet(); + private static readonly List MergeTargetsInDrag = new List(); + private static TabablzControl _mergeHintOwner; + + private Panel _itemsHolder; + private TabHeaderDragStartInformation _tabHeaderDragStartInformation; + private WeakReference _previousSelection; + private DragablzItemsControl _dragablzItemsControl; + private FrameworkElement _headerPanel; + private bool _isMergeHintWireUpPending; + private IDisposable _templateSubscription; + private readonly SerialDisposable _windowSubscription = new SerialDisposable(); + + private InterTabTransfer _interTabTransfer; + + static TabablzControl() + { + DefaultStyleKeyProperty.OverrideMetadata(typeof(TabablzControl), new FrameworkPropertyMetadata(typeof(TabablzControl))); + CommandManager.RegisterClassCommandBinding(typeof(FrameworkElement), new CommandBinding(CloseItemCommand, CloseItemClassHandler, CloseItemCanExecuteClassHandler)); + } + + /// + /// Default constructor. + /// + public TabablzControl() + { + AddHandler(DragablzItem.DragStarted, new DragablzDragStartedEventHandler(ItemDragStarted), true); + AddHandler(DragablzItem.PreviewDragDelta, new DragablzDragDeltaEventHandler(PreviewItemDragDelta), true); + AddHandler(DragablzItem.DragDelta, new DragablzDragDeltaEventHandler(ItemDragDelta), true); + AddHandler(DragablzItem.DragCompleted, new DragablzDragCompletedEventHandler(ItemDragCompleted), true); + CommandBindings.Add(new CommandBinding(AddItemCommand, AddItemHandler)); + + Loaded += OnLoaded; + Unloaded += OnUnloaded; + IsVisibleChanged += OnIsVisibleChanged; + } + + public static readonly DependencyProperty CustomHeaderItemStyleProperty = DependencyProperty.Register( + "CustomHeaderItemStyle", typeof(Style), typeof(TabablzControl), new PropertyMetadata(default(Style))); + + /// + /// Helper method which returns all the currently loaded instances. + /// + /// + public static IEnumerable GetLoadedInstances() + { + return LoadedInstances.Union(VisibleInstances).Distinct().ToList(); + } + + /// + /// Helper method to close all tabs where the item is the tab's content (helpful with MVVM scenarios) + /// + /// + /// In MVVM scenarios where you don't want to bind the routed command to your ViewModel, + /// with this helper method and embedding the TabablzControl in a UserControl, you can keep + /// the View-specific dependencies out of the ViewModel. + /// + /// An existing Tab item content (a ViewModel in MVVM scenarios) which is backing a tab control + public static void CloseItem(object tabContentItem) + { + if (tabContentItem == null) return; //Do nothing. + + //Find all loaded TabablzControl instances with tabs backed by this item and close them + foreach (var tabWithItemContent in + GetLoadedInstances().SelectMany(tc => + tc._dragablzItemsControl.DragablzItems().Where(di => di.Content.Equals(tabContentItem)).Select(di => new { tc, di }))) + { + TabablzControl.CloseItem(tabWithItemContent.di, tabWithItemContent.tc); + } + } + + /// + /// Helper method to add an item next to an existing item. + /// + /// + /// Due to the organisable nature of the control, the order of items may not reflect the order in the source collection. This method + /// will add items to the source collection, managing their initial appearance on screen at the same time. + /// If you are using a this will be used to add the item into the source collection. + /// + /// New item to add. + /// Existing object/tab item content which defines which tab control should be used to add the object. + /// Location, relative to the object + public static void AddItem(object item, object nearItem, AddLocationHint addLocationHint) + { + if (nearItem == null) throw new ArgumentNullException("nearItem"); + + var existingLocation = GetLoadedInstances().SelectMany(tabControl => + (tabControl.ItemsSource ?? tabControl.Items).OfType() + .Select(existingObject => new { tabControl, existingObject })) + .SingleOrDefault(a => nearItem.Equals(a.existingObject)); + + if (existingLocation == null) + throw new ArgumentException("Did not find precisely one instance of adjacentTo", "nearItem"); + + existingLocation.tabControl.AddToSource(item); + if (existingLocation.tabControl._dragablzItemsControl != null) + existingLocation.tabControl._dragablzItemsControl.MoveItem(new MoveItemRequest(item, nearItem, addLocationHint)); + } + + /// + /// Finds and selects an item. + /// + /// + public static void SelectItem(object item) + { + var existingLocation = GetLoadedInstances().SelectMany(tabControl => + (tabControl.ItemsSource ?? tabControl.Items).OfType() + .Select(existingObject => new { tabControl, existingObject })) + .FirstOrDefault(a => item.Equals(a.existingObject)); + + if (existingLocation == null) return; + + existingLocation.tabControl.SelectedItem = item; + } + + /// + /// Style to apply to header items which are not their own item container (). Typically items bound via the will use this style. + /// + [Obsolete] + public Style CustomHeaderItemStyle + { + get { return (Style)GetValue(CustomHeaderItemStyleProperty); } + set { SetValue(CustomHeaderItemStyleProperty, value); } + } + + public static readonly DependencyProperty CustomHeaderItemTemplateProperty = DependencyProperty.Register( + "CustomHeaderItemTemplate", typeof(DataTemplate), typeof(TabablzControl), new PropertyMetadata(default(DataTemplate))); + + [Obsolete("Prefer HeaderItemTemplate")] + public DataTemplate CustomHeaderItemTemplate + { + get { return (DataTemplate)GetValue(CustomHeaderItemTemplateProperty); } + set { SetValue(CustomHeaderItemTemplateProperty, value); } + } + + public static readonly DependencyProperty DefaultHeaderItemStyleProperty = DependencyProperty.Register( + "DefaultHeaderItemStyle", typeof(Style), typeof(TabablzControl), new PropertyMetadata(default(Style))); + + [Obsolete] + public Style DefaultHeaderItemStyle + { + get { return (Style)GetValue(DefaultHeaderItemStyleProperty); } + set { SetValue(DefaultHeaderItemStyleProperty, value); } + } + + public static readonly DependencyProperty AdjacentHeaderItemOffsetProperty = DependencyProperty.Register( + "AdjacentHeaderItemOffset", typeof(double), typeof(TabablzControl), new PropertyMetadata(default(double), AdjacentHeaderItemOffsetPropertyChangedCallback)); + + private static void AdjacentHeaderItemOffsetPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) + { + dependencyObject.SetValue(HeaderItemsOrganiserProperty, new HorizontalOrganiser((double)dependencyPropertyChangedEventArgs.NewValue)); + } + + public double AdjacentHeaderItemOffset + { + get { return (double)GetValue(AdjacentHeaderItemOffsetProperty); } + set { SetValue(AdjacentHeaderItemOffsetProperty, value); } + } + + public static readonly DependencyProperty HeaderItemsOrganiserProperty = DependencyProperty.Register( + "HeaderItemsOrganiser", typeof(IItemsOrganiser), typeof(TabablzControl), new PropertyMetadata(new HorizontalOrganiser())); + + public IItemsOrganiser HeaderItemsOrganiser + { + get { return (IItemsOrganiser)GetValue(HeaderItemsOrganiserProperty); } + set { SetValue(HeaderItemsOrganiserProperty, value); } + } + + public static readonly DependencyProperty HeaderMemberPathProperty = DependencyProperty.Register( + "HeaderMemberPath", typeof(string), typeof(TabablzControl), new PropertyMetadata(default(string))); + + public string HeaderMemberPath + { + get { return (string)GetValue(HeaderMemberPathProperty); } + set { SetValue(HeaderMemberPathProperty, value); } + } + + public static readonly DependencyProperty HeaderItemTemplateProperty = DependencyProperty.Register( + "HeaderItemTemplate", typeof(DataTemplate), typeof(TabablzControl), new PropertyMetadata(default(DataTemplate))); + + public DataTemplate HeaderItemTemplate + { + get { return (DataTemplate)GetValue(HeaderItemTemplateProperty); } + set { SetValue(HeaderItemTemplateProperty, value); } + } + + public static readonly DependencyProperty HeaderPrefixContentProperty = DependencyProperty.Register( + "HeaderPrefixContent", typeof(object), typeof(TabablzControl), new PropertyMetadata(default(object))); + + public object HeaderPrefixContent + { + get { return (object)GetValue(HeaderPrefixContentProperty); } + set { SetValue(HeaderPrefixContentProperty, value); } + } + + public static readonly DependencyProperty HeaderPrefixContentStringFormatProperty = DependencyProperty.Register( + "HeaderPrefixContentStringFormat", typeof(string), typeof(TabablzControl), new PropertyMetadata(default(string))); + + public string HeaderPrefixContentStringFormat + { + get { return (string)GetValue(HeaderPrefixContentStringFormatProperty); } + set { SetValue(HeaderPrefixContentStringFormatProperty, value); } + } + + public static readonly DependencyProperty HeaderPrefixContentTemplateProperty = DependencyProperty.Register( + "HeaderPrefixContentTemplate", typeof(DataTemplate), typeof(TabablzControl), new PropertyMetadata(default(DataTemplate))); + + public DataTemplate HeaderPrefixContentTemplate + { + get { return (DataTemplate)GetValue(HeaderPrefixContentTemplateProperty); } + set { SetValue(HeaderPrefixContentTemplateProperty, value); } + } + + public static readonly DependencyProperty HeaderPrefixContentTemplateSelectorProperty = DependencyProperty.Register( + "HeaderPrefixContentTemplateSelector", typeof(DataTemplateSelector), typeof(TabablzControl), new PropertyMetadata(default(DataTemplateSelector))); + + public DataTemplateSelector HeaderPrefixContentTemplateSelector + { + get { return (DataTemplateSelector)GetValue(HeaderPrefixContentTemplateSelectorProperty); } + set { SetValue(HeaderPrefixContentTemplateSelectorProperty, value); } + } + + public static readonly DependencyProperty HeaderSuffixContentProperty = DependencyProperty.Register( + "HeaderSuffixContent", typeof(object), typeof(TabablzControl), new PropertyMetadata(default(object))); + + public object HeaderSuffixContent + { + get { return (object)GetValue(HeaderSuffixContentProperty); } + set { SetValue(HeaderSuffixContentProperty, value); } + } + + public static readonly DependencyProperty HeaderSuffixContentStringFormatProperty = DependencyProperty.Register( + "HeaderSuffixContentStringFormat", typeof(string), typeof(TabablzControl), new PropertyMetadata(default(string))); + + public string HeaderSuffixContentStringFormat + { + get { return (string)GetValue(HeaderSuffixContentStringFormatProperty); } + set { SetValue(HeaderSuffixContentStringFormatProperty, value); } + } + + public static readonly DependencyProperty HeaderSuffixContentTemplateProperty = DependencyProperty.Register( + "HeaderSuffixContentTemplate", typeof(DataTemplate), typeof(TabablzControl), new PropertyMetadata(default(DataTemplate))); + + public DataTemplate HeaderSuffixContentTemplate + { + get { return (DataTemplate)GetValue(HeaderSuffixContentTemplateProperty); } + set { SetValue(HeaderSuffixContentTemplateProperty, value); } + } + + public static readonly DependencyProperty HeaderSuffixContentTemplateSelectorProperty = DependencyProperty.Register( + "HeaderSuffixContentTemplateSelector", typeof(DataTemplateSelector), typeof(TabablzControl), new PropertyMetadata(default(DataTemplateSelector))); + + public DataTemplateSelector HeaderSuffixContentTemplateSelector + { + get { return (DataTemplateSelector)GetValue(HeaderSuffixContentTemplateSelectorProperty); } + set { SetValue(HeaderSuffixContentTemplateSelectorProperty, value); } + } + + public static readonly DependencyProperty ShowDefaultCloseButtonProperty = DependencyProperty.Register( + "ShowDefaultCloseButton", typeof(bool), typeof(TabablzControl), new PropertyMetadata(default(bool))); + + /// + /// Indicates whether a default close button should be displayed. If manually templating the tab header content the close command + /// can be called by executing the command (typically via a ). + /// + public bool ShowDefaultCloseButton + { + get { return (bool)GetValue(ShowDefaultCloseButtonProperty); } + set { SetValue(ShowDefaultCloseButtonProperty, value); } + } + + public static readonly DependencyProperty ShowDefaultAddButtonProperty = DependencyProperty.Register( + "ShowDefaultAddButton", typeof(bool), typeof(TabablzControl), new PropertyMetadata(default(bool))); + + /// + /// Indicates whether a default add button should be displayed. Alternately an add button + /// could be added in or , utilising + /// . + /// + public bool ShowDefaultAddButton + { + get { return (bool)GetValue(ShowDefaultAddButtonProperty); } + set { SetValue(ShowDefaultAddButtonProperty, value); } + } + + public static readonly DependencyProperty IsHeaderPanelVisibleProperty = DependencyProperty.Register( + "IsHeaderPanelVisible", typeof(bool), typeof(TabablzControl), new PropertyMetadata(true)); + + /// + /// Indicates wither the heaeder panel is visible. Default is true. + /// + public bool IsHeaderPanelVisible + { + get { return (bool)GetValue(IsHeaderPanelVisibleProperty); } + set { SetValue(IsHeaderPanelVisibleProperty, value); } + } + + public static readonly DependencyProperty AddLocationHintProperty = DependencyProperty.Register( + "AddLocationHint", typeof(AddLocationHint), typeof(TabablzControl), new PropertyMetadata(AddLocationHint.Last)); + + /// + /// Gets or sets the location to add new tab items in the header. + /// + /// + /// The logical order of the header items might not add match the content of the source items, + /// so this property allows control of where new items should appear. + /// + public AddLocationHint AddLocationHint + { + get { return (AddLocationHint)GetValue(AddLocationHintProperty); } + set { SetValue(AddLocationHintProperty, value); } + } + + public static readonly DependencyProperty FixedHeaderCountProperty = DependencyProperty.Register( + "FixedHeaderCount", typeof(int), typeof(TabablzControl), new PropertyMetadata(default(int))); + + /// + /// Allows a the first adjacent tabs to be fixed (no dragging, and default close button will not show). + /// + public int FixedHeaderCount + { + get { return (int)GetValue(FixedHeaderCountProperty); } + set { SetValue(FixedHeaderCountProperty, value); } + } + + + public static readonly DependencyProperty DisableBranchConsolidationProperty = DependencyProperty.Register( + "DisableBranchConsolidation", typeof(bool), typeof(TabablzControl), new PropertyMetadata(default(bool))); + + /// + /// Disable the consolidation of branches when a tab is dragged out of a branch. Set it to true if you have + /// a main TabablzControl that is used to create new tab items and you don't want to remove this TabaBlzControl + /// when the last tab is dragged out. In dynamically created TabablzControls this property should then be set to + /// false (default). + /// If this is set to true the and + /// is ignored. + /// + public bool DisableBranchConsolidation + { + get { return (bool)GetValue(DisableBranchConsolidationProperty); } + set { SetValue(DisableBranchConsolidationProperty, value); } + } + + public static readonly DependencyProperty InterTabControllerProperty = DependencyProperty.Register( + "InterTabController", typeof(InterTabController), typeof(TabablzControl), new PropertyMetadata(null, InterTabControllerPropertyChangedCallback)); + + private static void InterTabControllerPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) + { + var instance = (TabablzControl)dependencyObject; + if (dependencyPropertyChangedEventArgs.OldValue != null) + instance.RemoveLogicalChild(dependencyPropertyChangedEventArgs.OldValue); + if (dependencyPropertyChangedEventArgs.NewValue != null) + instance.AddLogicalChild(dependencyPropertyChangedEventArgs.NewValue); + } + + /// + /// An must be provided to enable tab tearing. Behaviour customisations can be applied + /// vie the controller. + /// + public InterTabController InterTabController + { + get { return (InterTabController)GetValue(InterTabControllerProperty); } + set { SetValue(InterTabControllerProperty, value); } + } + + /// + /// Allows a factory to be provided for generating new items. Typically used in conjunction with . + /// + public static readonly DependencyProperty NewItemFactoryProperty = DependencyProperty.Register( + "NewItemFactory", typeof(Func), typeof(TabablzControl), new PropertyMetadata(default(Func))); + + /// + /// Allows a factory to be provided for generating new items. Typically used in conjunction with . + /// + public Func NewItemFactory + { + get { return (Func)GetValue(NewItemFactoryProperty); } + set { SetValue(NewItemFactoryProperty, value); } + } + + private static readonly DependencyPropertyKey IsEmptyPropertyKey = + DependencyProperty.RegisterReadOnly( + "IsEmpty", typeof(bool), typeof(TabablzControl), + new PropertyMetadata(true, OnIsEmptyChanged)); + + /// + /// Indicates if there are no current tab items. + /// + public static readonly DependencyProperty IsEmptyProperty = + IsEmptyPropertyKey.DependencyProperty; + + /// + /// Indicates if there are no current tab items. + /// + public bool IsEmpty + { + get { return (bool)GetValue(IsEmptyProperty); } + private set { SetValue(IsEmptyPropertyKey, value); } + } + + /// + /// Raised when changes. + /// + public static readonly RoutedEvent IsEmptyChangedEvent = + EventManager.RegisterRoutedEvent( + "IsEmptyChanged", + RoutingStrategy.Bubble, + typeof(RoutedPropertyChangedEventHandler), + typeof(TabablzControl)); + + /// + /// Event handler to list to . + /// + public event RoutedPropertyChangedEventHandler IsEmptyChanged + { + add { AddHandler(IsEmptyChangedEvent, value); } + remove { RemoveHandler(IsEmptyChangedEvent, value); } + } + + private static void OnIsEmptyChanged( + DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var instance = d as TabablzControl; + var args = new RoutedPropertyChangedEventArgs( + (bool)e.OldValue, + (bool)e.NewValue) + { RoutedEvent = IsEmptyChangedEvent }; + instance?.RaiseEvent(args); + } + + /// + /// Optionally allows a close item hook to be bound in. If this propety is provided, the func must return true for the close to continue. + /// + public static readonly DependencyProperty ClosingItemCallbackProperty = DependencyProperty.Register( + "ClosingItemCallback", typeof(ItemActionCallback), typeof(TabablzControl), new PropertyMetadata(default(ItemActionCallback))); + + /// + /// Optionally allows a close item hook to be bound in. If this propety is provided, the func must return true for the close to continue. + /// + public ItemActionCallback ClosingItemCallback + { + get { return (ItemActionCallback)GetValue(ClosingItemCallbackProperty); } + set { SetValue(ClosingItemCallbackProperty, value); } + } + + /// + /// Set to true to have tabs automatically be moved to another tab is a window is closed, so that they arent lost. + /// Can be useful for fixed/persistant tabs that may have been dragged into another Window. You can further control + /// this behaviour on a per tab item basis by providing . + /// + public static readonly DependencyProperty ConsolidateOrphanedItemsProperty = DependencyProperty.Register( + "ConsolidateOrphanedItems", typeof(bool), typeof(TabablzControl), new PropertyMetadata(default(bool))); + + /// + /// Set to true to have tabs automatically be moved to another tab is a window is closed, so that they arent lost. + /// Can be useful for fixed/persistant tabs that may have been dragged into another Window. You can further control + /// this behaviour on a per tab item basis by providing . + /// + public bool ConsolidateOrphanedItems + { + get { return (bool)GetValue(ConsolidateOrphanedItemsProperty); } + set { SetValue(ConsolidateOrphanedItemsProperty, value); } + } + + /// + /// Assuming is set to true, consolidation of individual + /// tab items can be cancelled by providing this call back and cancelling the + /// instance. + /// + public static readonly DependencyProperty ConsolidatingOrphanedItemCallbackProperty = DependencyProperty.Register( + "ConsolidatingOrphanedItemCallback", typeof(ItemActionCallback), typeof(TabablzControl), new PropertyMetadata(default(ItemActionCallback))); + + /// + /// Assuming is set to true, consolidation of individual + /// tab items can be cancelled by providing this call back and cancelling the + /// instance. + /// + public ItemActionCallback ConsolidatingOrphanedItemCallback + { + get { return (ItemActionCallback)GetValue(ConsolidatingOrphanedItemCallbackProperty); } + set { SetValue(ConsolidatingOrphanedItemCallbackProperty, value); } + } + + /// + /// Defines which part of the tab bar accepts a tab which is dragged (as a window) over it. The default + /// only accepts it over the existing tabs. + /// requires the optional template part . + /// + public static readonly DependencyProperty MergeTargetAreaProperty = DependencyProperty.Register( + "MergeTargetArea", typeof(MergeTargetArea), typeof(TabablzControl), + new PropertyMetadata(MergeTargetArea.HeaderItems)); + + /// + /// Defines which part of the tab bar accepts a tab which is dragged (as a window) over it. + /// + public MergeTargetArea MergeTargetArea + { + get { return (MergeTargetArea)GetValue(MergeTargetAreaProperty); } + set { SetValue(MergeTargetAreaProperty, value); } + } + + /// + /// Indicates whether a hint is shown in the tab bar while a tab can be dropped into this control. + /// + public static readonly DependencyProperty ShowMergeHintProperty = DependencyProperty.Register( + "ShowMergeHint", typeof(bool), typeof(TabablzControl), new PropertyMetadata(default(bool))); + + /// + /// Indicates whether a hint is shown in the tab bar while a tab can be dropped into this control. + /// + public bool ShowMergeHint + { + get { return (bool)GetValue(ShowMergeHintProperty); } + set { SetValue(ShowMergeHintProperty, value); } + } + + /// + /// Distance (device independent pixels) around the merge target within which is set. + /// + public static readonly DependencyProperty MergeHintProximityProperty = DependencyProperty.Register( + "MergeHintProximity", typeof(double), typeof(TabablzControl), new PropertyMetadata(48d)); + + /// + /// Distance (device independent pixels) around the merge target within which is set. + /// + public double MergeHintProximity + { + get { return (double)GetValue(MergeHintProximityProperty); } + set { SetValue(MergeHintProximityProperty, value); } + } + + /// + /// Optional template of the merge hint. A default visual is used if not set. The template is + /// instantiated inside the tab control, so bind to with a + /// RelativeSource AncestorType=TabablzControl binding. + /// + public static readonly DependencyProperty MergeHintTemplateProperty = DependencyProperty.Register( + "MergeHintTemplate", typeof(DataTemplate), typeof(TabablzControl), new PropertyMetadata(default(DataTemplate))); + + /// + /// Optional template of the merge hint. A default visual is used if not set. + /// + public DataTemplate MergeHintTemplate + { + get { return (DataTemplate)GetValue(MergeHintTemplateProperty); } + set { SetValue(MergeHintTemplateProperty, value); } + } + + private static readonly DependencyPropertyKey IsMergeTargetParticipatingPropertyKey = + DependencyProperty.RegisterReadOnly( + "IsMergeTargetParticipating", typeof(bool), typeof(TabablzControl), new PropertyMetadata(default(bool))); + + /// + /// Readonly dependency property which indicates that another tab control is dragging its window and + /// this control is a possible target to merge it into. + /// + public static readonly DependencyProperty IsMergeTargetParticipatingProperty = + IsMergeTargetParticipatingPropertyKey.DependencyProperty; + + /// + /// Readonly dependency property which indicates that another tab control is dragging its window and + /// this control is a possible target to merge it into. + /// + public bool IsMergeTargetParticipating + { + get { return (bool)GetValue(IsMergeTargetParticipatingProperty); } + private set { SetValue(IsMergeTargetParticipatingPropertyKey, value); } + } + + private static readonly DependencyPropertyKey IsMergeTargetOfferedPropertyKey = + DependencyProperty.RegisterReadOnly( + "IsMergeTargetOffered", typeof(bool), typeof(TabablzControl), new PropertyMetadata(default(bool))); + + /// + /// Readonly dependency property which indicates that the cursor of a dragged window is over or near + /// (see ) this control, so a drop would merge the tab into it. + /// + public static readonly DependencyProperty IsMergeTargetOfferedProperty = + IsMergeTargetOfferedPropertyKey.DependencyProperty; + + /// + /// Readonly dependency property which indicates that the cursor of a dragged window is over or near + /// (see ) this control, so a drop would merge the tab into it. + /// + public bool IsMergeTargetOffered + { + get { return (bool)GetValue(IsMergeTargetOfferedProperty); } + private set { SetValue(IsMergeTargetOfferedPropertyKey, value); } + } + + private static readonly DependencyPropertyKey IsDraggingWindowPropertyKey = + DependencyProperty.RegisterReadOnly( + "IsDraggingWindow", typeof(bool), typeof(TabablzControl), + new PropertyMetadata(default(bool), OnIsDraggingWindowChanged)); + + /// + /// Readonly dependency property which indicates whether the owning + /// is currently dragged + /// + public static readonly DependencyProperty IsDraggingWindowProperty = + IsDraggingWindowPropertyKey.DependencyProperty; + + /// + /// Readonly dependency property which indicates whether the owning + /// is currently dragged + /// + public bool IsDraggingWindow + { + get { return (bool)GetValue(IsDraggingWindowProperty); } + private set { SetValue(IsDraggingWindowPropertyKey, value); } + } + + /// + /// Event indicating has changed. + /// + public static readonly RoutedEvent IsDraggingWindowChangedEvent = + EventManager.RegisterRoutedEvent( + "IsDraggingWindowChanged", + RoutingStrategy.Bubble, + typeof(RoutedPropertyChangedEventHandler), + typeof(TabablzControl)); + + /// + /// Event indicating has changed. + /// + public event RoutedPropertyChangedEventHandler IsDraggingWindowChanged + { + add { AddHandler(IsDraggingWindowChangedEvent, value); } + remove { RemoveHandler(IsDraggingWindowChangedEvent, value); } + } + + private static void OnIsDraggingWindowChanged( + DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var instance = (TabablzControl)d; + var args = new RoutedPropertyChangedEventArgs( + (bool)e.OldValue, + (bool)e.NewValue) + { + RoutedEvent = IsDraggingWindowChangedEvent + }; + instance.RaiseEvent(args); + + if (!(bool)e.NewValue) + instance.ReleaseMergeTargetStates(); + } + + /// + /// Temporarily set by the framework if a users drag opration causes a Window to close (e.g if a tab is dragging into another tab). + /// + public static readonly DependencyProperty IsClosingAsPartOfDragOperationProperty = DependencyProperty.RegisterAttached( + "IsClosingAsPartOfDragOperation", typeof(bool), typeof(TabablzControl), new FrameworkPropertyMetadata(default(bool), FrameworkPropertyMetadataOptions.NotDataBindable)); + + internal static void SetIsClosingAsPartOfDragOperation(Window element, bool value) + { + element.SetValue(IsClosingAsPartOfDragOperationProperty, value); + } + + /// + /// Helper method which can tell you if a is being automatically closed due + /// to a user instigated drag operation (typically when a single tab is dropped into another window. + /// + /// + /// + public static bool GetIsClosingAsPartOfDragOperation(Window element) + { + return (bool)element.GetValue(IsClosingAsPartOfDragOperationProperty); + } + + /// + /// Provide a hint for how the header should size itself if there are no tabs left (and a Window is still open). + /// + public static readonly DependencyProperty EmptyHeaderSizingHintProperty = DependencyProperty.Register( + "EmptyHeaderSizingHint", typeof(EmptyHeaderSizingHint), typeof(TabablzControl), new PropertyMetadata(default(EmptyHeaderSizingHint))); + + /// + /// Provide a hint for how the header should size itself if there are no tabs left (and a Window is still open). + /// + public EmptyHeaderSizingHint EmptyHeaderSizingHint + { + get { return (EmptyHeaderSizingHint)GetValue(EmptyHeaderSizingHintProperty); } + set { SetValue(EmptyHeaderSizingHintProperty, value); } + } + + public static readonly DependencyProperty IsWrappingTabItemProperty = DependencyProperty.RegisterAttached( + "IsWrappingTabItem", typeof(bool), typeof(TabablzControl), new PropertyMetadata(default(bool))); + + internal static void SetIsWrappingTabItem(DependencyObject element, bool value) + { + element.SetValue(IsWrappingTabItemProperty, value); + } + + public static bool GetIsWrappingTabItem(DependencyObject element) + { + return (bool)element.GetValue(IsWrappingTabItemProperty); + } + + /// + /// Adds an item to the source collection. If the InterTabController.InterTabClient is set that instance will be deferred to. + /// Otherwise an attempt will be made to add to the property, and lastly . + /// + /// + public void AddToSource(object item) + { + if (item == null) throw new ArgumentNullException("item"); + + var manualInterTabClient = InterTabController == null ? null : InterTabController.InterTabClient as IManualInterTabClient; + if (manualInterTabClient != null) + { + manualInterTabClient.Add(item); + } + else + { + CollectionTeaser collectionTeaser; + if (CollectionTeaser.TryCreate(ItemsSource, out collectionTeaser)) + collectionTeaser.Add(item); + else + Items.Add(item); + } + } + + /// + /// Removes an item from the source collection. If the InterTabController.InterTabClient is set that instance will be deferred to. + /// Otherwise an attempt will be made to remove from the property, and lastly . + /// + /// + public void RemoveFromSource(object item) + { + if (item == null) throw new ArgumentNullException("item"); + + var manualInterTabClient = InterTabController == null ? null : InterTabController.InterTabClient as IManualInterTabClient; + if (manualInterTabClient != null) + { + manualInterTabClient.Remove(item); + } + else + { + CollectionTeaser collectionTeaser; + if (CollectionTeaser.TryCreate(ItemsSource, out collectionTeaser)) + collectionTeaser.Remove(item); + else + Items.Remove(item); + } + } + + /// + /// Gets the header items, ordered according to their current visual position in the tab header. + /// + /// + public IEnumerable GetOrderedHeaders() + { + return _dragablzItemsControl.ItemsOrganiser.Sort(_dragablzItemsControl.DragablzItems()); + } + + /// + /// Called when is called. + /// + public override void OnApplyTemplate() + { + _templateSubscription?.Dispose(); + _templateSubscription = Disposable.Empty; + + _dragablzItemsControl = GetTemplateChild(HeaderItemsControlPartName) as DragablzItemsControl; + if (_dragablzItemsControl != null) + { + _dragablzItemsControl.ItemContainerGenerator.StatusChanged += ItemContainerGeneratorOnStatusChanged; + _templateSubscription = + Disposable.Create( + () => + _dragablzItemsControl.ItemContainerGenerator.StatusChanged -= + ItemContainerGeneratorOnStatusChanged); + + _dragablzItemsControl.ContainerCustomisations = new ContainerCustomisations(null, PrepareChildContainerForItemOverride); + } + + if (SelectedItem == null) + SetCurrentValue(SelectedItemProperty, Items.OfType().FirstOrDefault()); + + _headerPanel = GetTemplateChild(HeaderPanelPartName) as FrameworkElement; + + _itemsHolder = GetTemplateChild(ItemsHolderPartName) as Panel; + UpdateSelectedItem(); + MarkWrappedTabItems(); + MarkInitialSelection(); + + base.OnApplyTemplate(); + } + + /// + /// update the visible child in the ItemsHolder + /// + /// + protected override void OnSelectionChanged(SelectionChangedEventArgs e) + { + if (e.RemovedItems.Count > 0 && e.AddedItems.Count > 0) + _previousSelection = new WeakReference(e.RemovedItems[0]); + + base.OnSelectionChanged(e); + UpdateSelectedItem(); + + if (_dragablzItemsControl == null) return; + + Func> notTabItems = + l => + l.Cast() + .Where(o => !(o is TabItem)) + .Select(o => _dragablzItemsControl.ItemContainerGenerator.ContainerFromItem(o)) + .OfType(); + foreach (var addedItem in notTabItems(e.AddedItems)) + { + addedItem.IsSelected = true; + addedItem.BringIntoView(); + } + foreach (var removedItem in notTabItems(e.RemovedItems)) + { + removedItem.IsSelected = false; + } + + foreach (var tabItem in e.AddedItems.OfType().Select(t => _dragablzItemsControl.ItemContainerGenerator.ContainerFromItem(t)).OfType()) + { + tabItem.IsSelected = true; + tabItem.BringIntoView(); + } + foreach (var tabItem in e.RemovedItems.OfType().Select(t => _dragablzItemsControl.ItemContainerGenerator.ContainerFromItem(t)).OfType()) + { + tabItem.IsSelected = false; + } + } + + /// + /// when the items change we remove any generated panel children and add any new ones as necessary + /// + /// + protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e) + { + base.OnItemsChanged(e); + + if (_itemsHolder == null) + { + return; + } + + switch (e.Action) + { + case NotifyCollectionChangedAction.Reset: + _itemsHolder.Children.Clear(); + + if (Items.Count > 0) + { + SelectedItem = base.Items[0]; + UpdateSelectedItem(); + } + + break; + + case NotifyCollectionChangedAction.Add: + UpdateSelectedItem(); + if (e.NewItems.Count == 1 && Items.Count > 1 && _dragablzItemsControl != null && _interTabTransfer == null) + _dragablzItemsControl.MoveItem(new MoveItemRequest(e.NewItems[0], SelectedItem, AddLocationHint)); + + break; + + case NotifyCollectionChangedAction.Remove: + foreach (var item in e.OldItems) + { + var cp = FindChildContentPresenter(item); + if (cp != null) + _itemsHolder.Children.Remove(cp); + } + + if (SelectedItem == null) + RestorePreviousSelection(); + UpdateSelectedItem(); + break; + + case NotifyCollectionChangedAction.Replace: + throw new NotImplementedException("Replace not implemented yet"); + } + + IsEmpty = Items.Count == 0; + } + + /// + /// Provides class handling for the routed event that occurs when the user presses a key. + /// + /// Provides data for . + protected override void OnKeyDown(KeyEventArgs e) + { + var sortedDragablzItems = _dragablzItemsControl.ItemsOrganiser.Sort(_dragablzItemsControl.DragablzItems()).ToList(); + DragablzItem selectDragablzItem = null; + switch (e.Key) + { + case Key.Tab: + if (SelectedItem == null) + { + selectDragablzItem = sortedDragablzItems.FirstOrDefault(); + break; + } + + if ((e.KeyboardDevice.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) + { + var selectedDragablzItem = (DragablzItem)_dragablzItemsControl.ItemContainerGenerator.ContainerFromItem(SelectedItem); + var selectedDragablzItemIndex = sortedDragablzItems.IndexOf(selectedDragablzItem); + var direction = ((e.KeyboardDevice.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift) + ? -1 : 1; + var newIndex = selectedDragablzItemIndex + direction; + if (newIndex < 0) newIndex = sortedDragablzItems.Count - 1; + else if (newIndex == sortedDragablzItems.Count) newIndex = 0; + + selectDragablzItem = sortedDragablzItems[newIndex]; + } + break; + case Key.Home: + selectDragablzItem = sortedDragablzItems.FirstOrDefault(); + break; + case Key.End: + selectDragablzItem = sortedDragablzItems.LastOrDefault(); + break; + } + + if (selectDragablzItem != null) + { + var item = _dragablzItemsControl.ItemContainerGenerator.ItemFromContainer(selectDragablzItem); + SetCurrentValue(SelectedItemProperty, item); + e.Handled = true; + } + + if (!e.Handled) + base.OnKeyDown(e); + } + + /// + /// Provides an appropriate automation peer implementation for this control + /// as part of the WPF automation infrastructure. + /// + /// The type-specific System.Windows.Automation.Peers.AutomationPeer implementation. + protected override AutomationPeer OnCreateAutomationPeer() + { + return new FrameworkElementAutomationPeer(this); + } + + internal static TabablzControl GetOwnerOfHeaderItems(DragablzItemsControl itemsControl) + { + return LoadedInstances.FirstOrDefault(t => Equals(t._dragablzItemsControl, itemsControl)); + } + + private static void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) + { + var tabablzControl = (TabablzControl)sender; + if (tabablzControl.IsVisible) + VisibleInstances.Add(tabablzControl); + else if (VisibleInstances.Contains(tabablzControl)) + VisibleInstances.Remove(tabablzControl); + } + + private void OnLoaded(object sender, RoutedEventArgs routedEventArgs) + { + LoadedInstances.Add(this); + var window = Window.GetWindow(this); + if (window == null) return; + window.Closing += WindowOnClosing; + _windowSubscription.Disposable = Disposable.Create(() => window.Closing -= WindowOnClosing); + } + + private void WindowOnClosing(object sender, CancelEventArgs cancelEventArgs) + { + _windowSubscription.Disposable = Disposable.Empty; + if (!ConsolidateOrphanedItems || InterTabController == null) return; + + var window = (Window)sender; + + var orphanedItems = _dragablzItemsControl.DragablzItems(); + if (ConsolidatingOrphanedItemCallback != null) + { + orphanedItems = + orphanedItems.Where( + di => + { + var args = new ItemActionCallbackArgs(window, this, di); + ConsolidatingOrphanedItemCallback(args); + return !args.IsCancelled; + }).ToList(); + } + + var target = + LoadedInstances.Except(this) + .FirstOrDefault( + other => + other.InterTabController != null && + other.InterTabController.Partition == InterTabController.Partition); + if (target == null) return; + + foreach (var item in orphanedItems.Select(orphanedItem => _dragablzItemsControl.ItemContainerGenerator.ItemFromContainer(orphanedItem))) + { + RemoveFromSource(item); + target.AddToSource(item); + } + } + + private void OnUnloaded(object sender, RoutedEventArgs routedEventArgs) + { + _windowSubscription.Disposable = Disposable.Empty; + LoadedInstances.Remove(this); + ReleaseMergeTargetStates(); + } + + private void MarkWrappedTabItems() + { + if (_dragablzItemsControl == null) return; + + foreach (var pair in _dragablzItemsControl.Items.OfType().Select(tabItem => + new + { + tabItem, + dragablzItem = _dragablzItemsControl.ItemContainerGenerator.ContainerFromItem(tabItem) as DragablzItem + }).Where(a => a.dragablzItem != null)) + { + var toolTipBinding = new Binding("ToolTip") { Source = pair.tabItem }; + BindingOperations.SetBinding(pair.dragablzItem, ToolTipProperty, toolTipBinding); + SetIsWrappingTabItem(pair.dragablzItem, true); + } + } + + private void MarkInitialSelection() + { + if (_dragablzItemsControl == null || + _dragablzItemsControl.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated) return; + + if (_dragablzItemsControl == null || SelectedItem == null) return; + + var tabItem = SelectedItem as TabItem; + tabItem?.SetCurrentValue(IsSelectedProperty, true); + + var containerFromItem = + _dragablzItemsControl.ItemContainerGenerator.ContainerFromItem(SelectedItem) as DragablzItem; + + containerFromItem?.SetCurrentValue(DragablzItem.IsSelectedProperty, true); + } + + private void ItemDragStarted(object sender, DragablzDragStartedEventArgs e) + { + if (!IsMyItem(e.DragablzItem)) return; + + //the thumb may steal the user selection, so we will try and apply it manually + if (_dragablzItemsControl == null) return; + + e.DragablzItem.IsDropTargetFound = false; + + var sourceOfDragItemsControl = ItemsControlFromItemContainer(e.DragablzItem) as DragablzItemsControl; + if (sourceOfDragItemsControl == null || !Equals(sourceOfDragItemsControl, _dragablzItemsControl)) return; + + var itemsControlOffset = Mouse.GetPosition(_dragablzItemsControl); + _tabHeaderDragStartInformation = new TabHeaderDragStartInformation(e.DragablzItem, itemsControlOffset.X, + itemsControlOffset.Y, e.DragStartedEventArgs.HorizontalOffset, e.DragStartedEventArgs.VerticalOffset); + + foreach (var otherItem in _dragablzItemsControl.Containers().Except(e.DragablzItem)) + otherItem.IsSelected = false; + e.DragablzItem.IsSelected = true; + e.DragablzItem.PartitionAtDragStart = InterTabController?.Partition?.ToString(); + var item = _dragablzItemsControl.ItemContainerGenerator.ItemFromContainer(e.DragablzItem); + var tabItem = item as TabItem; + if (tabItem != null) + tabItem.IsSelected = true; + SelectedItem = item; + + if (ShouldDragWindow(sourceOfDragItemsControl)) + { + IsDraggingWindow = true; + //the partition is not known yet for a freshly created host, so wire up on the first delta + _isMergeHintWireUpPending = true; + } + } + + private bool ShouldDragWindow(DragablzItemsControl sourceOfDragItemsControl) + { + return (Items.Count == 1 + && (InterTabController == null || InterTabController.MoveWindowWithSolitaryTabs) + && !Layout.IsContainedWithinBranch(sourceOfDragItemsControl)); + } + + private void PreviewItemDragDelta(object sender, DragablzDragDeltaEventArgs e) + { + if (_dragablzItemsControl == null) return; + + var sourceOfDragItemsControl = ItemsControlFromItemContainer(e.DragablzItem) as DragablzItemsControl; + if (sourceOfDragItemsControl == null || !Equals(sourceOfDragItemsControl, _dragablzItemsControl)) return; + + if (!ShouldDragWindow(sourceOfDragItemsControl)) return; + + if (_isMergeHintWireUpPending) + { + _isMergeHintWireUpPending = false; + WireUpMergeTargets(); + } + UpdateOfferedMergeTarget(); + + if (MonitorReentry(e)) return; + + var myWindow = Window.GetWindow(this); + if (myWindow == null) return; + + if (_interTabTransfer != null) + { + var cursorPos = Native.GetCursorPos().ToWpf(); + if (_interTabTransfer.BreachOrientation == Orientation.Vertical) + { + var vector = cursorPos - _interTabTransfer.DragStartWindowOffset; + myWindow.Left = vector.X; + myWindow.Top = vector.Y; + } + else + { + var offset = e.DragablzItem.TranslatePoint(_interTabTransfer.OriginatorContainer.MouseAtDragStart, myWindow); + var borderVector = myWindow.PointToScreen(new Point()).ToWpf() - new Point(myWindow.Left, myWindow.Top); + offset.Offset(borderVector.X, borderVector.Y); + myWindow.Left = cursorPos.X - offset.X; + myWindow.Top = cursorPos.Y - offset.Y; + } + } + else + { + myWindow.Left += e.DragDeltaEventArgs.HorizontalChange; + myWindow.Top += e.DragDeltaEventArgs.VerticalChange; + } + + e.Handled = true; + } + + /// + /// Other tab controls of the same partition a dragged tab could be merged into. + /// + private IEnumerable GetMergeTargetCandidates() + { + return LoadedInstances + .Where( + tc => + tc != this && tc.InterTabController != null && InterTabController != null + && Equals(tc.InterTabController.Partition, InterTabController.Partition) + && tc._dragablzItemsControl != null) + .ToList(); + } + + /// + /// Screen bounds (device pixels) in which a dragged tab is merged into this control. + /// + internal Rect? GetMergeTargetScreenBounds() + { + if (_dragablzItemsControl == null) return null; + + var itemsBounds = GetScreenBounds(_dragablzItemsControl); + Rect? panelBounds = null; + if (MergeTargetArea == MergeTargetArea.HeaderPanel && _headerPanel != null && _headerPanel.IsVisible) + panelBounds = GetScreenBounds(_headerPanel); + + var orientation = TabStripPlacement == Dock.Top || TabStripPlacement == Dock.Bottom + ? Orientation.Horizontal + : Orientation.Vertical; + + var lastFixedItem = _dragablzItemsControl.DragablzItems() + .OrderBy(di => di.LogicalIndex) + .Take(_dragablzItemsControl.FixedItemCount) + .LastOrDefault(); + var fixedItemsEnd = 0d; + if (lastFixedItem != null) + { + var scale = orientation == Orientation.Horizontal + ? VisualTreeHelper.GetDpi(_dragablzItemsControl).DpiScaleX + : VisualTreeHelper.GetDpi(_dragablzItemsControl).DpiScaleY; + fixedItemsEnd = orientation == Orientation.Horizontal + ? (lastFixedItem.X + lastFixedItem.ActualWidth) * scale + : (lastFixedItem.Y + lastFixedItem.ActualHeight) * scale; + } + + return MergeTargetCalculator.GetBounds(itemsBounds, panelBounds, MergeTargetArea, orientation, fixedItemsEnd); + } + + private static Rect GetScreenBounds(FrameworkElement element) + { + return new Rect( + element.PointToScreen(new Point()), + element.PointToScreen(new Point(element.ActualWidth, element.ActualHeight))); + } + + private void WireUpMergeTargets() + { + ClearMergeTargetStates(); + if (_dragablzItemsControl == null || InterTabController == null) return; + + var myWindow = Window.GetWindow(this); + _mergeHintOwner = this; + foreach (var target in GetMergeTargetCandidates() + .Where(tc => tc.IsVisible && !Equals(Window.GetWindow(tc), myWindow))) + { + target.IsMergeTargetParticipating = true; + MergeTargetsInDrag.Add(target); + } + } + + private void UpdateOfferedMergeTarget() + { + if (!ReferenceEquals(_mergeHintOwner, this) || MergeTargetsInDrag.Count == 0) return; + + var screenMousePosition = _dragablzItemsControl.PointToScreen(Mouse.GetPosition(_dragablzItemsControl)); + var topMost = Native.SortWindowsTopToBottom(Application.Current.Windows.OfType()).ToList(); + + //same rule as MonitorReentry: the first (top most) window under the cursor wins + TabablzControl offered = null; + var offeredIndex = int.MaxValue; + foreach (var target in MergeTargetsInDrag) + { + var bounds = target.GetMergeTargetScreenBounds(); + if (!bounds.HasValue) continue; + + var proximity = target.MergeHintProximity * VisualTreeHelper.GetDpi(target).DpiScaleX; + if (!MergeTargetCalculator.Inflate(bounds.Value, proximity).Contains(screenMousePosition)) continue; + + var index = topMost.IndexOf(Window.GetWindow(target)); + if (index < 0 || index >= offeredIndex) continue; + offered = target; + offeredIndex = index; + } + + foreach (var target in MergeTargetsInDrag) + target.IsMergeTargetOffered = ReferenceEquals(target, offered); + } + + private void ReleaseMergeTargetStates() + { + _isMergeHintWireUpPending = false; + if (ReferenceEquals(_mergeHintOwner, this)) + ClearMergeTargetStates(); + } + + /// + /// Resets and on all controls. + /// + internal static void ClearMergeTargetStates() + { + foreach (var target in MergeTargetsInDrag) + { + target.IsMergeTargetOffered = false; + target.IsMergeTargetParticipating = false; + } + MergeTargetsInDrag.Clear(); + _mergeHintOwner = null; + } + + private bool MonitorReentry(DragablzDragDeltaEventArgs e) + { + var screenMousePosition = _dragablzItemsControl.PointToScreen(Mouse.GetPosition(_dragablzItemsControl)); + + var sourceTabablzControl = (TabablzControl)e.Source; + if (sourceTabablzControl.Items.Count > 1 && e.DragablzItem.LogicalIndex < sourceTabablzControl.FixedHeaderCount) + { + return false; + } + + var otherTabablzControls = GetMergeTargetCandidates() + .Select(tc => new { tc, bounds = tc.GetMergeTargetScreenBounds() }) + .Where(a => a.bounds.HasValue); + + var target = Native.SortWindowsTopToBottom(Application.Current.Windows.OfType()) + .Join(otherTabablzControls, w => w, a => Window.GetWindow(a.tc), (w, a) => a) + .FirstOrDefault(a => a.bounds.Value.Contains(screenMousePosition)); + + if (target == null) return false; + + var mousePositionOnItem = Mouse.GetPosition(e.DragablzItem); + + var floatingItemSnapShots = this.VisualTreeDepthFirstTraversal() + .OfType() + .SelectMany(l => l.FloatingDragablzItems().Select(FloatingItemSnapShot.Take)) + .ToList(); + + e.DragablzItem.IsDropTargetFound = true; + var item = RemoveItem(e.DragablzItem); + + var interTabTransfer = new InterTabTransfer(item, e.DragablzItem, mousePositionOnItem, floatingItemSnapShots); + e.DragablzItem.IsDragging = false; + + ClearMergeTargetStates(); + target.tc.ReceiveDrag(interTabTransfer); + e.Cancel = true; + + return true; + } + + internal object RemoveItem(DragablzItem dragablzItem) + { + var item = _dragablzItemsControl.ItemContainerGenerator.ItemFromContainer(dragablzItem); + + //stop the header shrinking if the tab stays open when empty + var minSize = EmptyHeaderSizingHint == EmptyHeaderSizingHint.PreviousTab + ? new Size(_dragablzItemsControl.ActualWidth, _dragablzItemsControl.ActualHeight) + : new Size(); + + _dragablzItemsControl.MinHeight = 0; + _dragablzItemsControl.MinWidth = 0; + + var contentPresenter = FindChildContentPresenter(item); + RemoveFromSource(item); + _itemsHolder.Children.Remove(contentPresenter); + + // Return if it is not the last item + if (Items.Count != 0) + return item; + + // Set min size + _dragablzItemsControl.MinHeight = minSize.Height; + _dragablzItemsControl.MinWidth = minSize.Width; + + // Disable branch consolidation (close branch or window is ignored) + if (DisableBranchConsolidation) + return item; + + // Find window + var window = Window.GetWindow(this); + + if (window == null || InterTabController == null) + return item; + + // Get tab emptied response + var tabEmptiedResponse = InterTabController.InterTabClient.TabEmptiedHandler(this, window); + + // This is e.g. to DoNothing + if (tabEmptiedResponse is not (TabEmptiedResponse.CloseLayoutBranch or TabEmptiedResponse.CloseWindowOrLayoutBranch)) + return item; + + // Consolidate branch + if (Layout.ConsolidateBranch(this)) + return item; + + // Close window + if (tabEmptiedResponse is TabEmptiedResponse.CloseWindowOrLayoutBranch) + { + try + { + SetIsClosingAsPartOfDragOperation(window, true); + window.Close(); + } + finally + { + SetIsClosingAsPartOfDragOperation(window, false); + } + } + + return item; + } + + private void ItemDragCompleted(object sender, DragablzDragCompletedEventArgs e) + { + if (!IsMyItem(e.DragablzItem)) return; + + _interTabTransfer = null; + _dragablzItemsControl.LockedMeasure = null; + IsDraggingWindow = false; + ReleaseMergeTargetStates(); + } + + private void ItemDragDelta(object sender, DragablzDragDeltaEventArgs e) + { + if (!IsMyItem(e.DragablzItem)) return; + if (FixedHeaderCount > 0 && + _dragablzItemsControl.ItemsOrganiser.Sort(_dragablzItemsControl.DragablzItems()) + .Take(FixedHeaderCount) + .Contains(e.DragablzItem)) + return; + + if (_tabHeaderDragStartInformation == null || + !Equals(_tabHeaderDragStartInformation.DragItem, e.DragablzItem) || InterTabController == null) return; + + if (InterTabController.InterTabClient == null) + throw new InvalidOperationException("An InterTabClient must be provided on an InterTabController."); + + MonitorBreach(e); + } + + private bool IsMyItem(DragablzItem item) + { + return _dragablzItemsControl != null && _dragablzItemsControl.DragablzItems().Contains(item); + } + + private void MonitorBreach(DragablzDragDeltaEventArgs e) + { + var mousePositionOnHeaderItemsControl = Mouse.GetPosition(_dragablzItemsControl); + + Orientation? breachOrientation = null; + if (mousePositionOnHeaderItemsControl.X < -InterTabController.HorizontalPopoutGrace + || (mousePositionOnHeaderItemsControl.X - _dragablzItemsControl.ActualWidth) > InterTabController.HorizontalPopoutGrace) + breachOrientation = Orientation.Horizontal; + else if (mousePositionOnHeaderItemsControl.Y < -InterTabController.VerticalPopoutGrace + || (mousePositionOnHeaderItemsControl.Y - _dragablzItemsControl.ActualHeight) > InterTabController.VerticalPopoutGrace) + breachOrientation = Orientation.Vertical; + + if (!breachOrientation.HasValue) return; + + var newTabHost = InterTabController.InterTabClient.GetNewHost(InterTabController.InterTabClient, + InterTabController.Partition, this); + if (newTabHost?.TabablzControl == null || newTabHost.Container == null) + throw new ApplicationException("New tab host was not correctly provided"); + + var item = _dragablzItemsControl.ItemContainerGenerator.ItemFromContainer(e.DragablzItem); + var isTransposing = IsTransposing(newTabHost.TabablzControl); + + var myWindow = Window.GetWindow(this); + if (myWindow == null) throw new ApplicationException("Unable to find owning window."); + var dragStartWindowOffset = ConfigureNewHostSizeAndGetDragStartWindowOffset(myWindow, newTabHost, e.DragablzItem, isTransposing); + + var dragableItemHeaderPoint = e.DragablzItem.TranslatePoint(new Point(), _dragablzItemsControl); + var dragableItemSize = new Size(e.DragablzItem.ActualWidth, e.DragablzItem.ActualHeight); + var floatingItemSnapShots = this.VisualTreeDepthFirstTraversal() + .OfType() + .SelectMany(l => l.FloatingDragablzItems().Select(FloatingItemSnapShot.Take)) + .ToList(); + + var interTabTransfer = new InterTabTransfer(item, e.DragablzItem, breachOrientation.Value, dragStartWindowOffset, e.DragablzItem.MouseAtDragStart, dragableItemHeaderPoint, dragableItemSize, floatingItemSnapShots, isTransposing); + + if (myWindow.WindowState == WindowState.Maximized) + { + var desktopMousePosition = Native.GetCursorPos().ToWpf(); + newTabHost.Container.Left = desktopMousePosition.X - dragStartWindowOffset.X; + newTabHost.Container.Top = desktopMousePosition.Y - dragStartWindowOffset.Y; + } + else + { + newTabHost.Container.Left = myWindow.Left; + newTabHost.Container.Top = myWindow.Top; + } + newTabHost.Container.Show(); + var contentPresenter = FindChildContentPresenter(item); + + //stop the header shrinking if the tab stays open when empty + var minSize = EmptyHeaderSizingHint == EmptyHeaderSizingHint.PreviousTab + ? new Size(_dragablzItemsControl.ActualWidth, _dragablzItemsControl.ActualHeight) + : new Size(); + System.Diagnostics.Debug.WriteLine("B " + minSize); + + RemoveFromSource(item); + _itemsHolder.Children.Remove(contentPresenter); + if (Items.Count == 0) + { + _dragablzItemsControl.MinHeight = minSize.Height; + _dragablzItemsControl.MinWidth = minSize.Width; + + if (!DisableBranchConsolidation) + Layout.ConsolidateBranch(this); + } + + RestorePreviousSelection(); + + foreach (var dragablzItem in _dragablzItemsControl.DragablzItems()) + { + dragablzItem.IsDragging = false; + dragablzItem.IsSiblingDragging = false; + } + + newTabHost.TabablzControl.ReceiveDrag(interTabTransfer); + interTabTransfer.OriginatorContainer.IsDropTargetFound = true; + e.Cancel = true; + } + + private bool IsTransposing(TabControl target) + { + return IsVertical(this) != IsVertical(target); + } + + private static bool IsVertical(TabControl tabControl) + { + return tabControl.TabStripPlacement == Dock.Left + || tabControl.TabStripPlacement == Dock.Right; + } + + private void RestorePreviousSelection() + { + var previousSelection = _previousSelection?.Target; + if (previousSelection != null && Items.Contains(previousSelection)) + SelectedItem = previousSelection; + else + SelectedItem = Items.OfType().FirstOrDefault(); + } + + private Point ConfigureNewHostSizeAndGetDragStartWindowOffset(Window currentWindow, INewTabHost newTabHost, DragablzItem dragablzItem, bool isTransposing) + { + var layout = this.VisualTreeAncestory().OfType().FirstOrDefault(); + Point dragStartWindowOffset; + if (layout != null) + { + newTabHost.Container.Width = ActualWidth + Math.Max(0, currentWindow.RestoreBounds.Width - layout.ActualWidth); + newTabHost.Container.Height = ActualHeight + Math.Max(0, currentWindow.RestoreBounds.Height - layout.ActualHeight); + dragStartWindowOffset = dragablzItem.TranslatePoint(new Point(), this); + //dragStartWindowOffset.Offset(currentWindow.RestoreBounds.Width - layout.ActualWidth, currentWindow.RestoreBounds.Height - layout.ActualHeight); + } + else + { + if (newTabHost.Container.GetType() == currentWindow.GetType()) + { + newTabHost.Container.Width = currentWindow.RestoreBounds.Width; + newTabHost.Container.Height = currentWindow.RestoreBounds.Height; + dragStartWindowOffset = isTransposing ? new Point(dragablzItem.MouseAtDragStart.X, dragablzItem.MouseAtDragStart.Y) : dragablzItem.TranslatePoint(new Point(), currentWindow); + } + else + { + newTabHost.Container.Width = ActualWidth; + newTabHost.Container.Height = ActualHeight; + dragStartWindowOffset = isTransposing ? new Point() : dragablzItem.TranslatePoint(new Point(), this); + dragStartWindowOffset.Offset(dragablzItem.MouseAtDragStart.X, dragablzItem.MouseAtDragStart.Y); + return dragStartWindowOffset; + } + } + + dragStartWindowOffset.Offset(dragablzItem.MouseAtDragStart.X, dragablzItem.MouseAtDragStart.Y); + var borderVector = currentWindow.PointToScreen(new Point()).ToWpf() - new Point(currentWindow.GetActualLeft(), currentWindow.GetActualTop()); + dragStartWindowOffset.Offset(borderVector.X, borderVector.Y); + return dragStartWindowOffset; + } + + internal void ReceiveDrag(InterTabTransfer interTabTransfer) + { + var myWindow = Window.GetWindow(this); + if (myWindow == null) throw new ApplicationException("Unable to find owning window."); + myWindow.Activate(); + + _interTabTransfer = interTabTransfer; + + if (Items.Count == 0) + { + if (interTabTransfer.IsTransposing) + _dragablzItemsControl.LockedMeasure = new Size( + interTabTransfer.ItemSize.Width, + interTabTransfer.ItemSize.Height); + else + _dragablzItemsControl.LockedMeasure = new Size( + interTabTransfer.ItemPositionWithinHeader.X + interTabTransfer.ItemSize.Width, + interTabTransfer.ItemPositionWithinHeader.Y + interTabTransfer.ItemSize.Height); + } + + var lastFixedItem = _dragablzItemsControl.DragablzItems() + .OrderBy(i => i.LogicalIndex) + .Take(_dragablzItemsControl.FixedItemCount) + .LastOrDefault(); + + var lastItemEnd = _dragablzItemsControl.DragablzItems() + .Select(i => TabStripPlacement == Dock.Top || TabStripPlacement == Dock.Bottom + ? i.X + i.ActualWidth + : i.Y + i.ActualHeight) + .DefaultIfEmpty(0d) + .Max(); + + AddToSource(interTabTransfer.Item); + SelectedItem = interTabTransfer.Item; + + Dispatcher.BeginInvoke(new Action(() => Layout.RestoreFloatingItemSnapShots(this, interTabTransfer.FloatingItemSnapShots)), DispatcherPriority.Loaded); + _dragablzItemsControl.InstigateDrag(interTabTransfer.Item, newContainer => + { + newContainer.PartitionAtDragStart = interTabTransfer.OriginatorContainer.PartitionAtDragStart; + newContainer.IsDropTargetFound = true; + + if (interTabTransfer.TransferReason == InterTabTransferReason.Breach) + { + if (interTabTransfer.IsTransposing) + { + newContainer.Y = 0; + newContainer.X = 0; + } + else + { + newContainer.Y = interTabTransfer.OriginatorContainer.Y; + newContainer.X = interTabTransfer.OriginatorContainer.X; + } + } + else + { + if (TabStripPlacement == Dock.Top || TabStripPlacement == Dock.Bottom) + { + var mouseXOnItemsControl = Native.GetCursorPos().X - + _dragablzItemsControl.PointToScreen(new Point()).X; + var newX = mouseXOnItemsControl - interTabTransfer.DragStartItemOffset.X; + if (lastFixedItem != null) + { + newX = Math.Max(newX, lastFixedItem.X + lastFixedItem.ActualWidth); + } + //a drop on the empty part of the header must end up behind the last item + newX = MergeTargetCalculator.ClampInsertPosition(newX, + lastFixedItem != null ? lastFixedItem.X + lastFixedItem.ActualWidth : 0, lastItemEnd); + newContainer.X = newX; + newContainer.Y = 0; + } + else + { + var mouseYOnItemsControl = Native.GetCursorPos().Y - + _dragablzItemsControl.PointToScreen(new Point()).Y; + var newY = mouseYOnItemsControl - interTabTransfer.DragStartItemOffset.Y; + if (lastFixedItem != null) + { + newY = Math.Max(newY, lastFixedItem.Y + lastFixedItem.ActualHeight); + } + newY = MergeTargetCalculator.ClampInsertPosition(newY, + lastFixedItem != null ? lastFixedItem.Y + lastFixedItem.ActualHeight : 0, lastItemEnd); + newContainer.X = 0; + newContainer.Y = newY; + } + } + newContainer.MouseAtDragStart = interTabTransfer.DragStartItemOffset; + }); + } + + /// + /// generate a ContentPresenter for the selected item + /// + private void UpdateSelectedItem() + { + if (_itemsHolder == null) + { + return; + } + + CreateChildContentPresenter(SelectedItem); + + // show the right child + var selectedContent = GetContent(SelectedItem); + foreach (ContentPresenter child in _itemsHolder.Children) + { + var isSelected = (child.Content == selectedContent); + child.Visibility = isSelected ? Visibility.Visible : Visibility.Collapsed; + child.IsEnabled = isSelected; + } + } + + private static object GetContent(object item) + { + return (item is TabItem) ? ((TabItem)item).Content : item; + } + + /// + /// create the child ContentPresenter for the given item (could be data or a TabItem) + /// + /// + /// + private void CreateChildContentPresenter(object item) + { + if (item == null) return; + + var cp = FindChildContentPresenter(item); + if (cp != null) return; + + // the actual child to be added. cp.Tag is a reference to the TabItem + cp = new ContentPresenter + { + Content = GetContent(item), + ContentTemplate = ContentTemplate, + ContentTemplateSelector = ContentTemplateSelector, + ContentStringFormat = ContentStringFormat, + Visibility = Visibility.Collapsed, + }; + _itemsHolder.Children.Add(cp); + } + + /// + /// Find the CP for the given object. data could be a TabItem or a piece of data + /// + /// + /// + private ContentPresenter FindChildContentPresenter(object data) + { + if (data is TabItem) + data = ((TabItem)data).Content; + + return data == null + ? null + : _itemsHolder?.Children.Cast().FirstOrDefault(cp => cp.Content == data); + } + + private void ItemContainerGeneratorOnStatusChanged(object sender, EventArgs eventArgs) + { + MarkWrappedTabItems(); + MarkInitialSelection(); + } + + private static void CloseItem(DragablzItem item, TabablzControl owner) + { + if (item == null) + throw new ApplicationException("Valid DragablzItem to close is required."); + + if (owner == null) + throw new ApplicationException("Valid TabablzControl container is required."); + + if (!owner.IsMyItem(item)) + throw new ApplicationException("TabablzControl container must be an owner of the DragablzItem to close"); + + var cancel = false; + if (owner.ClosingItemCallback != null) + { + var callbackArgs = new ItemActionCallbackArgs(Window.GetWindow(owner), owner, item); + owner.ClosingItemCallback(callbackArgs); + cancel = callbackArgs.IsCancelled; + } + + if (!cancel) + owner.RemoveItem(item); + } + + private static void CloseItemCanExecuteClassHandler(object sender, CanExecuteRoutedEventArgs e) + { + e.CanExecute = FindOwner(e.Parameter, e.OriginalSource) != null; + } + private static void CloseItemClassHandler(object sender, ExecutedRoutedEventArgs e) + { + var owner = FindOwner(e.Parameter, e.OriginalSource); + + if (owner == null) throw new ApplicationException("Unable to ascertain DragablzItem to close."); + + CloseItem(owner.Item1, owner.Item2); + } + + private static Tuple FindOwner(object eventParameter, object eventOriginalSource) + { + var dragablzItem = eventParameter as DragablzItem; + if (dragablzItem == null) + { + var dependencyObject = eventOriginalSource as DependencyObject; + dragablzItem = dependencyObject.VisualTreeAncestory().OfType().FirstOrDefault(); + if (dragablzItem == null) + { + var popup = dependencyObject.LogicalTreeAncestory().OfType().LastOrDefault(); + if (popup?.PlacementTarget != null) + { + dragablzItem = popup.PlacementTarget.VisualTreeAncestory().OfType().FirstOrDefault(); + } + } + } + + if (dragablzItem == null) return null; + + var tabablzControl = LoadedInstances.FirstOrDefault(tc => tc.IsMyItem(dragablzItem)); + + return tabablzControl == null ? null : new Tuple(dragablzItem, tabablzControl); + } + + private void AddItemHandler(object sender, ExecutedRoutedEventArgs e) + { + if (NewItemFactory == null) + throw new InvalidOperationException("NewItemFactory must be provided."); + + var newItem = NewItemFactory(); + if (newItem == null) throw new ApplicationException("NewItemFactory returned null."); + + AddToSource(newItem); + SelectedItem = newItem; + + Dispatcher.BeginInvoke(new Action(_dragablzItemsControl.InvalidateMeasure), DispatcherPriority.Loaded); + } + + private void PrepareChildContainerForItemOverride(DependencyObject dependencyObject, object o) + { + var dragablzItem = dependencyObject as DragablzItem; + if (dragablzItem != null && HeaderMemberPath != null) + { + var contentBinding = new Binding(HeaderMemberPath) { Source = o }; + dragablzItem.SetBinding(ContentControl.ContentProperty, contentBinding); + dragablzItem.UnderlyingContent = o; + } + + SetIsWrappingTabItem(dependencyObject, o is TabItem); + } + } +} diff --git a/Source/3rdparty/Dragablz/TabablzHeaderSizeConverter.cs b/Source/3rdparty/Dragablz/TabablzHeaderSizeConverter.cs new file mode 100644 index 0000000000..cfd6fe7c5e --- /dev/null +++ b/Source/3rdparty/Dragablz/TabablzHeaderSizeConverter.cs @@ -0,0 +1,50 @@ +using System; +using System.Globalization; +using System.Linq; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Media; + +namespace Dragablz +{ + /// + /// Provides a little help for sizing the header panel in the tab control + /// + public class TabablzHeaderSizeConverter : IMultiValueConverter + { + public Orientation Orientation { get; set; } + + /// + /// The first value should be the total size available size, typically the parent control size. + /// The second value should be from or (height equivalent) + /// All additional values should be siblings sizes (width or height) which will affect (reduce) the available size. + /// + /// + /// + /// + /// + /// + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) + { + if (values == null) throw new ArgumentNullException("values"); + + if (values.Length < 2) return Binding.DoNothing; + + var val = values + .Skip(2) + .OfType() + .Where(d => !double.IsInfinity(d) && !double.IsNaN(d)) + .Aggregate(values.OfType().First(), (current, diminish) => current - diminish); + + var maxWidth = values.Take(2).OfType().Min(); + + return Math.Min(Math.Max(val, 0), maxWidth); + } + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/TabablzItemStyleSelector.cs b/Source/3rdparty/Dragablz/TabablzItemStyleSelector.cs new file mode 100644 index 0000000000..6085b76c5f --- /dev/null +++ b/Source/3rdparty/Dragablz/TabablzItemStyleSelector.cs @@ -0,0 +1,27 @@ +using System.Windows; +using System.Windows.Controls; + +namespace Dragablz +{ + /// + /// Selects style to apply to a according to the tab item content itself. + /// + public class TabablzItemStyleSelector : StyleSelector + { + private readonly Style _defaultHeaderItemStyle; + private readonly Style _customHeaderItemStyle; + + public TabablzItemStyleSelector(Style defaultHeaderItemStyle, Style customHeaderItemStyle) + { + _defaultHeaderItemStyle = defaultHeaderItemStyle; + _customHeaderItemStyle = customHeaderItemStyle; + } + + public override Style SelectStyle(object item, DependencyObject container) + { + if (item is TabItem) return _defaultHeaderItemStyle; + + return _customHeaderItemStyle; + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Themes/BrushToRadialGradientBrushConverter.cs b/Source/3rdparty/Dragablz/Themes/BrushToRadialGradientBrushConverter.cs new file mode 100644 index 0000000000..1e041c6065 --- /dev/null +++ b/Source/3rdparty/Dragablz/Themes/BrushToRadialGradientBrushConverter.cs @@ -0,0 +1,31 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Media; + +namespace Dragablz.Themes +{ + public class BrushToRadialGradientBrushConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + var solidColorBrush = value as SolidColorBrush; + if (solidColorBrush == null) return Binding.DoNothing; + + return new RadialGradientBrush(solidColorBrush.Color, Colors.Transparent) + { + Center = new Point(.5, .5), + GradientOrigin = new Point(.5, .5), + RadiusX = .5, + RadiusY = .5, + Opacity = .39 + }; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + return Binding.DoNothing; + } + } +} \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Themes/Dockablz.xaml b/Source/3rdparty/Dragablz/Themes/Dockablz.xaml new file mode 100644 index 0000000000..825049e38d --- /dev/null +++ b/Source/3rdparty/Dragablz/Themes/Dockablz.xaml @@ -0,0 +1,8 @@ + + + + + \ No newline at end of file diff --git a/Source/3rdparty/Dragablz/Themes/Generic.xaml b/Source/3rdparty/Dragablz/Themes/Generic.xaml new file mode 100644 index 0000000000..902ce4019c --- /dev/null +++ b/Source/3rdparty/Dragablz/Themes/Generic.xaml @@ -0,0 +1,1980 @@ + + + + + + + + + + + + + + + #e04343 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +