diff --git a/.claude/skills/feature-review/SKILL.md b/.claude/skills/feature-review/SKILL.md index 42395206e2..95e015e524 100644 --- a/.claude/skills/feature-review/SKILL.md +++ b/.claude/skills/feature-review/SKILL.md @@ -237,4 +237,5 @@ When fixing: the manual Windows tests of the handover file. - Add strings to `Strings.resx` and, in alphabetical order, to `Strings.Designer.cs`. - Update the feature documentation and add a changelog entry in `Website/docs/changelog/next-release.md`. -- Never modify `Source/3rdparty/`. +- Change `Source/3rdparty/Dragablz` only when the fix needs it: keep it small, don't reformat, add an entry to its + `CHANGELOG.md` (see AGENTS.md). diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 48a570cee5..7f90ff15ad 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -40,7 +40,7 @@ Closes # - [ ] The [documentation](https://github.com/BornToBeRoot/NETworkManager/tree/main/Website/docs) is updated (if needed). - [ ] An entry is added to the [changelog](https://github.com/BornToBeRoot/NETworkManager/blob/main/Website/docs/changelog/next-release.md). - [ ] New texts are only added to `Strings.resx` (translations are done on [Transifex](https://app.transifex.com/BornToBeRoot/NETworkManager/dashboard/)). -- [ ] No files in `Source/3rdparty/` are changed. +- [ ] Changes in `Source/3rdparty/` (if any) are needed and listed in the `CHANGELOG.md` of that library. ## Contributing diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 7a00dd98f0..0126682f98 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -33,8 +33,6 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@v7 - with: - submodules: 'true' # The C# autobuild needs the SDK from Source/global.json (the runner image may only have an older one) - name: Setup .NET 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/AGENTS.md b/AGENTS.md index c9c1e11759..66a726bd65 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,8 +34,8 @@ REPOSITORY_ROOT/ │ ├── NETworkManager.Documentation/ # Documentation resources │ ├── NETworkManager.Setup/ # WiX installer project │ ├── NETworkManager.Tests/ # xUnit unit tests (run by AppVeyor) -│ └── 3rdparty/ # Third-party dependencies (Dragablz: submodule of the fork BornToBeRoot/Dragablz) -│ └── (managed-manually) # NOTE: Maintained manually — AI agents MUST NOT modify this directory +│ └── 3rdparty/ # Third-party source code maintained in this repository +│ └── Dragablz/ # Dragablz (MIT), stripped to what we use - see its README.md / CHANGELOG.md ├── Website/ # Docusaurus documentation website ├── Scripts/ # Build and automation scripts │ ├── Create-FlagFromSVG.ps1 # Create flag images @@ -82,7 +82,7 @@ REPOSITORY_ROOT/ `Source/NETworkManager.Controls/LucideIcons.cs` (only the used icons, see `$Icons` in the script) and drawn as lines by `LucideIcon` (stroke 1.75); license in `Source/NETworkManager.Documentation/Licenses/Lucide.txt` - **MahApps.Metro.SimpleChildWindow** - Dialog windows -- **Dragablz** - Tearable/draggable tab control +- **Dragablz** - Tearable/draggable tab control (source in `Source/3rdparty/Dragablz`, modified) - **GongSolutions.Wpf.DragDrop** (`gong-wpf-dragdrop`) - Drag and drop framework - **Progress / loading** - MahApps `MetroProgressBar` (style `DefaultMetroProgressBar`) and `ProgressRing` in three sizes (`ProgressRingSmall` 16 inline, `ProgressRingMedium` 24 dialogs, `ProgressRingLarge` 48 centered), see @@ -160,11 +160,9 @@ Website/ ### Building the Application -**Clone with Submodules**: +**Clone**: ```powershell git clone https://github.com/BornToBeRoot/NETworkManager.git -cd NETworkManager -git submodule update --init --recursive ``` **Build via Visual Studio/Rider**: @@ -378,7 +376,7 @@ The website is deployed to GitHub Pages at: https://borntoberoot.net/NETworkMana - **`.github/dependabot.yml`**: Dependabot configuration - **`.github/mergify.yml`**: Mergify auto-merge configuration - **`.github/transifex.yml`**: Transifex translation sync configuration -- **`.gitmodules`**: Git submodule configuration (Dragablz) +- **`Source/3rdparty/Dragablz/`**: Dragablz source (`LICENSE`, origin in `README.md`, changes in `CHANGELOG.md`) - **`Website/docusaurus.config.js`**: Documentation site configuration - **`Website/docs/changelog/next-release.md`**: Changelog of the upcoming release - **`.claude/skills/feature-review/`**: Feature review skill incl. the app's conventions (`references/conventions.md`) @@ -426,9 +424,6 @@ npm run clear # or yarn clear ### Git Operations ```powershell -# Update submodules -git submodule update --init --recursive - # Check status git status @@ -554,7 +549,7 @@ SemiBold (section headers), `MessageTextBlock` 16 gray (messages in empty areas) `DragablzTabHeaderBorder` / `Title` / `CloseIcon` / `AccentLine` in `DragablzStyles.xaml` - change the tab look only there); a single tab is shown as the view title. Dragged-out tabs merge on the whole tab bar (`MergeTargetArea="HeaderPanel"`) and the target tab bars show a slot (`ShowMergeHint`, `MergeHintTemplate` in - `DefaultTabablzControl`) - features of our Dragablz fork (BornToBeRoot/Dragablz, submodule). + `DefaultTabablzControl`) - features of our modified Dragablz (`Source/3rdparty/Dragablz`). - Data grids: row height 30, semibold headers, accent-tinted selection. - Windows have rounded corners on Windows 11 (`WindowCornerHelper.RoundCorners`, DWM). @@ -592,7 +587,8 @@ see `.claude/skills/feature-review/references/conventions.md`. content transitions** when switching tools; check `AppearanceManager.AnimationsEnabled` when an animation starts): `ChildWindowAnimation` (dialogs zoom 92 → 100 %, run command `Kind="SlideDown"`), `SelectionIndicatorAnimation` (navigation indicator), `ExpanderAnimation` (chevron rotates, content fades in; `SwapChevron` for the profile panel), -`SmoothProgress`, notification slide-in. Short color / opacity fades in XAML storyboards (button and navigation hover / +`SmoothProgress`, notification slide-in, tab reorder slide while a tab is dragged (Dragablz `StackOrganiser`, +`Canvas.Left` - exception to the `RenderTransform` rule, switch `StackOrganiser.AnimationsEnabled` set in `App.xaml.cs`). Short color / opacity fades in XAML storyboards (button and navigation hover / pressed layers, tooltip, dialog overlay) don't move anything and are always shown (documented in the Animations setting). Native windows (Remote Desktop, PuTTY, PowerShell, TigerVNC, WebView2) can't be animated, clipped or put in transparent windows. @@ -639,8 +635,12 @@ WebView2) can't be animated, clipped or put in transparent windows. 5. **Update Documentation**: Changes to features should include doc updates and a changelog entry in `Website/docs/changelog/next-release.md` 6. **Test on Real Networks**: Network tools require real network testing 7. **Version Management**: Assembly version is auto-generated in CI/CD -8. **Submodules**: Remember to init/update submodules (Dragablz in `Source/3rdparty/`) -9. **DO NOT Modify 3rdparty**: The `Source/3rdparty/` directory contains the Dragablz submodule and is maintained manually — AI agents MUST NOT modify this directory +8. **3rdparty (Dragablz)**: `Source/3rdparty/Dragablz` is the Dragablz library (MIT), maintained in this repository. + Change it only when a feature or fix needs it, keep the changes small, don't reformat / restyle the code, add an + entry to its `CHANGELOG.md` and keep its `LICENSE` +9. **Third-party licenses**: Code or libraries from other projects need their license in + `Source/NETworkManager.Documentation/Licenses/` (+ `Content` entry in the csproj), an entry in `LibraryManager` and in + the README; embedded single files also keep the license header (e.g. `AirspacePanel.cs`) 10. **Automation Scripts**: Use scripts in `Scripts/` directory for updating lists (OUI, ports, WHOIS servers) 11. **Check CI Status**: Both AppVeyor (main build) and GitHub Actions (CodeQL, website) must pass 12. **Dependency Updates**: Dependabot automatically creates PRs for dependency updates diff --git a/README.md b/README.md index 3bfb808562..0ada62e946 100644 --- a/README.md +++ b/README.md @@ -179,12 +179,9 @@ Build NETworkManager yourself with these steps: 2. **Clone the Repository**: - - Clone with submodules: - ```powershell - git clone https://github.com/BornToBeRoot/NETworkManager.git - cd NETworkManager - git submodule update --init --recursive - ``` + ```powershell + git clone https://github.com/BornToBeRoot/NETworkManager.git + ``` 3. **Build**: - Open `.\Source\NETworkManager.sln` in Visual Studio or JetBrains Rider. @@ -213,7 +210,7 @@ A huge thank you to our supporters and contributors who make NETworkManager poss - [ControlzEx](https://github.com/ControlzEx/ControlzEx) - Shared Controlz for WPF and more. - [DnsClient.NET](https://github.com/MichaCo/DnsClient.NET) - Powerful, high-performance open-source library for DNS lookups. - [Docusaurus](https://docusaurus.io/) - Easy to maintain open source documentation websites. - - [Dragablz](https://dragablz.net/) - Tearable TabControl for WPF. + - [Dragablz](https://github.com/ButchersBoy/Dragablz) - Tearable TabControl for WPF (modified, included in `Source/3rdparty/Dragablz`). - [GongSolutions.Wpf.DragDrop](https://github.com/punker76/gong-wpf-dragdrop) - An easy to use drag'n'drop framework for WPF. - [IPNetwork](https://github.com/lduchosal/ipnetwork) - .NET library for complex network, IP, and subnet calculations. - [LiveCharts2](https://github.com/Live-Charts/LiveCharts2) - Beautiful, interactive charts, maps, and gauges. 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..ab68bb2d2e --- /dev/null +++ b/Source/3rdparty/Dragablz/CHANGELOG.md @@ -0,0 +1,117 @@ +# 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`) + +- Every removed item (closed, dragged out, merged, consolidated) gets all its `ContentPresenter`s removed in + `OnItemsChanged` (instead of only in `RemoveItem` / `MonitorBreach`); no presenter for an item without content (a new + one was added on every selection change). +- Fix (tear out, `HeaderPanel`): no grace beyond the header panel horizontally - in a maximized window it reaches the + screen edge, the cursor couldn't get past it and a tab could only be torn out vertically. +- Fix: a tab grabbed while it still slid (right after the previous drag) didn't follow the cursor and snapped back to + the old slide target - `OrganiseOnDragStarted` stops the slide of the dragged item. +- Fix: the content of a removed tab could stay visible without a tab (e.g. merged and torn out again right away): while + the item was removed, a stale `SelectedItem` created a new `ContentPresenter` for it, which was never removed. + `CreateChildContentPresenter` skips items that are no longer in the control, `RemoveItem` / `MonitorBreach` remove + every presenter of the item. +- Fix (merge area, `MergeTargetArea.HeaderPanel`): a tab merged into the empty part of the tab bar (e.g. an empty bar, + where it is placed at the start) was torn out again at once - `MonitorBreach` measured against the area of the tabs. + With `HeaderPanel`, a tab is now only torn out when it leaves the whole tab bar (the area that accepts it). +- Removed `DragablzColors` and the undocumented DWM call (`DwmGetColorizationParameters`, `Core/Native.cs`): the hover + background of the default add / menu buttons (not shown by NETworkManager) uses `SystemColors.ActiveCaptionBrush`. +- Fix (right click): a second right click while waiting for the button up saved the disabled thumb as the state to + restore (tab no longer draggable), and a thumb replaced meanwhile (custom thumb) was re-enabled. +- Fix: `StackOrganiser.Organise` sorted by X / Y instead of the target of a running slide - an Organise during a slide + restored the old order. `ForgetItem` is part of `IItemsOrganiser` (default no-op) instead of a `StackOrganiser` cast. +- `DragablzItem.OnPreviewMouseRightButtonDown` (fix for the right click lock, see the fork): calls `base` before the + wait instead of after the routing, restores the thumb it disabled (local) and documents why it polls the button. +- Removed the MahApps theme (`Themes/MahApps.xaml`): NETworkManager uses its own invisible thumb style and focus visual + (`FocusVisual.Ring` instead of the dotted MahApps one). The `Foreground` of `MahAppsTabablzControlStyle` (theme + background - the inverted color for the tab content) is dropped. +- Removed more dead code: `Dockablz/FloatRequestedEvent.cs`, the window-only colors of `DragablzColors` + (`WindowGlassBalancedBrush`, `WindowInactiveBrush`, `WindowBaseColor` and their helpers, incl. a second DWM call in + the static initializer) and unused usings. +- Fix (`StackOrganiser` slides): a drag back to the original location during a running slide was ignored (compared + with X / Y instead of the slide target); a direct placement (e.g. after a tab was dragged out) or "animations off" + didn't stop a running slide to another location (gap, motion); a removed item stayed in the organiser until the + next drag (now `ForgetItem`, called by `DragablzItemsControl.ClearContainerForItemOverride`). The running slide is + tracked per item; the start locations of a drag are still one field per organiser, so an organiser shared by several + controls (e.g. the `VerticalOrganiser` of the vertical tab style) can still mix them. +- Removed dead code: the unused static `ContinuationIndex` (`StoryboardCompletionListener`), the right mouse up + disposable of `DragablzItem` (only ever set to empty), a `Debug.WriteLine` in `MonitorBreach` and the empty + `ItemsChanged` handler of `DragablzItemsControl`. +- Removed the unused tab styles of `Generic.xaml` (`TrapezoidDragableTabItemStyle`, + `SizableFromBottomRightDragablzItemStyle`, `CloseItemCommandButtonStyle`, `CloseCommandHighlightColor`), the + `Trapezoid` control and `ShowDefaultCloseButtonConverter`. +- Fix: the splitter between branches stacked on top of each other reached 3 px into the neighbouring branches on the + left and right (`Margin="-3,-3"` instead of `"0,-3"`, from the wider hit area of the fork). +- `StackOrganiser.AnimationsEnabled` (static, set by NETworkManager from Settings > Appearance > Animations): without + animations the items are moved directly instead of sliding; the slide uses a quadratic instead of a cubic ease-out. +- Fix: when a tab's slide animation was replaced by a newer one (tab dragged back and forth), the completion of the old + one set the old location and removed the newer target (`StackOrganiser.SendToLocation`). +- Fix: `StackOrganiser` kept the start locations of the last drag (items and their window alive) and threw a + `KeyNotFoundException` for an item added during a drag. The state is now cleared after the drag, which also makes a + shared organiser (e.g. the `VerticalOrganiser` of the vertical tab style) harmless. +- Fix: a tab dropped on a drop zone whose window closed during the drag was moved into the closed window (lost). +- Fix: the static `CloseItem(object)` threw for tab controls without an applied template or tabs without content, and + closed the tabs while enumerating them (collection modified). +- Fix: `NullReferenceException` in `RemoveItem` when the `InterTabClient` of the controller is `null` (binding without + value) or the template has no items holder. +- Fix: all tab controls shared one `HorizontalOrganiser` (default value of `HeaderItemsOrganiser`, used unless + `AdjacentHeaderItemOffset` changes), which kept the items of the last drag (and their window) alive and mixed the drag + state of different controls. Each `TabablzControl` now gets its own. +- Fix: a tab merged into another tab control was inserted at the wrong position above 100 % display scaling + (`ReceiveDrag` mixed screen pixels and DIPs). +- Fix: crash (`InvalidOperationException` in `PointToScreen`) while a tab is dragged as a window and another window + with a merge target closes; hidden tab controls are no longer merge targets (`GetMergeTargetScreenBounds`). +- Fix: the drop zone offered during a drag (`Layout`) was not reset when the drag ended with a merge into another tab + control or in a tab control with more than one item. The next drag of a single tab could branch into the stale + zone - also of a closed window (tab lost) - and the static reference kept that window alive. +- `Themes/MahApps.xaml` reduced to the styles NETworkManager uses: `MahAppsFocusVisual`, `MahAppsInvisibleThumbStyle` + and `MahAppsTabablzControlStyle` (without `ItemContainerStyle` and the trapezoid offset + `AdjacentHeaderItemOffset=-12`, NETworkManager sets its own). Removed the converters, + button, trapezoid tab and tool window styles. +- Removed unused code: `HeaderedItemViewModel`, `TabablzItemStyleSelector`, + `HorizontalPositionMonitor` / `VerticalPositionMonitor`, `Core/HitTest.cs` and the empty project template files + `Properties/Resources.*` / `Properties/Settings.*`. +- Removed the custom window `DragablzWindow` (NETworkManager uses MahApps windows) with `DragablzIcon`, the internal + `SystemCommand` / `WindowMessage` enums, the window-only natives in `Core/Native.cs` + (`SendMessage`, `PostMessage`, `SetWindowPlacement`, `WINDOWPLACEMENT`, `RECT`, `GetRawCursorPos`) and their + styles in `Generic.xaml` (`DragablzIcon`, `WindowTemplateKey`, `DragablzWindow`, `CloseMenuCommandButtonStyle`). +- Removed the MaterialDesign theme (`Themes/MaterialDesign.xaml`, `MaterialDesignAssist`, + `BrushToRadialGradientBrushConverter`), the `Ripple` control (`Ripple`, `RippleAssist`, its style in `Generic.xaml`) + used only by that theme, and the empty `Themes/Dockablz.xaml`. +- 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`). Most of these styles were + removed later (see the `MahApps.xaml` reduction above). +- 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/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/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..f54e235263 --- /dev/null +++ b/Source/3rdparty/Dragablz/Core/Native.cs @@ -0,0 +1,77 @@ +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); + } + } + + [DllImport("user32.dll")] + private static extern bool GetCursorPos(out POINT 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]; + } + + 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); + } +} 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/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/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..e2aa66ebe3 --- /dev/null +++ b/Source/3rdparty/Dragablz/Dockablz/Layout.cs @@ -0,0 +1,1006 @@ +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; + + //NETworkManager: always reset the offered drop zone, also when the drag ended with a merge (IsDropTargetFound) + //or in a tab control with more items - a stale zone was used by the next drag (branch into a closed window) + var offeredDropZone = _currentlyOfferedDropZone; + _currentlyOfferedDropZone = null; + if (offeredDropZone == null) return; + offeredDropZone.Item2.IsOffered = false; + + //NETworkManager: the layout of the offered zone can be unloaded during the drag (its window closed) - a branch + //into it would move the item into the closed window + if (e.DragablzItem.IsDropTargetFound || !LoadedLayouts.Contains(offeredDropZone.Item1)) return; + + TabablzControl tabablzControl; + if (TryGetSourceTabControl(e.DragablzItem, out tabablzControl)) + { + if (tabablzControl.Items.Count > 1) return; + + if (offeredDropZone.Item2.Location == DropZoneLocation.Floating) + Float(offeredDropZone.Item1, e.DragablzItem); + else + offeredDropZone.Item1.Branch(offeredDropZone.Item2.Location, e.DragablzItem); + } + } + + 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/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/DragablzItem.cs b/Source/3rdparty/Dragablz/DragablzItem.cs new file mode 100644 index 0000000000..60047c42bf --- /dev/null +++ b/Source/3rdparty/Dragablz/DragablzItem.cs @@ -0,0 +1,646 @@ +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 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) + { + //NETworkManager: base before the await (afterwards the event is already routed), the thumb kept in a local + //(the template can change while the button is pressed). Polling instead of PreviewMouseRightButtonUp: a + //context menu opened by the right click gets the button up, the thumb would stay disabled (no drag). + base.OnPreviewMouseRightButtonDown(e); + + //a second right click while waiting would save the disabled state as the one to restore + var thumb = _thumb; + if (thumb == null || _isWaitingForRightButtonUp) return; + + _isWaitingForRightButtonUp = true; + var currentThumbIsHitTestVisible = thumb.IsHitTestVisible; + thumb.SetCurrentValue(IsHitTestVisibleProperty, false); + + try + { + while (Mouse.RightButton == MouseButtonState.Pressed) + await Task.Delay(25); + } + finally + { + _isWaitingForRightButtonUp = false; + } + + //only if the thumb is still the active one (the custom thumb can replace the template thumb meanwhile, which + //disables the template thumb on purpose) + if (ReferenceEquals(thumb, _thumb)) + thumb.SetCurrentValue(IsHitTestVisibleProperty, currentThumbIsHitTestVisible); + } + + private bool _isWaitingForRightButtonUp; + + 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..9ef394da31 --- /dev/null +++ b/Source/3rdparty/Dragablz/DragablzItemsControl.cs @@ -0,0 +1,397 @@ +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; + 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); } + } + + 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; + //NETworkManager: the organiser must not keep the removed item (slide, drag state) + ItemsOrganiser?.ForgetItem((DragablzItem)element); + + 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/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/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/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..764b9c7d0d --- /dev/null +++ b/Source/3rdparty/Dragablz/IItemsOrganiser.cs @@ -0,0 +1,27 @@ +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); + + /// + /// NETworkManager: the container of the item was removed (tab closed, dragged out or merged) - release all state + /// kept for it, so the organiser doesn't keep it (and its window) alive. + /// + void ForgetItem(DragablzItem dragablzItem) { } + } +} 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/README.md b/Source/3rdparty/Dragablz/README.md new file mode 100644 index 0000000000..eb2a40b67d --- /dev/null +++ b/Source/3rdparty/Dragablz/README.md @@ -0,0 +1,38 @@ +# 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` in the +application stay unchanged. The default styles come from `Themes/Generic.xaml`; the look of the tabs is defined in +NETworkManager (`Resources/Styles/DragablzStyles.xaml`). + +## 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, which only silences the + analyzers - "Format Document" / `dotnet format` would still reformat it, so don't run them on this folder. +- 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`). + +## Existing clones (with the old submodule) + +Switching to a commit with this folder fails with "untracked working tree files would be overwritten" while the old +submodule is still checked out. Remove it once, then pull / switch again: + +```powershell +git submodule deinit -f Source/3rdparty/Dragablz +Remove-Item -Recurse -Force .git/modules/Source/3rdparty/Dragablz, Source/3rdparty/Dragablz +``` 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..ccaad94517 --- /dev/null +++ b/Source/3rdparty/Dragablz/StackOrganiser.cs @@ -0,0 +1,380 @@ +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(); + + //NETworkManager: the running slide per item, to stop it when the item is placed directly or removed + private readonly Dictionary _activeStoryboards = + 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, + //NETworkManager: the target of a running slide, not X / Y (still the old location) - otherwise + //an Organise during a slide restores the old order (SetLocation stops the slide) + MultiComparer>.Ascending(tuple => GetLocationInfo(tuple.Item2).Start) + .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; + + //NETworkManager: an item added during the drag has no start location (KeyNotFoundException) - use its current one + private double GetStartOnDragStart(LocationInfo location) + { + LocationInfo locationOnDragStart; + return _siblingItemLocationOnDragStart != null && + _siblingItemLocationOnDragStart.TryGetValue(location.Item, out locationOnDragStart) + ? locationOnDragStart.Start + : location.Start; + } + + 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"); + + //NETworkManager: a tab grabbed while it still slides (e.g. right after the previous drag) must follow the + //cursor - the slide would hold Canvas.Left and set its old target on completion + StopSlide(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 : GetStartOnDragStart(loc)); + + 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 : GetStartOnDragStart(loc)); + + 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); + + //NETworkManager: don't keep the items (and their window) of the last drag alive + _siblingItemLocationOnDragStart = null; + } + + 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) + { + //NETworkManager: a slide to another location would end there later (e.g. a gap after a tab was dragged out) + double activeTarget; + if (_activeStoryboardTargetLocations.TryGetValue(dragablzItem, out activeTarget) && + Math.Abs(activeTarget - location) >= 1.0) + StopSlide(dragablzItem); + _setLocation(dragablzItem, location); + } + + private void StopSlide(DragablzItem dragablzItem) + { + Storyboard storyboard; + if (_activeStoryboards.TryGetValue(dragablzItem, out storyboard)) + storyboard.Remove(dragablzItem); + _activeStoryboards.Remove(dragablzItem); + _activeStoryboardTargetLocations.Remove(dragablzItem); + } + + /// + /// NETworkManager: called when the container of an item is removed (tab closed, dragged out or merged) - stops its + /// slide and forgets the item, so the organiser doesn't keep it (and its window) alive. + /// + public virtual void ForgetItem(DragablzItem dragablzItem) + { + StopSlide(dragablzItem); + if (_siblingItemLocationOnDragStart != null) + _siblingItemLocationOnDragStart.Remove(dragablzItem); + } + + /// + /// NETworkManager: whether the items slide to their new location while a tab is dragged (checked each time an item + /// moves). null = always. Set by the application (Appearance > Animations). + /// + public static Func AnimationsEnabled { get; set; } + + private void SendToLocation(DragablzItem dragablzItem, double location) + { + if (AnimationsEnabled != null && !AnimationsEnabled()) + { + StopSlide(dragablzItem); + _setLocation(dragablzItem, location); + return; + } + + //NETworkManager: compare with the target of a running slide (X / Y only change when it completes), otherwise + //a drag back to the original location during the slide was ignored + double activeTarget; + var hasActiveTarget = _activeStoryboardTargetLocations.TryGetValue(dragablzItem, out activeTarget); + if (Math.Abs((hasActiveTarget ? activeTarget : _getLocation(dragablzItem)) - location) < 1.0) + return; + + _activeStoryboardTargetLocations[dragablzItem] = location; + + var storyboard = new Storyboard { FillBehavior = FillBehavior.Stop }; + _activeStoryboards[dragablzItem] = storyboard; + storyboard.WhenComplete(sb => + { + //NETworkManager: a storyboard replaced by a newer one (or stopped) must not set its location or remove + //the newer target + Storyboard activeStoryboard; + if (!_activeStoryboards.TryGetValue(dragablzItem, out activeStoryboard) || + !ReferenceEquals(activeStoryboard, sb)) + { + sb.Remove(dragablzItem); + return; + } + _setLocation(dragablzItem, location); + sb.Remove(dragablzItem); + _activeStoryboards.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))) + { + //NETworkManager: quadratic ease-out like the other animations of the application + EasingFunction = new QuadraticEase() { 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..c428bb72b4 --- /dev/null +++ b/Source/3rdparty/Dragablz/StoryboardCompletionListener.cs @@ -0,0 +1,37 @@ +using System; +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 + { + 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..81fd3441a4 --- /dev/null +++ b/Source/3rdparty/Dragablz/TabablzControl.cs @@ -0,0 +1,1858 @@ +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)); + + //NETworkManager: own organiser per control - the default value of HeaderItemsOrganiser is one instance shared + //by all controls (it keeps the items of the last drag, and their window, alive and mixes the drag state of + //different controls). SetCurrentValue keeps styles / triggers (e.g. VerticalOrganiser) working. + SetCurrentValue(HeaderItemsOrganiserProperty, new HorizontalOrganiser()); + + 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 + //NETworkManager: skip controls without template (visible instances can be not loaded yet), items without content + GetLoadedInstances().Where(tc => tc._dragablzItemsControl != null).SelectMany(tc => + tc._dragablzItemsControl.DragablzItems().Where(di => Equals(di.Content, tabContentItem)).Select(di => new { tc, di })).ToList()) + { + 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: + //NETworkManager: all presenters of the item (see RemoveChildContentPresenters) + foreach (var item in e.OldItems) + RemoveChildContentPresenters(item); + + 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; + + //NETworkManager: a target can be hidden or its window closed during the drag (the targets are collected at + //the start) - PointToScreen throws without a PresentationSource + if (!IsVisible || PresentationSource.FromVisual(_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); + + //NETworkManager: InterTabClient can be null (binding to a view model property without a value) + if (window == null || InterTabController?.InterTabClient == 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) + { + //NETworkManager: with MergeTargetArea.HeaderPanel the whole tab bar accepts a tab, so only leaving the tab bar + //tears it out - with the area of the tabs, a tab merged into the empty part of the bar (e.g. an empty bar, + //where it is placed at the start) was torn out again at once + FrameworkElement breachArea = MergeTargetArea == MergeTargetArea.HeaderPanel && _headerPanel != null && + _headerPanel.IsVisible + ? _headerPanel + : _dragablzItemsControl; + var mousePositionOnBreachArea = Mouse.GetPosition(breachArea); + //the header panel can reach the screen edge (maximized window) - no grace beyond it, the cursor can't get there + var horizontalGrace = ReferenceEquals(breachArea, _headerPanel) ? 0 : InterTabController.HorizontalPopoutGrace; + + Orientation? breachOrientation = null; + if (mousePositionOnBreachArea.X < -horizontalGrace + || (mousePositionOnBreachArea.X - breachArea.ActualWidth) > horizontalGrace) + breachOrientation = Orientation.Horizontal; + else if (mousePositionOnBreachArea.Y < -InterTabController.VerticalPopoutGrace + || (mousePositionOnBreachArea.Y - breachArea.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(); + + 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) + { + //NETworkManager: PointFromScreen converts the screen pixels to DIPs (the difference of two screen + //positions is in pixels, but X / Y of the items are DIPs - wrong position above 100 % scaling) + var mouseXOnItemsControl = _dragablzItemsControl.PointFromScreen(Native.GetCursorPos()).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 + { + //NETworkManager: PointFromScreen converts the screen pixels to DIPs (the difference of two screen + //positions is in pixels, but X / Y of the items are DIPs - wrong position above 100 % scaling) + var mouseYOnItemsControl = _dragablzItemsControl.PointFromScreen(Native.GetCursorPos()).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) + { + //NETworkManager: not for an item that is no longer in the control (a stale SelectedItem while the item is + //removed, e.g. merged and torn out again) - its content would stay visible without a tab + //no presenter for an item without content either: FindChildContentPresenter can't find it, a new one would + //be added on every selection change + if (item == null || !Items.Contains(item) || GetContent(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); + } + + /// + /// NETworkManager: removes every ContentPresenter of the item - called for every removed item + /// (), whichever way it was removed (closed, dragged out, merged, consolidated). + /// + private void RemoveChildContentPresenters(object item) + { + if (_itemsHolder == null) return; + + var content = GetContent(item); + if (content == null) return; + + foreach (var cp in _itemsHolder.Children.OfType().Where(cp => cp.Content == content).ToList()) + _itemsHolder.Children.Remove(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/Themes/Generic.xaml b/Source/3rdparty/Dragablz/Themes/Generic.xaml new file mode 100644 index 0000000000..332bfe8b77 --- /dev/null +++ b/Source/3rdparty/Dragablz/Themes/Generic.xaml @@ -0,0 +1,1538 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +